virtual void ConvertFromUTF16(const url_parse::UTF16Char* input, int inputLength, url_canon::CanonOutput* output) { CString encoded = m_encoding->encode(input, inputLength, URLEncodedEntitiesForUnencodables); output->Append(encoded.data(), static_cast<int>(encoded.length())); }
void WebPreferences::migrateWebKitPreferencesToCFPreferences() { CFStringRef didMigrateKey = CFSTR(WebKitDidMigrateWebKitPreferencesToCFPreferencesPreferenceKey); if (boolValueForKey(didMigrateKey)) return; bool oldValue = m_autoSaves; m_autoSaves = true; setBoolValue(didMigrateKey, TRUE); m_autoSaves = oldValue; CString path = oldPreferencesPath().utf8(); RetainPtr<CFURLRef> urlRef(AdoptCF, CFURLCreateFromFileSystemRepresentation(0, reinterpret_cast<const UInt8*>(path.data()), path.length(), false)); if (!urlRef) return; RetainPtr<CFReadStreamRef> stream(AdoptCF, CFReadStreamCreateWithFile(0, urlRef.get())); if (!stream) return; if (!CFReadStreamOpen(stream.get())) return; CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0 | kCFPropertyListXMLFormat_v1_0; RetainPtr<CFPropertyListRef> plist(AdoptCF, CFPropertyListCreateFromStream(0, stream.get(), 0, kCFPropertyListMutableContainersAndLeaves, &format, 0)); CFReadStreamClose(stream.get()); if (!plist || CFGetTypeID(plist.get()) != CFDictionaryGetTypeID()) return; copyWebKitPreferencesToCFPreferences(static_cast<CFDictionaryRef>(plist.get())); deleteFile(oldPreferencesPath()); }
void PageSerializer::serializeFrame(Frame* frame) { Document* document = frame->document(); KURL url = document->url(); if (!url.isValid() || url.isBlankURL()) { // For blank frames we generate a fake URL so they can be referenced by their containing frame. url = urlForBlankFrame(frame); } if (m_resourceURLs.contains(url)) { // FIXME: We could have 2 frame with the same URL but which were dynamically changed and have now // different content. So we should serialize both and somehow rename the frame src in the containing // frame. Arg! return; } Vector<Node*> nodes; SerializerMarkupAccumulator accumulator(this, document, &nodes); WTF::TextEncoding textEncoding(document->charset()); CString data; if (!textEncoding.isValid()) { // FIXME: iframes used as images trigger this. We should deal with them correctly. return; } String text = accumulator.serializeNodes(document, IncludeNode); CString frameHTML = textEncoding.normalizeAndEncode(text, WTF::EntitiesForUnencodables); m_resources->append(SerializedResource(url, document->suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length()))); m_resourceURLs.add(url); for (Vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) { Node* node = *iter; if (!node->isElementNode()) continue; Element* element = toElement(node); // We have to process in-line style as it might contain some resources (typically background images). if (element->isStyledElement()) retrieveResourcesForProperties(element->inlineStyle(), document); if (element->hasTagName(HTMLNames::imgTag)) { HTMLImageElement* imageElement = toHTMLImageElement(element); KURL url = document->completeURL(imageElement->getAttribute(HTMLNames::srcAttr)); ImageResource* cachedImage = imageElement->cachedImage(); addImageToResources(cachedImage, imageElement->renderer(), url); } else if (element->hasTagName(HTMLNames::inputTag)) { HTMLInputElement* inputElement = toHTMLInputElement(element); if (inputElement->isImageButton() && inputElement->hasImageLoader()) { KURL url = inputElement->src(); ImageResource* cachedImage = inputElement->imageLoader()->image(); addImageToResources(cachedImage, inputElement->renderer(), url); } } else if (element->hasTagName(HTMLNames::linkTag)) { HTMLLinkElement* linkElement = toHTMLLinkElement(element); if (CSSStyleSheet* sheet = linkElement->sheet()) { KURL url = document->completeURL(linkElement->getAttribute(HTMLNames::hrefAttr)); serializeCSSStyleSheet(sheet, url); ASSERT(m_resourceURLs.contains(url)); } } else if (element->hasTagName(HTMLNames::styleTag)) { HTMLStyleElement* styleElement = toHTMLStyleElement(element); if (CSSStyleSheet* sheet = styleElement->sheet()) serializeCSSStyleSheet(sheet, KURL()); } } for (Frame* childFrame = frame->tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling()) serializeFrame(childFrame); }
bool ChromeClientBlackBerry::runBeforeUnloadConfirmPanel(const String& message, Frame* frame) { #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD if (m_webPagePrivate->m_dumpRenderTree) return m_webPagePrivate->m_dumpRenderTree->runBeforeUnloadConfirmPanel(message); #endif TimerBase::fireTimersInNestedEventLoop(); CString latinOrigin = toOriginString(frame); return m_webPagePrivate->m_client->runBeforeUnloadConfirmPanel(message.characters(), message.length(), latinOrigin.data(), latinOrigin.length()); }
PassRefPtr<FormData> FormData::create(const CString& string) { RefPtr<FormData> result = create(); result->appendData(string.data(), string.length()); return result.release(); }
bool getContextMenuFromProposedMenu(WebPageProxy&, const Vector<RefPtr<WebContextMenuItem>>& proposedMenu, Vector<RefPtr<WebContextMenuItem>>&, const WebHitTestResultData& hitTestResultData, API::Object* userData) override { GRefPtr<GVariant> variant; if (userData) { ASSERT(userData->type() == API::Object::Type::String); CString userDataString = static_cast<API::String*>(userData)->string().utf8(); variant = adoptGRef(g_variant_parse(nullptr, userDataString.data(), userDataString.data() + userDataString.length(), nullptr, nullptr)); } Vector<WebContextMenuItemData> menuItems; menuItems.reserveInitialCapacity(proposedMenu.size()); for (auto& item : proposedMenu) menuItems.uncheckedAppend(*item->data()); webkitWebViewPopulateContextMenu(m_webView, menuItems, hitTestResultData, variant.get()); return true; }
void ChromeClientBlackBerry::runJavaScriptAlert(Frame* frame, const String& message) { #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD if (m_webPagePrivate->m_dumpRenderTree) { m_webPagePrivate->m_dumpRenderTree->runJavaScriptAlert(message); return; } #endif TimerBase::fireTimersInNestedEventLoop(); CString latinOrigin = toOriginString(frame); m_webPagePrivate->m_client->runJavaScriptAlert(message.characters(), message.length(), latinOrigin.data(), latinOrigin.length()); }
static void addStringToSHA1(SHA1& sha1, const String& string) { CString cString = string.utf8(); sha1.addBytes(reinterpret_cast<const uint8_t*>(cString.data()), cString.length()); }
PassRefPtr<ShapeResult> HarfBuzzShaper::shapeResult() { RefPtr<ShapeResult> result = ShapeResult::create(m_font, m_normalizedBufferLength, m_textRun.direction()); HarfBuzzScopedPtr<hb_buffer_t> harfBuzzBuffer(hb_buffer_create(), hb_buffer_destroy); const FontDescription& fontDescription = m_font->getFontDescription(); const String& localeString = fontDescription.locale(); CString locale = localeString.latin1(); const hb_language_t language = hb_language_from_string(locale.data(), locale.length()); RunSegmenter::RunSegmenterRange segmentRange = { 0, 0, USCRIPT_INVALID_CODE, OrientationIterator::OrientationInvalid, SmallCapsIterator::SmallCapsSameCase, FontFallbackPriority::Invalid }; RunSegmenter runSegmenter( m_normalizedBuffer.get(), m_normalizedBufferLength, m_font->getFontDescription().orientation(), fontDescription.variant()); Vector<UChar32> fallbackCharsHint; // TODO: Check whether this treatAsZerowidthspace from the previous script // segmentation plays a role here, does the new scriptRuniterator handle that correctly? while (runSegmenter.consume(&segmentRange)) { RefPtr<FontFallbackIterator> fallbackIterator = m_font->createFontFallbackIterator( segmentRange.fontFallbackPriority); appendToHolesQueue(HolesQueueNextFont, 0, 0); appendToHolesQueue(HolesQueueRange, segmentRange.start, segmentRange.end - segmentRange.start); const SimpleFontData* currentFont = nullptr; RefPtr<UnicodeRangeSet> currentFontRangeSet; bool fontCycleQueued = false; while (m_holesQueue.size()) { HolesQueueItem currentQueueItem = m_holesQueue.takeFirst(); if (currentQueueItem.m_action == HolesQueueNextFont) { // For now, we're building a character list with which we probe // for needed fonts depending on the declared unicode-range of a // segmented CSS font. Alternatively, we can build a fake font // for the shaper and check whether any glyphs were found, or // define a new API on the shaper which will give us coverage // information? if (!collectFallbackHintChars(fallbackCharsHint, fallbackIterator->needsHintList())) { // Give up shaping since we cannot retrieve a font fallback // font without a hintlist. m_holesQueue.clear(); break; } FontDataForRangeSet nextFontDataForRangeSet = fallbackIterator->next(fallbackCharsHint); currentFont = nextFontDataForRangeSet.fontData().get(); currentFontRangeSet = nextFontDataForRangeSet.ranges(); if (!currentFont) { ASSERT(!m_holesQueue.size()); break; } fontCycleQueued = false; continue; } // TODO crbug.com/522964: Only use smallCapsFontData when the font does not support true smcp. The spec // says: "To match the surrounding text, a font may provide alternate glyphs for caseless characters when // these features are enabled but when a user agent simulates small capitals, it must not attempt to // simulate alternates for codepoints which are considered caseless." const SimpleFontData* smallcapsAdjustedFont = segmentRange.smallCapsBehavior == SmallCapsIterator::SmallCapsUppercaseNeeded ? currentFont->smallCapsFontData(fontDescription).get() : currentFont; // Compatibility with SimpleFontData approach of keeping a flag for overriding drawing direction. // TODO: crbug.com/506224 This should go away in favor of storing that information elsewhere, for example in // ShapeResult. const SimpleFontData* directionAndSmallCapsAdjustedFont = fontDataAdjustedForOrientation(smallcapsAdjustedFont, m_font->getFontDescription().orientation(), segmentRange.renderOrientation); if (!shapeRange(harfBuzzBuffer.get(), currentQueueItem.m_startIndex, currentQueueItem.m_numCharacters, directionAndSmallCapsAdjustedFont, currentFontRangeSet, segmentRange.script, language)) DLOG(ERROR) << "Shaping range failed."; if (!extractShapeResults(harfBuzzBuffer.get(), result.get(), fontCycleQueued, currentQueueItem, directionAndSmallCapsAdjustedFont, segmentRange.script, !fallbackIterator->hasNext())) DLOG(ERROR) << "Shape result extraction failed."; hb_buffer_reset(harfBuzzBuffer.get()); } } return result.release(); }
void DateTimeChooserImpl::writeDocument(WebCore::DocumentWriter& writer) { WebCore::DateComponents date; date.setMillisecondsSinceEpochForDate(m_parameters.minimum); String minString = date.toString(); date.setMillisecondsSinceEpochForDate(m_parameters.maximum); String maxString = date.toString(); String stepString = String::number(m_parameters.step); String stepBaseString = String::number(m_parameters.stepBase, 11, WTF::TruncateTrailingZeros); IntRect anchorRectInScreen = m_chromeClient->rootViewToScreen(m_parameters.anchorRectInRootView); FrameView* view = static_cast<WebViewImpl*>(m_chromeClient->webView())->page()->mainFrame()->view(); IntRect rootViewVisibleContentRect = view->visibleContentRect(true /* include scrollbars */); IntRect rootViewRectInScreen = m_chromeClient->rootViewToScreen(rootViewVisibleContentRect); addString("<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", writer); writer.addData(WebCore::pickerCommonCss, sizeof(WebCore::pickerCommonCss)); writer.addData(WebCore::suggestionPickerCss, sizeof(WebCore::suggestionPickerCss)); writer.addData(WebCore::calendarPickerCss, sizeof(WebCore::calendarPickerCss)); CString extraStyle = WebCore::RenderTheme::defaultTheme()->extraCalendarPickerStyleSheet(); if (extraStyle.length()) writer.addData(extraStyle.data(), extraStyle.length()); addString("</style></head><body><div id=main>Loading...</div><script>\n" "window.dialogArguments = {\n", writer); addProperty("anchorRectInScreen", anchorRectInScreen, writer); addProperty("rootViewRectInScreen", rootViewRectInScreen, writer); #if OS(MAC_OS_X) addProperty("confineToRootView", true, writer); #else addProperty("confineToRootView", false, writer); #endif addProperty("min", minString, writer); addProperty("max", maxString, writer); addProperty("step", stepString, writer); addProperty("stepBase", stepBaseString, writer); addProperty("required", m_parameters.required, writer); addProperty("currentValue", m_parameters.currentValue, writer); addProperty("locale", WebCore::defaultLanguage(), writer); addProperty("todayLabel", Platform::current()->queryLocalizedString(WebLocalizedString::CalendarToday), writer); addProperty("clearLabel", Platform::current()->queryLocalizedString(WebLocalizedString::CalendarClear), writer); addProperty("weekStartDay", m_locale->firstDayOfWeek(), writer); addProperty("monthLabels", m_locale->monthLabels(), writer); addProperty("dayLabels", m_locale->weekDayShortLabels(), writer); addProperty("isCalendarRTL", m_locale->isRTL(), writer); addProperty("isRTL", m_parameters.isAnchorElementRTL, writer); if (m_parameters.suggestionValues.size()) { addProperty("inputWidth", static_cast<unsigned>(m_parameters.anchorRectInRootView.width()), writer); addProperty("suggestionValues", m_parameters.suggestionValues, writer); addProperty("localizedSuggestionValues", m_parameters.localizedSuggestionValues, writer); addProperty("suggestionLabels", m_parameters.suggestionLabels, writer); addProperty("showOtherDateEntry", m_parameters.type == WebCore::InputTypeNames::date(), writer); addProperty("otherDateLabel", Platform::current()->queryLocalizedString(WebLocalizedString::OtherDateLabel), writer); addProperty("suggestionHighlightColor", WebCore::RenderTheme::defaultTheme()->activeListBoxSelectionBackgroundColor().serialized(), writer); addProperty("suggestionHighlightTextColor", WebCore::RenderTheme::defaultTheme()->activeListBoxSelectionForegroundColor().serialized(), writer); } addString("}\n", writer); writer.addData(WebCore::pickerCommonJs, sizeof(WebCore::pickerCommonJs)); writer.addData(WebCore::suggestionPickerJs, sizeof(WebCore::suggestionPickerJs)); writer.addData(WebCore::calendarPickerJs, sizeof(WebCore::calendarPickerJs)); addString("</script></body>\n", writer); }
PassRefPtr<ShapeResult> HarfBuzzShaper::shapeResult() { RefPtr<ShapeResult> result = ShapeResult::create(m_font, m_normalizedBufferLength, m_textRun.direction()); HarfBuzzScopedPtr<hb_buffer_t> harfBuzzBuffer(hb_buffer_create(), hb_buffer_destroy); const FontDescription& fontDescription = m_font->getFontDescription(); const String& localeString = fontDescription.locale(); CString locale = localeString.latin1(); const hb_language_t language = hb_language_from_string(locale.data(), locale.length()); bool needsCapsHandling = fontDescription.variantCaps() != FontDescription::CapsNormal; OpenTypeCapsSupport capsSupport; RunSegmenter::RunSegmenterRange segmentRange = { 0, 0, USCRIPT_INVALID_CODE, OrientationIterator::OrientationInvalid, FontFallbackPriority::Invalid }; RunSegmenter runSegmenter( m_normalizedBuffer.get(), m_normalizedBufferLength, m_font->getFontDescription().orientation()); Vector<UChar32> fallbackCharsHint; // TODO: Check whether this treatAsZerowidthspace from the previous script // segmentation plays a role here, does the new scriptRuniterator handle that correctly? while (runSegmenter.consume(&segmentRange)) { RefPtr<FontFallbackIterator> fallbackIterator = m_font->createFontFallbackIterator( segmentRange.fontFallbackPriority); appendToHolesQueue(HolesQueueNextFont, 0, 0); appendToHolesQueue(HolesQueueRange, segmentRange.start, segmentRange.end - segmentRange.start); RefPtr<FontDataForRangeSet> currentFontDataForRangeSet; bool fontCycleQueued = false; while (m_holesQueue.size()) { HolesQueueItem currentQueueItem = m_holesQueue.takeFirst(); if (currentQueueItem.m_action == HolesQueueNextFont) { // For now, we're building a character list with which we probe // for needed fonts depending on the declared unicode-range of a // segmented CSS font. Alternatively, we can build a fake font // for the shaper and check whether any glyphs were found, or // define a new API on the shaper which will give us coverage // information? if (!collectFallbackHintChars(fallbackCharsHint, fallbackIterator->needsHintList())) { // Give up shaping since we cannot retrieve a font fallback // font without a hintlist. m_holesQueue.clear(); break; } currentFontDataForRangeSet = fallbackIterator->next(fallbackCharsHint); if (!currentFontDataForRangeSet->fontData()) { ASSERT(!m_holesQueue.size()); break; } fontCycleQueued = false; continue; } SmallCapsIterator::SmallCapsBehavior smallCapsBehavior = SmallCapsIterator::SmallCapsSameCase; if (needsCapsHandling) { capsSupport = OpenTypeCapsSupport( currentFontDataForRangeSet->fontData()->platformData().harfBuzzFace(), fontDescription.variantCaps(), ICUScriptToHBScript(segmentRange.script)); if (capsSupport.needsRunCaseSplitting()) splitUntilNextCaseChange(currentQueueItem, smallCapsBehavior); } ASSERT(currentQueueItem.m_numCharacters); const SimpleFontData* smallcapsAdjustedFont = needsCapsHandling && capsSupport.needsSyntheticFont(smallCapsBehavior) ? currentFontDataForRangeSet->fontData()->smallCapsFontData(fontDescription).get() : currentFontDataForRangeSet->fontData(); // Compatibility with SimpleFontData approach of keeping a flag for overriding drawing direction. // TODO: crbug.com/506224 This should go away in favor of storing that information elsewhere, for example in // ShapeResult. const SimpleFontData* directionAndSmallCapsAdjustedFont = fontDataAdjustedForOrientation(smallcapsAdjustedFont, m_font->getFontDescription().orientation(), segmentRange.renderOrientation); CaseMapIntend caseMapIntend = CaseMapIntend::KeepSameCase; if (needsCapsHandling) { caseMapIntend = capsSupport.needsCaseChange(smallCapsBehavior); } CaseMappingHarfBuzzBufferFiller( caseMapIntend, fontDescription.locale(), harfBuzzBuffer.get(), m_normalizedBuffer.get(), m_normalizedBufferLength, currentQueueItem.m_startIndex, currentQueueItem.m_numCharacters); CapsFeatureSettingsScopedOverlay capsOverlay(m_features, capsSupport.fontFeatureToUse(smallCapsBehavior)); if (!shapeRange(harfBuzzBuffer.get(), currentQueueItem.m_startIndex, currentQueueItem.m_numCharacters, directionAndSmallCapsAdjustedFont, currentFontDataForRangeSet->ranges(), segmentRange.script, language)) DLOG(ERROR) << "Shaping range failed."; if (!extractShapeResults(harfBuzzBuffer.get(), result.get(), fontCycleQueued, currentQueueItem, directionAndSmallCapsAdjustedFont, segmentRange.script, !fallbackIterator->hasNext())) DLOG(ERROR) << "Shape result extraction failed."; hb_buffer_reset(harfBuzzBuffer.get()); } } return result.release(); }
void ChromeClientBlackBerry::requestGeolocationPermissionForFrame(Frame* frame, Geolocation* geolocation) { if (!m_webPage->settings()->isGeolocationEnabled()) { geolocation->setIsAllowed(false); return; } DOMWindow* window = frame->domWindow(); if (!window) return; CString latinOrigin = frameOrigin(frame); m_webPage->client()->requestGeolocationPermission(m_webPage->d->m_geolocationClient, geolocation, latinOrigin.data(), latinOrigin.length()); }
void ListServer_Main() { if ( listServerFields[5] == "localhost" ) return; if (!lsConnected) return; CBuffer receiveBuff; if (listServer.receiveBytes(receiveBuff, 65536) < 0) { errorOut("serverlog.txt", "Disconnected from list server."); lsConnected = false; return; } CStringList lines; lines.load(receiveBuff.text(), "\n"); for (int i = 0; i < lines.count(); i++) { CPacket line = CPacket() << lines[i]; int messageId = line.readByte1(); switch (messageId) { case GSVOLD: { printf("[%s] SERVER VERSION CHECK - Current: %i, Latest: %i - Old version, please upgrade.\n", getTimeStr(1).text(), GSERVER_BUILD, line.readByte2()); break; } case GSVCURRENT: { printf("[%s] SERVER VERSION CHECK - Current: %i, Latest: %i - You are up to date :)\n", getTimeStr(1).text(), GSERVER_BUILD, GSERVER_BUILD); break; } case GSVACCOUNT: { CString accountName = line.readChars(line.readByte1()); CString errorMsg = line.readString(""); for (int i = 0; i < newPlayers.count(); i++) { CPlayer *player = (CPlayer *)newPlayers[i]; if (player->accountName == accountName) { if (errorMsg == "SUCCESS") { player->sendAccount(); } else { player->sendPacket(CPacket() << (char)DISMESSAGE << errorMsg); player->deleteMe = true; } break; } } break; } case GSVGUILD: { int playerId = line.readByte2(); CPlayer *player = (CPlayer *)playerIds[playerId]; if (player != NULL) { CString nick = line.readChars((unsigned char)line.readByte1()); CString guild = nick.copy( nick.findl( '(' ) ).remove( ")" ); if ( globalGuilds == false ) { if ( globalGuildList.find( guild ) != -1 ) player->setNick(nick, false); } else player->setNick(nick, false); } break; } case GSVFILEC: { CString fileData, fileName = CString() << dataDir << "global" << fSep << line.readChars(line.readByte1()); fileData.save(fileName.text()); break; } case GSVFILED: { CString fileName = line.readChars(line.readByte1()); CPlayer *player = (CPlayer *)playerIds[line.readByte2()]; switch (line.readByte1()) { case 0: // head player->headImage = fileName; player->updateProp(HEADGIF); break; case 1: // body player->bodyImage = fileName; player->updateProp(BODYIMG); break; case 2: // sword player->swordImage = fileName; player->updateProp(SWORDPOWER); break; case 3: // shield player->shieldImage = fileName; player->updateProp(SHIELDPOWER); break; } break; } case GSVFILES: { CString fileData, fileName, newData, shortName; shortName = line.readChars(line.readByte1()); int pos = shortName.find("Revision"); if (pos >= 0) { #ifdef WIN32 fileName = CString() << "GServer-NEW.exe"; #else fileName = CString() << "GServer-NEW"; #endif newData = line.readString(""); } else { fileName = CString() << dataDir << "global" << fSep << shortName.text(); newData = line.readString(""); } fileData.load(fileName.text()); fileData << newData.B64_Decode(); fileData.save(fileName.text()); break; } case GSVPROFILE: /* Unsure if this works, temp */ { CPacket profile; CPlayer *player1 = (CPlayer *)playerIds[line.readByte2()]; CPlayer *player2 = findPlayerId(line.readChars(line.readByte1())); if (player1 == NULL || player2 == NULL) return; profile << (char)player2->accountName.length() << player2->accountName << line.readString(""); int time = player2->onlineSecs; CString line2; //Online time line2 << toString((int)time/3600) << " hrs "; line2 << toString((int)(time/60)%60) << " mins "; line2 << toString((int)time%60) << " secs"; profile << (char)line2.length() << line2; for (int i = 0; i < profileList.count(); i++) { CStringList a; a.load(profileList[i].text(), ":="); if (a[0].length() < 1) continue; CString n; if (a[1] == "playerkills") n = toString(player2->kills); else if (a[1] == "playerdeaths") n = toString(player2->deaths); else if (a[1] == "playerfullhearts") { if ( (float)(int)player2->maxPower == (float)player2->maxPower ) n = toString((int)player2->maxPower); else { n = toString(player2->maxPower); n = n.copy( 0, n.length() - 1 ); } } else if (a[1] == "playerrating") n = toString((int)player2->rating) << "/" << toString((int)player2->deviation); else if (a[1] == "playerap") n = toString(player2->ap); else if (a[1] == "playerrupees") n = toString(player2->rubins); else if (a[1] == "playerswordpower") n = toString(player2->swordPower); else if (a[1] == "canspin") n = (player2->status & 64 ? "true" : "false"); else if (a[1] == "playerhearts") { if ( (float)(int)player2->power == (float)player2->power ) n = toString((int)player2->power); else { n = toString(player2->power); n = n.copy( 0, n.length() - 1 ); } } else if (a[1] == "playerdarts") n = toString(player2->darts); else if (a[1] == "playerbombs") n = toString(player2->bombs); else if (a[1] == "playermp") n = toString(player2->magicPoints); else if (a[1] == "playershieldpower") n = toString(player2->shieldPower); else if (a[1] == "playerglovepower") n = toString(player2->glovePower); else { for (int i = 0; i < player2->myFlags.count(); i++) { CStringList b; b.load(player2->myFlags[i].text(), "="); if (b[0] == a[1]) { n = b[1]; break; } } } profile << (char)(a[0].length() + n.length() + 2) << a[0] << ":=" << n; } player1->sendPacket(CPacket() << (char)DPROFILE << profile); break; } case GSVMSG: printf("[%s] %s\n", getTimeStr(1).text(), line.readString("")); break; case GSVPING: // Sent every 60 seconds, do nothing. break; default: printf("[%s] Invalid List Server Message: %i\n", getTimeStr(1).text(), messageId); break; } } }
PassRefPtr<SharedBuffer> MHTMLArchive::generateMHTMLData(Page* page) { Vector<PageSerializer::Resource> resources; PageSerializer pageSerializer(&resources); pageSerializer.serialize(page); String boundary = generateRandomBoundary(); String endOfResourceBoundary = makeString("--", boundary, "\r\n"); GregorianDateTime now; now.setToCurrentLocalTime(); String dateString = makeRFC2822DateString(now.weekDay(), now.monthDay(), now.month(), now.year(), now.hour(), now.minute(), now.second(), now.utcOffset() / 60); StringBuilder stringBuilder; stringBuilder.append("From: <Saved by WebKit>\r\n"); stringBuilder.append("Subject: "); // We replace non ASCII characters with '?' characters to match IE's behavior. stringBuilder.append(replaceNonPrintableCharacters(page->mainFrame().document()->title())); stringBuilder.append("\r\nDate: "); stringBuilder.append(dateString); stringBuilder.append("\r\nMIME-Version: 1.0\r\n"); stringBuilder.append("Content-Type: multipart/related;\r\n"); stringBuilder.append("\ttype=\""); stringBuilder.append(page->mainFrame().document()->suggestedMIMEType()); stringBuilder.append("\";\r\n"); stringBuilder.append("\tboundary=\""); stringBuilder.append(boundary); stringBuilder.append("\"\r\n\r\n"); // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? (we still only have put ASCII characters in it). ASSERT(stringBuilder.toString().containsOnlyASCII()); CString asciiString = stringBuilder.toString().utf8(); RefPtr<SharedBuffer> mhtmlData = SharedBuffer::create(); mhtmlData->append(asciiString.data(), asciiString.length()); for (auto& resource : resources) { stringBuilder.clear(); stringBuilder.append(endOfResourceBoundary); stringBuilder.append("Content-Type: "); stringBuilder.append(resource.mimeType); const char* contentEncoding = nullptr; if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(resource.mimeType) || MIMETypeRegistry::isSupportedNonImageMIMEType(resource.mimeType)) contentEncoding = quotedPrintable; else contentEncoding = base64; stringBuilder.append("\r\nContent-Transfer-Encoding: "); stringBuilder.append(contentEncoding); stringBuilder.append("\r\nContent-Location: "); stringBuilder.append(resource.url); stringBuilder.append("\r\n\r\n"); asciiString = stringBuilder.toString().utf8(); mhtmlData->append(asciiString.data(), asciiString.length()); // FIXME: ideally we would encode the content as a stream without having to fetch it all. const char* data = resource.data->data(); size_t dataLength = resource.data->size(); Vector<char> encodedData; if (!strcmp(contentEncoding, quotedPrintable)) { quotedPrintableEncode(data, dataLength, encodedData); mhtmlData->append(encodedData.data(), encodedData.size()); mhtmlData->append("\r\n", 2); } else { ASSERT(!strcmp(contentEncoding, base64)); // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs. base64Encode(data, dataLength, encodedData); const size_t maximumLineLength = 76; size_t index = 0; size_t encodedDataLength = encodedData.size(); do { size_t lineLength = std::min(encodedDataLength - index, maximumLineLength); mhtmlData->append(encodedData.data() + index, lineLength); mhtmlData->append("\r\n", 2); index += maximumLineLength; } while (index < encodedDataLength); } } asciiString = makeString("--", boundary, "--\r\n").utf8(); mhtmlData->append(asciiString.data(), asciiString.length()); return mhtmlData.release(); }
bool ChromeClientBlackBerry::runJavaScriptConfirm(Frame* frame, const WTF::String& message) { if (m_webPage->d->m_dumpRenderTree) return m_webPage->d->m_dumpRenderTree->runJavaScriptConfirm(message); TimerBase::fireTimersInNestedEventLoop(); CString latinOrigin = frameOrigin(frame); return m_webPage->client()->runJavaScriptConfirm(message.characters(), message.length(), latinOrigin.data(), latinOrigin.length()); }
void HTMLDocument::determineParseMode() { // FIXME: It's terrible that this code runs separately and isn't just built in to the // HTML tokenizer/parser. // This code more or less mimics Mozilla's implementation (specifically the // doctype parsing implemented by David Baron in Mozilla's nsParser.cpp). // // There are three possible parse modes: // COMPAT - quirks mode emulates WinIE and NS4. CSS parsing is also relaxed in this mode, e.g., unit types can // be omitted from numbers. // ALMOST STRICT - This mode is identical to strict mode except for its treatment of line-height in the inline box model. For // now (until the inline box model is re-written), this mode is identical to STANDARDS mode. // STRICT - no quirks apply. Web pages will obey the specifications to the letter. bool wasInCompatMode = inCompatMode(); DocumentType* docType = doctype(); if (!docType || !equalIgnoringCase(docType->name(), "html")) // No doctype found at all or the doctype is not HTML. Default to quirks mode and Html4. setParseMode(Compat); else if (!doctype()->systemId().isEmpty() && equalIgnoringCase(docType->systemId(), "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd")) // Assume quirks mode for this particular system ID. In the HTML5 spec, this is the only // system identifier that is examined. setParseMode(Compat); else if (docType->publicId().isEmpty()) // A doctype without a public ID means use strict mode. setParseMode(Strict); else { // We have to check a list of public IDs to see what we // should do. String lowerPubID = docType->publicId().lower(); CString pubIDStr = lowerPubID.latin1(); #ifdef ANDROID_META_SUPPORT if ((!frame()->tree() || !frame()->tree()->parent()) && strstr(pubIDStr.data(), "-//wapforum//dtd xhtml mobile 1.") == pubIDStr.data()) { // fit mobile sites directly in the screen frame()->settings()->setMetadataSettings("width", "device-width"); } #endif // Look up the entry in our gperf-generated table. const PubIDInfo* doctypeEntry = findDoctypeEntry(pubIDStr.data(), pubIDStr.length()); if (!doctypeEntry) // The DOCTYPE is not in the list. Assume strict mode. setParseMode(Strict); else { switch (docType->systemId().isEmpty() ? doctypeEntry->mode_if_no_sysid : doctypeEntry->mode_if_sysid) { case PubIDInfo::eQuirks3: case PubIDInfo::eQuirks: setParseMode(Compat); break; case PubIDInfo::eAlmostStandards: setParseMode(AlmostStrict); break; default: ASSERT(false); } } } if (inCompatMode() != wasInCompatMode) updateStyleSelector(); }
bool ChromeClientBlackBerry::runJavaScriptPrompt(Frame* frame, const WTF::String& message, const WTF::String& defaultValue, WTF::String& result) { WebString clientResult; if (m_webPage->d->m_dumpRenderTree) { result = m_webPage->d->m_dumpRenderTree->runJavaScriptPrompt(message, defaultValue); return true; } TimerBase::fireTimersInNestedEventLoop(); CString latinOrigin = frameOrigin(frame); if (m_webPage->client()->runJavaScriptPrompt(message.characters(), message.length(), defaultValue.characters(), defaultValue.length(), latinOrigin.data(), latinOrigin.length(), clientResult)) { result = clientResult; return true; } return false; }
bool ChromeClientBlackBerry::runJavaScriptConfirm(Frame* frame, const String& message) { #if ENABLE_DRT if (m_webPagePrivate->m_dumpRenderTree) return m_webPagePrivate->m_dumpRenderTree->runJavaScriptConfirm(message); #endif TimerBase::fireTimersInNestedEventLoop(); CString latinOrigin = frameOrigin(frame); return m_webPagePrivate->m_client->runJavaScriptConfirm(message.characters(), message.length(), latinOrigin.data(), latinOrigin.length()); }
// Strip special controle char, like color, bold, ... CString CLogMod::Sanitize(const CString& sLine) { unsigned int i,l; // Color codes format (regex): \x03([0-9]{1,2}(,[0-9]{1,2})?)? // e: escape, if true, we have met an escape char (\x03) and are still striping. bool e; // c: comma, if we passed the comma yet or not bool c; // d: the number of digits we already striped (maximum 2 each time) unsigned int d=0; CString sRet; l = sLine.length(); sRet.reserve(l); e=false; d=0; c=false; for(i=0; i<l; i++) { unsigned char ch = sLine[i]; switch (ch) { case '\x02': // Bold case '\x0f': // Reset case '\x12': // Reverse Color case '\x15': // Underline case '\x16': // Reverse case '\x1D': // Italic case '\x1f': // Underline continue; case '\x03': // Color e=true; d=0; c=false; continue; case ',': if (e) { if(!c && d>0) { c=true; d=0; continue; } } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (e && d <2) { d++; continue; } default: e=false; sRet += ch; } } sRet.reserve(0); return sRet; }
void dumpNodeFlags(PrintStream& actualOut, NodeFlags flags) { StringPrintStream out; CommaPrinter comma("|"); if (flags & NodeResultMask) { switch (flags & NodeResultMask) { case NodeResultJS: out.print(comma, "JS"); break; case NodeResultNumber: out.print(comma, "Number"); break; case NodeResultDouble: out.print(comma, "Double"); break; case NodeResultInt32: out.print(comma, "Int32"); break; case NodeResultInt52: out.print(comma, "Int52"); break; case NodeResultBoolean: out.print(comma, "Boolean"); break; case NodeResultStorage: out.print(comma, "Storage"); break; default: RELEASE_ASSERT_NOT_REACHED(); break; } } if (flags & NodeMustGenerate) out.print(comma, "MustGen"); if (flags & NodeHasVarArgs) out.print(comma, "VarArgs"); if (flags & NodeClobbersWorld) out.print(comma, "Clobbers"); if (flags & NodeMightClobber) out.print(comma, "MightClobber"); if (flags & NodeResultMask) { if (!(flags & NodeBytecodeUsesAsNumber) && !(flags & NodeBytecodeNeedsNegZero)) out.print(comma, "PureInt"); else if (!(flags & NodeBytecodeUsesAsNumber)) out.print(comma, "PureInt(w/ neg zero)"); else if (!(flags & NodeBytecodeNeedsNegZero)) out.print(comma, "PureNum"); if (flags & NodeBytecodeUsesAsOther) out.print(comma, "UseAsOther"); } if (flags & NodeMayOverflow) out.print(comma, "MayOverflow"); if (flags & NodeMayNegZero) out.print(comma, "MayNegZero"); if (flags & NodeBytecodeUsesAsInt) out.print(comma, "UseAsInt"); if (!(flags & NodeDoesNotExit)) out.print(comma, "CanExit"); if (flags & NodeIsFlushed) out.print(comma, "IsFlushed"); CString string = out.toCString(); if (!string.length()) actualOut.print("<empty>"); else actualOut.print(string); }
bool ChromeClientBlackBerry::runJavaScriptPrompt(Frame* frame, const String& message, const String& defaultValue, String& result) { #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD if (m_webPagePrivate->m_dumpRenderTree) { result = m_webPagePrivate->m_dumpRenderTree->runJavaScriptPrompt(message, defaultValue); return true; } #endif TimerBase::fireTimersInNestedEventLoop(); CString latinOrigin = toOriginString(frame); WebString clientResult; if (m_webPagePrivate->m_client->runJavaScriptPrompt(message.characters(), message.length(), defaultValue.characters(), defaultValue.length(), latinOrigin.data(), latinOrigin.length(), clientResult)) { result = clientResult; return true; } return false; }
PassRefPtr<SharedBuffer> MHTMLArchive::generateMHTMLData(Page* page, bool useBinaryEncoding) { Vector<PageSerializer::Resource> resources; PageSerializer pageSerializer(&resources); pageSerializer.serialize(page); String boundary = generateRandomBoundary(); String endOfResourceBoundary = makeString("--", boundary, "\r\n"); String dateString; time_t localTime = time(0); tm localTM; getLocalTime(&localTime, &localTM); dateString = makeRFC2822DateString(localTM.tm_wday, localTM.tm_mday, localTM.tm_mon, 1900 + localTM.tm_year, localTM.tm_hour, localTM.tm_min, localTM.tm_sec, calculateUTCOffset() / (1000 * 60)); StringBuilder stringBuilder; stringBuilder.append("From: <Saved by WebKit>\r\n"); stringBuilder.append("Subject: "); // We replace non ASCII characters with '?' characters to match IE's behavior. stringBuilder.append(replaceNonPrintableCharacters(page->mainFrame()->document()->title())); stringBuilder.append("\r\nDate: "); stringBuilder.append(dateString); stringBuilder.append("\r\nMIME-Version: 1.0\r\n"); stringBuilder.append("Content-Type: multipart/related;\r\n"); stringBuilder.append("\ttype=\""); stringBuilder.append(page->mainFrame()->document()->suggestedMIMEType()); stringBuilder.append("\";\r\n"); stringBuilder.append("\tboundary=\""); stringBuilder.append(boundary); stringBuilder.append("\"\r\n\r\n"); // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? (we still only have put ASCII characters in it). ASSERT(stringBuilder.toString().containsOnlyASCII()); CString asciiString = stringBuilder.toString().utf8(); RefPtr<SharedBuffer> mhtmlData = SharedBuffer::create(); mhtmlData->append(asciiString.data(), asciiString.length()); for (size_t i = 0; i < resources.size(); ++i) { const PageSerializer::Resource& resource = resources[i]; stringBuilder.clear(); stringBuilder.append(endOfResourceBoundary); stringBuilder.append("Content-Type: "); stringBuilder.append(resource.mimeType); const char* contentEncoding = useBinaryEncoding ? binary : base64; stringBuilder.append("\r\nContent-Transfer-Encoding: "); stringBuilder.append(contentEncoding); stringBuilder.append("\r\nContent-Location: "); stringBuilder.append(resource.url); stringBuilder.append("\r\n\r\n"); asciiString = stringBuilder.toString().utf8(); mhtmlData->append(asciiString.data(), asciiString.length()); if (!strcmp(contentEncoding, binary)) { const char* data; size_t position = 0; while (size_t length = resource.data->getSomeData(data, position)) { mhtmlData->append(data, length); position += length; } } else { // FIXME: ideally we would encode the content as a stream without having to fetch it all. const char* data = resource.data->data(); size_t dataLength = resource.data->size(); Vector<char> encodedData; if (!strcmp(contentEncoding, quotedPrintable)) { quotedPrintableEncode(data, dataLength, encodedData); mhtmlData->append(encodedData.data(), encodedData.size()); mhtmlData->append("\r\n", 2); } else { ASSERT(!strcmp(contentEncoding, base64)); // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs. base64Encode(data, dataLength, encodedData); const size_t maximumLineLength = 76; size_t index = 0; size_t encodedDataLength = encodedData.size(); do { size_t lineLength = std::min(encodedDataLength - index, maximumLineLength); mhtmlData->append(encodedData.data() + index, lineLength); mhtmlData->append("\r\n", 2); index += maximumLineLength; } while (index < encodedDataLength); } } } asciiString = makeString("--", boundary, "--\r\n").utf8(); mhtmlData->append(asciiString.data(), asciiString.length()); return mhtmlData.release(); }
void CIRCSock::ReadLine(const CString& sData) { CString sLine = sData; sLine.TrimRight("\n\r"); DEBUG("(" << m_pUser->GetUserName() << ") IRC -> ZNC [" << sLine << "]"); MODULECALL(OnRaw(sLine), m_pUser, NULL, return); if (sLine.Equals("PING ", false, 5)) { PutIRC("PONG " + sLine.substr(5)); m_pUser->PutUser(sLine); return; } else if (sLine.Token(1).Equals("PONG") && sLine.Token(3).Equals(":ZNC")) { // We asked for this so don't forward the reply to clients. return; } else if (sLine.Equals("ERROR ", false, 6)) { //ERROR :Closing Link: nick[24.24.24.24] (Excess Flood) CString sError(sLine.substr(7)); if (sError.Left(1) == ":") { sError.LeftChomp(); } m_pUser->PutStatus("Error from Server [" + sError + "]"); return; } CString sCmd = sLine.Token(1); if ((sCmd.length() == 3) && (isdigit(sCmd[0])) && (isdigit(sCmd[1])) && (isdigit(sCmd[2]))) { CString sServer = sLine.Token(0); sServer.LeftChomp(); unsigned int uRaw = sCmd.ToUInt(); CString sNick = sLine.Token(2); CString sRest = sLine.Token(3, true); switch (uRaw) { case 1: {// :irc.server.com 001 nick :Welcome to the Internet Relay Network nick m_pUser->SetIRCServer(sServer); SetTimeout(240, TMO_READ); // Now that we are connected, let nature take its course PutIRC("WHO " + sNick); m_bAuthed = true; m_pUser->PutStatus("Connected!"); vector<CClient*>& vClients = m_pUser->GetClients(); for (unsigned int a = 0; a < vClients.size(); a++) { CClient* pClient = vClients[a]; CString sClientNick = pClient->GetNick(false); if (!sClientNick.Equals(sNick)) { // If they connected with a nick that doesn't match the one we got on irc, then we need to update them pClient->PutClient(":" + sClientNick + "!" + m_Nick.GetIdent() + "@" + m_Nick.GetHost() + " NICK :" + sNick); } } SetNick(sNick); MODULECALL(OnIRCConnected(), m_pUser, NULL, ); m_pUser->ClearRawBuffer(); m_pUser->AddRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); CZNC::Get().ReleaseISpoof(); m_bISpoofReleased = true; break; } case 5: ParseISupport(sRest); m_pUser->UpdateExactRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 2: case 3: case 4: case 250: // highest connection count case 251: // user count case 252: // oper count case 254: // channel count case 255: // client count case 265: // local users case 266: // global users m_pUser->UpdateRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 305: m_pUser->SetIRCAway(false); break; case 306: m_pUser->SetIRCAway(true); break; case 324: { // MODE sRest.Trim(); CChan* pChan = m_pUser->FindChan(sRest.Token(0)); if (pChan) { pChan->SetModes(sRest.Token(1, true)); } } break; case 329: { sRest.Trim(); CChan* pChan = m_pUser->FindChan(sRest.Token(0)); if (pChan) { unsigned long ulDate = sLine.Token(4).ToULong(); pChan->SetCreationDate(ulDate); } } break; case 331: { // :irc.server.com 331 yournick #chan :No topic is set. CChan* pChan = m_pUser->FindChan(sLine.Token(3)); if (pChan) { pChan->SetTopic(""); } break; } case 332: { // :irc.server.com 332 yournick #chan :This is a topic CChan* pChan = m_pUser->FindChan(sLine.Token(3)); if (pChan) { CString sTopic = sLine.Token(4, true); sTopic.LeftChomp(); pChan->SetTopic(sTopic); } break; } case 333: { // :irc.server.com 333 yournick #chan setternick 1112320796 CChan* pChan = m_pUser->FindChan(sLine.Token(3)); if (pChan) { sNick = sLine.Token(4); unsigned long ulDate = sLine.Token(5).ToULong(); pChan->SetTopicOwner(sNick); pChan->SetTopicDate(ulDate); } break; } case 352: { // :irc.yourserver.com 352 yournick #chan ident theirhost.com irc.theirserver.com theirnick H :0 Real Name sServer = sLine.Token(0); sNick = sLine.Token(7); CString sIdent = sLine.Token(4); CString sHost = sLine.Token(5); sServer.LeftChomp(); if (sNick.Equals(GetNick())) { m_Nick.SetIdent(sIdent); m_Nick.SetHost(sHost); } m_pUser->SetIRCNick(m_Nick); m_pUser->SetIRCServer(sServer); const vector<CChan*>& vChans = m_pUser->GetChans(); for (unsigned int a = 0; a < vChans.size(); a++) { vChans[a]->OnWho(sNick, sIdent, sHost); } break; } case 353: { // NAMES sRest.Trim(); // Todo: allow for non @+= server msgs CChan* pChan = m_pUser->FindChan(sRest.Token(1)); // If we don't know that channel, some client might have // requested a /names for it and we really should forward this. if (pChan) { CString sNicks = sRest.Token(2, true); if (sNicks.Left(1) == ":") { sNicks.LeftChomp(); } pChan->AddNicks(sNicks); } ForwardRaw353(sLine); // We forwarded it already, so return return; } case 366: { // end of names list m_pUser->PutUser(sLine); // First send them the raw // :irc.server.com 366 nick #chan :End of /NAMES list. CChan* pChan = m_pUser->FindChan(sRest.Token(0)); if (pChan) { if (pChan->IsOn()) { // If we are the only one in the chan, set our default modes if (pChan->GetNickCount() == 1) { CString sModes = pChan->GetDefaultModes(); if (sModes.empty()) { sModes = m_pUser->GetDefaultChanModes(); } if (!sModes.empty()) { PutIRC("MODE " + pChan->GetName() + " " + sModes); } } } } return; // return so we don't send them the raw twice } case 375: // begin motd case 422: // MOTD File is missing m_pUser->ClearMotdBuffer(); case 372: // motd case 376: // end motd m_pUser->AddMotdBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 437: // :irc.server.net 437 * badnick :Nick/channel is temporarily unavailable // :irc.server.net 437 mynick badnick :Nick/channel is temporarily unavailable // :irc.server.net 437 mynick badnick :Cannot change nickname while banned on channel if (m_pUser->IsChan(sRest.Token(0)) || sNick != "*") break; case 432: // :irc.server.com 432 * nick :Erroneous Nickname: Illegal characters case 433: { CString sBadNick = sRest.Token(0); if (!m_bAuthed) { SendAltNick(sBadNick); return; } break; } case 470: { // :irc.unreal.net 470 mynick [Link] #chan1 has become full, so you are automatically being transferred to the linked channel #chan2 // :mccaffrey.freenode.net 470 mynick #electronics ##electronics :Forwarding to another channel // freenode style numeric CChan* pChan = m_pUser->FindChan(sRest.Token(0)); if (!pChan) { // unreal style numeric pChan = m_pUser->FindChan(sRest.Token(1)); } if (pChan) { pChan->Disable(); m_pUser->PutStatus("Channel [" + pChan->GetName() + "] is linked to " "another channel and was thus disabled."); } break; } } } else {
String FormData::decode(const CString& data) const { return encoding().decode(data.data(), data.length()); }
CFURLRef WKURLCopyCFURL(CFAllocatorRef allocatorRef, WKURLRef URLRef) { ASSERT(!toImpl(URLRef)->string().isNull()); // We first create a CString and then create the CFURL from it. This will ensure that the CFURL is stored in // UTF-8 which uses less memory and is what WebKit clients might expect. // This pattern of using UTF-8 and then falling back to Latin1 on failure matches KURL::createCFString with the // major differnce being that KURL does not do a UTF-8 conversion and instead chops off the high bits of the UTF-16 // character sequence. CString buffer = toImpl(URLRef)->string().utf8(); CFURLRef result = CFURLCreateAbsoluteURLWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8*>(buffer.data()), buffer.length(), kCFStringEncodingUTF8, 0, true); if (!result) result = CFURLCreateAbsoluteURLWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8*>(buffer.data()), buffer.length(), kCFStringEncodingISOLatin1, 0, true); return result; }
void PageSerializer::serializeCSSStyleSheet(CSSStyleSheet* styleSheet, const KURL& url) { StringBuilder cssText; for (unsigned i = 0; i < styleSheet->length(); ++i) { CSSRule* rule = styleSheet->item(i); String itemText = rule->cssText(); if (!itemText.isEmpty()) { cssText.append(itemText); if (i < styleSheet->length() - 1) cssText.append("\n\n"); } // Some rules have resources associated with them that we need to retrieve. if (rule->isImportRule()) { CSSImportRule* importRule = static_cast<CSSImportRule*>(rule); Document* document = styleSheet->findDocument(); KURL importURL = document->completeURL(importRule->href()); if (m_resourceURLs.contains(importURL)) continue; serializeCSSStyleSheet(importRule->styleSheet(), importURL); } else if (rule->isFontFaceRule()) { // FIXME: Add support for font face rule. It is not clear to me at this point if the actual otf/eot file can // be retrieved from the CSSFontFaceRule object. } else if (rule->isStyleRule()) retrieveResourcesForCSSRule(static_cast<CSSStyleRule*>(rule)); } if (url.isValid() && !m_resourceURLs.contains(url)) { // FIXME: We should check whether a charset has been specified and if none was found add one. TextEncoding textEncoding(styleSheet->charset()); ASSERT(textEncoding.isValid()); String textString = cssText.toString(); CString text = textEncoding.encode(textString.characters(), textString.length(), EntitiesForUnencodables); m_resources->append(Resource(url, String("text/css"), SharedBuffer::create(text.data(), text.length()))); m_resourceURLs.add(url); } }
void CIRCSock::ReadLine(const CString& sData) { CString sLine = sData; sLine.TrimRight("\n\r"); DEBUG("(" << m_pNetwork->GetUser()->GetUserName() << "/" << m_pNetwork->GetName() << ") IRC -> ZNC [" << sLine << "]"); NETWORKMODULECALL(OnRaw(sLine), m_pNetwork->GetUser(), m_pNetwork, NULL, return); if (sLine.Equals("PING ", false, 5)) { // Generate a reply and don't forward this to any user, // we don't want any PING forwarded PutIRC("PONG " + sLine.substr(5)); return; } else if (sLine.Token(1).Equals("PONG")) { // Block PONGs, we already responded to the pings return; } else if (sLine.Equals("ERROR ", false, 6)) { //ERROR :Closing Link: nick[24.24.24.24] (Excess Flood) CString sError(sLine.substr(6)); sError.TrimPrefix(); m_pNetwork->PutStatus("Error from Server [" + sError + "]"); return; } CString sCmd = sLine.Token(1); if ((sCmd.length() == 3) && (isdigit(sCmd[0])) && (isdigit(sCmd[1])) && (isdigit(sCmd[2]))) { CString sServer = sLine.Token(0).LeftChomp_n(); unsigned int uRaw = sCmd.ToUInt(); CString sNick = sLine.Token(2); CString sRest = sLine.Token(3, true); switch (uRaw) { case 1: { // :irc.server.com 001 nick :Welcome to the Internet Relay Network nick if (m_bAuthed && sServer == "irc.znc.in") { // m_bAuthed == true => we already received another 001 => we might be in a traffic loop m_pNetwork->PutStatus("ZNC seems to be connected to itself, disconnecting..."); Quit(); return; } m_pNetwork->SetIRCServer(sServer); SetTimeout(540, TMO_READ); // Now that we are connected, let nature take its course PutIRC("WHO " + sNick); m_bAuthed = true; m_pNetwork->PutStatus("Connected!"); vector<CClient*>& vClients = m_pNetwork->GetClients(); for (unsigned int a = 0; a < vClients.size(); a++) { CClient* pClient = vClients[a]; CString sClientNick = pClient->GetNick(false); if (!sClientNick.Equals(sNick)) { // If they connected with a nick that doesn't match the one we got on irc, then we need to update them pClient->PutClient(":" + sClientNick + "!" + m_Nick.GetIdent() + "@" + m_Nick.GetHost() + " NICK :" + sNick); } } SetNick(sNick); NETWORKMODULECALL(OnIRCConnected(), m_pNetwork->GetUser(), m_pNetwork, NULL, NOTHING); m_pNetwork->ClearRawBuffer(); m_pNetwork->AddRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; } case 5: ParseISupport(sRest); m_pNetwork->UpdateExactRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 10: { // :irc.server.com 010 nick <hostname> <port> :<info> CString sHost = sRest.Token(0); CString sPort = sRest.Token(1); CString sInfo = sRest.Token(2, true).TrimPrefix_n(); m_pNetwork->PutStatus("Server [" + m_pNetwork->GetCurrentServer()->GetString(false) + "] redirects us to [" + sHost + ":" + sPort + "] with reason [" + sInfo + "]"); m_pNetwork->PutStatus("Perhaps you want to add it as a new server."); // Don't send server redirects to the client return; } case 2: case 3: case 4: case 250: // highest connection count case 251: // user count case 252: // oper count case 254: // channel count case 255: // client count case 265: // local users case 266: // global users m_pNetwork->UpdateRawBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 305: m_pNetwork->SetIRCAway(false); break; case 306: m_pNetwork->SetIRCAway(true); break; case 324: { // MODE sRest.Trim(); CChan* pChan = m_pNetwork->FindChan(sRest.Token(0)); if (pChan) { pChan->SetModes(sRest.Token(1, true)); // We don't SetModeKnown(true) here, // because a 329 will follow if (!pChan->IsModeKnown()) { // When we JOIN, we send a MODE // request. This makes sure the // reply isn't forwarded. return; } } } break; case 329: { sRest.Trim(); CChan* pChan = m_pNetwork->FindChan(sRest.Token(0)); if (pChan) { unsigned long ulDate = sLine.Token(4).ToULong(); pChan->SetCreationDate(ulDate); if (!pChan->IsModeKnown()) { pChan->SetModeKnown(true); // When we JOIN, we send a MODE // request. This makes sure the // reply isn't forwarded. return; } } } break; case 331: { // :irc.server.com 331 yournick #chan :No topic is set. CChan* pChan = m_pNetwork->FindChan(sLine.Token(3)); if (pChan) { pChan->SetTopic(""); } break; } case 332: { // :irc.server.com 332 yournick #chan :This is a topic CChan* pChan = m_pNetwork->FindChan(sLine.Token(3)); if (pChan) { CString sTopic = sLine.Token(4, true); sTopic.LeftChomp(); pChan->SetTopic(sTopic); } break; } case 333: { // :irc.server.com 333 yournick #chan setternick 1112320796 CChan* pChan = m_pNetwork->FindChan(sLine.Token(3)); if (pChan) { sNick = sLine.Token(4); unsigned long ulDate = sLine.Token(5).ToULong(); pChan->SetTopicOwner(sNick); pChan->SetTopicDate(ulDate); } break; } case 352: { // :irc.yourserver.com 352 yournick #chan ident theirhost.com irc.theirserver.com theirnick H :0 Real Name sServer = sLine.Token(0); sNick = sLine.Token(7); CString sIdent = sLine.Token(4); CString sHost = sLine.Token(5); sServer.LeftChomp(); if (sNick.Equals(GetNick())) { m_Nick.SetIdent(sIdent); m_Nick.SetHost(sHost); } m_pNetwork->SetIRCNick(m_Nick); m_pNetwork->SetIRCServer(sServer); const vector<CChan*>& vChans = m_pNetwork->GetChans(); for (unsigned int a = 0; a < vChans.size(); a++) { vChans[a]->OnWho(sNick, sIdent, sHost); } break; } case 353: { // NAMES sRest.Trim(); // Todo: allow for non @+= server msgs CChan* pChan = m_pNetwork->FindChan(sRest.Token(1)); // If we don't know that channel, some client might have // requested a /names for it and we really should forward this. if (pChan) { CString sNicks = sRest.Token(2, true).TrimPrefix_n(); pChan->AddNicks(sNicks); } ForwardRaw353(sLine); // We forwarded it already, so return return; } case 366: { // end of names list m_pNetwork->PutUser(sLine); // First send them the raw // :irc.server.com 366 nick #chan :End of /NAMES list. CChan* pChan = m_pNetwork->FindChan(sRest.Token(0)); if (pChan) { if (pChan->IsOn()) { // If we are the only one in the chan, set our default modes if (pChan->GetNickCount() == 1) { CString sModes = pChan->GetDefaultModes(); if (sModes.empty()) { sModes = m_pNetwork->GetUser()->GetDefaultChanModes(); } if (!sModes.empty()) { PutIRC("MODE " + pChan->GetName() + " " + sModes); } } } } return; // return so we don't send them the raw twice } case 375: // begin motd case 422: // MOTD File is missing m_pNetwork->ClearMotdBuffer(); case 372: // motd case 376: // end motd m_pNetwork->AddMotdBuffer(":" + sServer + " " + sCmd + " ", " " + sRest); break; case 437: // :irc.server.net 437 * badnick :Nick/channel is temporarily unavailable // :irc.server.net 437 mynick badnick :Nick/channel is temporarily unavailable // :irc.server.net 437 mynick badnick :Cannot change nickname while banned on channel if (m_pNetwork->IsChan(sRest.Token(0)) || sNick != "*") break; case 432: // :irc.server.com 432 * nick :Erroneous Nickname: Illegal characters case 433: { CString sBadNick = sRest.Token(0); if (!m_bAuthed) { SendAltNick(sBadNick); return; } break; } case 451: // :irc.server.com 451 CAP :You have not registered // Servers that dont support CAP will give us this error, dont send it to the client if (sNick.Equals("CAP")) return; case 470: { // :irc.unreal.net 470 mynick [Link] #chan1 has become full, so you are automatically being transferred to the linked channel #chan2 // :mccaffrey.freenode.net 470 mynick #electronics ##electronics :Forwarding to another channel // freenode style numeric CChan* pChan = m_pNetwork->FindChan(sRest.Token(0)); if (!pChan) { // unreal style numeric pChan = m_pNetwork->FindChan(sRest.Token(1)); } if (pChan) { pChan->Disable(); m_pNetwork->PutStatus("Channel [" + pChan->GetName() + "] is linked to " "another channel and was thus disabled."); } break; } } } else { CNick Nick(sLine.Token(0).TrimPrefix_n()); sCmd = sLine.Token(1); CString sRest = sLine.Token(2, true); if (sCmd.Equals("NICK")) { CString sNewNick = sRest.TrimPrefix_n(); bool bIsVisible = false; vector<CChan*> vFoundChans; const vector<CChan*>& vChans = m_pNetwork->GetChans(); for (unsigned int a = 0; a < vChans.size(); a++) { CChan* pChan = vChans[a]; if (pChan->ChangeNick(Nick.GetNick(), sNewNick)) { vFoundChans.push_back(pChan); if (!pChan->IsDetached()) { bIsVisible = true; } } } // Todo: use nick compare function here if (Nick.GetNick().Equals(GetNick())) { // We are changing our own nick, the clients always must see this! bIsVisible = true; SetNick(sNewNick); } NETWORKMODULECALL(OnNick(Nick, sNewNick, vFoundChans), m_pNetwork->GetUser(), m_pNetwork, NULL, NOTHING); if (!bIsVisible) { return; } } else if (sCmd.Equals("QUIT")) { CString sMessage = sRest.TrimPrefix_n(); bool bIsVisible = false; // :[email protected] QUIT :message if (Nick.GetNick().Equals(GetNick())) { m_pNetwork->PutStatus("You quit [" + sMessage + "]"); // We don't call module hooks and we don't // forward this quit to clients (Some clients // disconnect if they receive such a QUIT) return; } vector<CChan*> vFoundChans; const vector<CChan*>& vChans = m_pNetwork->GetChans(); for (unsigned int a = 0; a < vChans.size(); a++) { CChan* pChan = vChans[a]; if (pChan->RemNick(Nick.GetNick())) { vFoundChans.push_back(pChan); if (!pChan->IsDetached()) { bIsVisible = true; } } } NETWORKMODULECALL(OnQuit(Nick, sMessage, vFoundChans), m_pNetwork->GetUser(), m_pNetwork, NULL, NOTHING); if (!bIsVisible) { return; } } else if (sCmd.Equals("JOIN")) { CString sChan = sRest.Token(0).TrimPrefix_n(); CChan* pChan; // Todo: use nick compare function if (Nick.GetNick().Equals(GetNick())) { m_pNetwork->AddChan(sChan, false); pChan = m_pNetwork->FindChan(sChan); if (pChan) { pChan->ResetJoinTries(); pChan->Enable(); pChan->SetIsOn(true); PutIRC("MODE " + sChan); } } else { pChan = m_pNetwork->FindChan(sChan); } if (pChan) { pChan->AddNick(Nick.GetNickMask()); NETWORKMODULECALL(OnJoin(Nick.GetNickMask(), *pChan), m_pNetwork->GetUser(), m_pNetwork, NULL, NOTHING); if (pChan->IsDetached()) { return; } } } else if (sCmd.Equals("PART")) { CString sChan = sRest.Token(0).TrimPrefix_n(); CString sMsg = sRest.Token(1, true).TrimPrefix_n(); CChan* pChan = m_pNetwork->FindChan(sChan); bool bDetached = false; if (pChan) { pChan->RemNick(Nick.GetNick()); NETWORKMODULECALL(OnPart(Nick.GetNickMask(), *pChan, sMsg), m_pNetwork->GetUser(), m_pNetwork, NULL, NOTHING); if (pChan->IsDetached()) bDetached = true; } // Todo: use nick compare function if (Nick.GetNick().Equals(GetNick())) { m_pNetwork->DelChan(sChan); } /* * We use this boolean because * m_pNetwork->DelChan() will delete this channel * and thus we would dereference an * already-freed pointer! */ if (bDetached) { return; } } else if (sCmd.Equals("MODE")) { CString sTarget = sRest.Token(0); CString sModes = sRest.Token(1, true); if (sModes.Left(1) == ":") sModes = sModes.substr(1); CChan* pChan = m_pNetwork->FindChan(sTarget); if (pChan) { pChan->ModeChange(sModes, &Nick); if (pChan->IsDetached()) { return; } } else if (sTarget == m_Nick.GetNick()) { CString sModeArg = sModes.Token(0); bool bAdd = true; /* no module call defined (yet?) MODULECALL(OnRawUserMode(*pOpNick, *this, sModeArg, sArgs), m_pNetwork->GetUser(), NULL, ); */ for (unsigned int a = 0; a < sModeArg.size(); a++) { const unsigned char& uMode = sModeArg[a]; if (uMode == '+') { bAdd = true; } else if (uMode == '-') { bAdd = false; } else { if (bAdd) { m_scUserModes.insert(uMode); } else { m_scUserModes.erase(uMode); } } } } } else if (sCmd.Equals("KICK")) { // :[email protected] KICK #chan nick :msg CString sChan = sRest.Token(0); CString sKickedNick = sRest.Token(1); CString sMsg = sRest.Token(2, true); sMsg.LeftChomp(); CChan* pChan = m_pNetwork->FindChan(sChan); if (pChan) { NETWORKMODULECALL(OnKick(Nick, sKickedNick, *pChan, sMsg), m_pNetwork->GetUser(), m_pNetwork, NULL, NOTHING); // do not remove the nick till after the OnKick call, so modules // can do Chan.FindNick or something to get more info. pChan->RemNick(sKickedNick); } if (GetNick().Equals(sKickedNick) && pChan) { pChan->SetIsOn(false); // Don't try to rejoin! pChan->Disable(); } if ((pChan) && (pChan->IsDetached())) { return; } } else if (sCmd.Equals("NOTICE")) { // :[email protected] NOTICE #chan :Message CString sTarget = sRest.Token(0); CString sMsg = sRest.Token(1, true); sMsg.LeftChomp(); if (sMsg.WildCmp("\001*\001")) { sMsg.LeftChomp(); sMsg.RightChomp(); if (sTarget.Equals(GetNick())) { if (OnCTCPReply(Nick, sMsg)) { return; } } m_pNetwork->PutUser(":" + Nick.GetNickMask() + " NOTICE " + sTarget + " :\001" + sMsg + "\001"); return; } else { if (sTarget.Equals(GetNick())) { if (OnPrivNotice(Nick, sMsg)) { return; } } else { if (OnChanNotice(Nick, sTarget, sMsg)) { return; } } } if (Nick.GetNick().Equals(m_pNetwork->GetIRCServer())) { m_pNetwork->PutUser(":" + Nick.GetNick() + " NOTICE " + sTarget + " :" + sMsg); } else { m_pNetwork->PutUser(":" + Nick.GetNickMask() + " NOTICE " + sTarget + " :" + sMsg); } return; } else if (sCmd.Equals("TOPIC")) { // :[email protected] TOPIC #chan :This is a topic CChan* pChan = m_pNetwork->FindChan(sLine.Token(2)); if (pChan) { CString sTopic = sLine.Token(3, true); sTopic.LeftChomp(); NETWORKMODULECALL(OnTopic(Nick, *pChan, sTopic), m_pNetwork->GetUser(), m_pNetwork, NULL, return); pChan->SetTopicOwner(Nick.GetNick()); pChan->SetTopicDate((unsigned long) time(NULL)); pChan->SetTopic(sTopic); if (pChan->IsDetached()) { return; // Don't forward this } sLine = ":" + Nick.GetNickMask() + " TOPIC " + pChan->GetName() + " :" + sTopic; } } else if (sCmd.Equals("PRIVMSG")) {
bool CFileUtil::writeString(IFileObject* file, const CString &str) { uint32 len = str.length(); return file->write(&len, sizeof(uint32)) && file->write(*str, len); }
void PageSerializer::serializeCSSStyleSheet(CSSStyleSheet* styleSheet, const KURL& url) { StringBuilder cssText; for (unsigned i = 0; i < styleSheet->length(); ++i) { CSSRule* rule = styleSheet->item(i); String itemText = rule->cssText(); if (!itemText.isEmpty()) { cssText.append(itemText); if (i < styleSheet->length() - 1) cssText.append("\n\n"); } Document* document = styleSheet->ownerDocument(); // Some rules have resources associated with them that we need to retrieve. if (rule->type() == CSSRule::IMPORT_RULE) { CSSImportRule* importRule = toCSSImportRule(rule); KURL importURL = document->completeURL(importRule->href()); if (m_resourceURLs.contains(importURL)) continue; serializeCSSStyleSheet(importRule->styleSheet(), importURL); } else if (rule->type() == CSSRule::FONT_FACE_RULE) { retrieveResourcesForProperties(toCSSFontFaceRule(rule)->styleRule()->properties(), document); } else if (rule->type() == CSSRule::STYLE_RULE) { retrieveResourcesForProperties(toCSSStyleRule(rule)->styleRule()->properties(), document); } } if (url.isValid() && !m_resourceURLs.contains(url)) { // FIXME: We should check whether a charset has been specified and if none was found add one. WTF::TextEncoding textEncoding(styleSheet->contents()->charset()); ASSERT(textEncoding.isValid()); String textString = cssText.toString(); CString text = textEncoding.normalizeAndEncode(textString, WTF::EntitiesForUnencodables); m_resources->append(SerializedResource(url, String("text/css"), SharedBuffer::create(text.data(), text.length()))); m_resourceURLs.add(url); } }
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family) { const char* name = 0; CString nameString; // Keeps name valid within scope of this function in case that name is from a family. // If a fallback font is being created (e.g. "-webkit-monospace"), convert // it in to the fallback name (e.g. "monospace"). if (!family.length() || family.startsWith("-webkit-")) name = getFallbackFontName(fontDescription); else { nameString = family.string().utf8(); name = nameString.data(); } int style = SkTypeface::kNormal; if (fontDescription.weight() >= FontWeightBold) style |= SkTypeface::kBold; if (fontDescription.italic()) style |= SkTypeface::kItalic; SkTypeface* typeface = 0; FontPlatformData* result = 0; if (PlatformSupport::layoutTestMode()) { CString customFontPath = getCustomFontPath(name, style & SkTypeface::kBold, style & SkTypeface::kItalic); if (customFontPath.length()) { typeface = SkTypeface::CreateFromFile(customFontPath.data()); result = new FontPlatformData(typeface, name, fontDescription.computedSize(), (style & SkTypeface::kBold) && !typeface->isBold(), (style & SkTypeface::kItalic) && !typeface->isItalic(), fontDescription.orientation(), fontDescription.textOrientation()); } } if (!typeface) { FallbackScripts fallbackScript = SkGetFallbackScriptFromID(name); if (SkTypeface_ValidScript(fallbackScript)) { // Do not use fallback fonts in layout test. if (PlatformSupport::layoutTestMode()) return NULL; typeface = SkCreateTypefaceForScript(fallbackScript); if (typeface) result = new FontPlatformData(typeface, name, fontDescription.computedSize(), (style & SkTypeface::kBold) && !typeface->isBold(), (style & SkTypeface::kItalic) && !typeface->isItalic(), fontDescription.orientation(), fontDescription.textOrientation()); } else { typeface = SkTypeface::CreateFromName(name, SkTypeface::kNormal); // CreateFromName always returns a typeface, falling back to a default font // if the one requested could not be found. Calling Equal() with a null // pointer will compare the returned font against the default, with the // caveat that the default is always of normal style. When that happens, // ignore the default font and allow WebCore to provide the next font on the // CSS fallback list. The only exception to this occurs when the family name // is a commonly used generic family, which is the case when called by // getSimilarFontPlatformData() or getLastResortFallbackFont(). In that case // the default font is an acceptable result. if (!SkTypeface::Equal(typeface, 0) || isFallbackFamily(family.string())) { // We had to use normal styling to see if this was a default font. If // we need bold or italic, replace with the corrected typeface. if (style != SkTypeface::kNormal) { typeface->unref(); typeface = SkTypeface::CreateFromName(name, static_cast<SkTypeface::Style>(style)); } result = new FontPlatformData(typeface, name, fontDescription.computedSize(), (style & SkTypeface::kBold) && !typeface->isBold(), (style & SkTypeface::kItalic) && !typeface->isItalic(), fontDescription.orientation(), fontDescription.textOrientation()); } } } SkSafeUnref(typeface); return result; }