void CalendarPickerElement::writeDocument(DocumentWriter& writer) { HTMLInputElement* input = hostInput(); DateComponents date; date.setMillisecondsSinceEpochForDate(input->minimum()); String minString = date.toString(); date.setMillisecondsSinceEpochForDate(input->maximum()); String maxString = date.toString(); Decimal step; String stepString = input->fastGetAttribute(stepAttr); if (stepString.isEmpty() || !input->getAllowedValueStep(&step)) stepString = "1"; addString("<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", writer); writer.addData(calendarPickerCss, sizeof(calendarPickerCss)); if (document()->page()) { CString extraStyle = document()->page()->theme()->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("min", minString, writer); addProperty("max", maxString, writer); addProperty("step", stepString, writer); addProperty("required", input->required(), writer); addProperty("currentValue", input->value(), writer); addProperty("locale", defaultLanguage(), writer); addProperty("todayLabel", calendarTodayText(), writer); addProperty("clearLabel", calendarClearText(), writer); addProperty("weekStartDay", firstDayOfWeek(), writer); addProperty("monthLabels", monthLabels(), writer); addProperty("dayLabels", weekDayShortLabels(), writer); Direction dir = direction(monthLabels()[0][0]); addProperty("isRTL", dir == RightToLeft || dir == RightToLeftArabic, writer); addString("}\n", writer); writer.addData(calendarPickerJs, sizeof(calendarPickerJs)); addString("</script></body>\n", writer); }
void COSXClipboard::add(EFormat format, const CString & data) { bool emptied = false; if (m_pboard == NULL) return; LOG((CLOG_DEBUG "add %d bytes to clipboard format: %d", data.size(), format)); for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { IOSXClipboardConverter* converter = *index; // skip converters for other formats if (converter->getFormat() == format) { CString osXData = converter->fromIClipboard(data); CFStringRef flavorType = converter->getOSXFormat(); CFDataRef dataRef = CFDataCreate(kCFAllocatorDefault, (UInt8 *)osXData.data(), osXData.size()); // integ tests showed that if you call add(...) twice, then the // second call will actually fail to set clipboard data. calling // empty() seems to solve this problem. but, only clear the clipboard // for the first converter, otherwise further converters will wipe out // what we just added. if (!emptied) { empty(); emptied = true; } PasteboardPutItemFlavor( m_pboard, (PasteboardItemID) 0, flavorType, dataRef, kPasteboardFlavorNoFlags); LOG((CLOG_DEBUG "added %d bytes to clipboard format: %d", data.size(), format)); } } }
void ResourceHandleManager::setupPOST(ResourceHandle* job) { ResourceHandleInternal* d = job->getInternal(); curl_easy_setopt(d->m_handle, CURLOPT_POST, TRUE); job->request().httpBody()->flatten(d->m_postBytes); if (d->m_postBytes.size() != 0) { curl_easy_setopt(d->m_handle, CURLOPT_POSTFIELDSIZE, d->m_postBytes.size()); curl_easy_setopt(d->m_handle, CURLOPT_POSTFIELDS, d->m_postBytes.data()); } Vector<FormDataElement> elements = job->request().httpBody()->elements(); size_t size = elements.size(); struct curl_httppost* lastItem = 0; struct curl_httppost* post = 0; for (size_t i = 0; i < size; i++) { if (elements[i].m_type != FormDataElement::encodedFile) continue; CString cstring = elements[i].m_filename.utf8(); ASSERT(!d->m_fileName); d->m_fileName = strdup(cstring.data()); // Fill in the file upload field curl_formadd(&post, &lastItem, CURLFORM_COPYNAME, "sendfile", CURLFORM_FILE, d->m_fileName, CURLFORM_END); // Fill in the filename field curl_formadd(&post, &lastItem, CURLFORM_COPYNAME, "filename", CURLFORM_COPYCONTENTS, d->m_fileName, CURLFORM_END); // FIXME: We should not add a "submit" field for each file uploaded. Review this code. // Fill in the submit field too, even if this is rarely needed curl_formadd(&post, &lastItem, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "send", CURLFORM_END); // FIXME: should we support more than one file? break; } if (post) curl_easy_setopt(d->m_handle, CURLOPT_HTTPPOST, post); }
void ChromeClient::mouseDidMoveOverElement(const HitTestResult& hit, unsigned modifierFlags) { iSeeLogA("ChromeClient::mouseDidMoveOverElement()\n"); // check if the element is a link... bool isLink = hit.isLiveLink(); if (isLink) { #if 0 KURL url = hit.absoluteLinkURL(); if (!url.isEmpty() && url != m_hoveredLinkURL) { CString titleString = hit.title().utf8(); DeprecatedCString urlString = url.prettyURL().utf8(); g_signal_emit_by_name(m_webView, "hovering-over-link", titleString.data(), urlString.data()); m_hoveredLinkURL = url; } #endif } else if (!isLink && !m_hoveredLinkURL.isEmpty()) { #if 0 g_signal_emit_by_name(m_webView, "hovering-over-link", 0, 0); m_hoveredLinkURL = KURL(); #endif } }
bool SecurityOrigin::isLocalhost() const { if (m_host == "localhost") return true; if (m_host == "[::1]") return true; // Test if m_host matches 127.0.0.1/8 ASSERT(m_host.containsOnlyASCII()); CString hostAscii = m_host.ascii(); Vector<uint8, 4> ipNumber; ipNumber.resize(4); int numComponents; url::Component hostComponent(0, hostAscii.length()); url::CanonHostInfo::Family family = url::IPv4AddressToNumber( hostAscii.data(), hostComponent, &(ipNumber)[0], &numComponents); if (family != url::CanonHostInfo::IPV4) return false; return ipNumber[0] == 127; }
sk_sp<SkTypeface> FontCache::createTypeface( const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, CString& name) { AtomicString family = creationParams.family(); if (family.isEmpty()) { name = getFallbackFontFamily(fontDescription).string().utf8(); } else { name = family.utf8(); } fonts::FontRequest request; request.family = name.data(); request.weight = ToIntegerWeight(fontDescription.weight()); request.width = static_cast<uint32_t>(fontDescription.stretch()); request.slant = ToFontSlant(fontDescription.style()); fonts::FontResponsePtr response; auto& font_provider = GetFontProvider(); font_provider->GetFont( std::move(request), [&response](fonts::FontResponsePtr r) { response = std::move(r); }); font_provider.WaitForResponse(); FXL_DCHECK(response) << "Unable to contact the font provider. Did you run " "Flutter in an environment that has a font manager?\n" "See <https://fuchsia.googlesource.com/modular/+/master/README.md>."; if (!response) return nullptr; sk_sp<SkData> data = MakeSkDataFromBuffer(response->data.buffer); if (!data) return nullptr; return SkFontMgr::RefDefault()->makeFromData(std::move(data)); }
xmlDocPtr XSLStyleSheet::locateStylesheetSubResource(xmlDocPtr parentDoc, const xmlChar* uri) { bool matchedParent = (parentDoc == document()); unsigned len = length(); for (unsigned i = 0; i < len; ++i) { StyleBase* rule = item(i); if (rule->isImportRule()) { XSLImportRule* import = static_cast<XSLImportRule*>(rule); XSLStyleSheet* child = import->styleSheet(); if (!child) continue; if (matchedParent) { if (child->processed()) continue; // libxslt has been given this sheet already. // Check the URI of the child stylesheet against the doc URI. // In order to ensure that libxml canonicalized both URLs, we get the original href // string from the import rule and canonicalize it using libxml before comparing it // with the URI argument. CString importHref = import->href().utf8(); xmlChar* base = xmlNodeGetBase(parentDoc, (xmlNodePtr)parentDoc); xmlChar* childURI = xmlBuildURI((const xmlChar*)importHref.data(), base); bool equalURIs = xmlStrEqual(uri, childURI); xmlFree(base); xmlFree(childURI); if (equalURIs) { child->markAsProcessed(); return child->document(); } } else { xmlDocPtr result = import->styleSheet()->locateStylesheetSubResource(parentDoc, uri); if (result) return result; } } } return 0; }
// Setters for the data. Using the ASCII version when you know the // data is ASCII will be slightly more efficient. The UTF-8 version // will always be correct if the caller is unsure. void KURLPrivate::setUTF8(const CString& string) { const char* data = string.data(); unsigned dataLength = string.length(); // The m_utf8IsASCII must always be correct since the DeprecatedString // getter must create it with the proper constructor. This test can be // removed when DeprecatedString is gone, but it still might be a // performance win. m_utf8IsASCII = true; for (unsigned i = 0; i < dataLength; i++) { if (static_cast<unsigned char>(data[i]) >= 0x80) { m_utf8IsASCII = false; break; } } m_utf8 = string; m_stringIsValid = false; initProtocolIsInHTTPFamily(); initInnerURL(); }
void WebSocketServerConnection::sendHTTPResponseHeader(int statusCode, const String& statusText, const HTTPHeaderMap& headerFields) { if (!m_socket) return; StringBuilder builder; builder.append("HTTP/1.1 "); builder.append(String::number(statusCode)); builder.append(" "); builder.append(statusText); builder.append("\r\n"); HTTPHeaderMap::const_iterator end = headerFields.end(); for (HTTPHeaderMap::const_iterator it = headerFields.begin(); it != end; ++it) { builder.append(it->key); builder.append(": "); builder.append(it->value + "\r\n"); } builder.append("\r\n"); CString header = builder.toString().latin1(); m_socket->send(header.data(), header.length()); }
static void serverCallback(SoupServer* httpServer, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) { if (message->method != SOUP_METHOD_GET) { soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); return; } if (!strcmp(path, "/favicon.ico")) { CString faviconPath = environment->pathForResource("blank.ico"); Eina_File* f = eina_file_open(faviconPath.data(), false); if (!f) { soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); soup_message_body_complete(message->response_body); return; } size_t fileSize = eina_file_size_get(f); void* contents = eina_file_map_all(f, EINA_FILE_POPULATE); if (!contents) { soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); soup_message_body_complete(message->response_body); return; } soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, contents, fileSize); soup_message_set_status(message, SOUP_STATUS_OK); soup_message_body_complete(message->response_body); eina_file_map_free(f, contents); eina_file_close(f); return; } const char contents[] = "<html><body>favicon test</body></html>"; soup_message_set_status(message, SOUP_STATUS_OK); soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, contents, strlen(contents)); soup_message_body_complete(message->response_body); }
void PageClientBase::processDidCrash() { // Check if loading was ongoing, when web process crashed. double loadProgress = ewk_view_load_progress_get(m_view->evasObject()); if (loadProgress >= 0 && loadProgress < 1) { loadProgress = 1; m_view->smartCallback<LoadProgress>().call(&loadProgress); } m_view->smartCallback<TooltipTextUnset>().call(); bool handled = false; m_view->smartCallback<WebProcessCrashed>().call(&handled); if (!handled) { CString url = m_view->page()->urlAtProcessExit().utf8(); WARN("WARNING: The web process experienced a crash on '%s'.\n", url.data()); // Display an error page ewk_view_html_string_load(m_view->evasObject(), "The web process has crashed.", 0, url.data()); } }
Vector<String> listDirectory(const String& path, const String& filter) { Vector<String> matchingEntries; CString cfilter = filter.utf8(); const char *f_name; Eina_Iterator* it = eina_file_ls(path.utf8().data()); // FIXME: Early return if the iterator is null to avoid error messages from eina_iterator_free(). // This check can be removed once the magic check on _free() removed in Eina. // http://www.mail-archive.com/[email protected]/msg42944.html if (!it) return matchingEntries; EINA_ITERATOR_FOREACH(it, f_name) { if (!fnmatch(cfilter.data(), f_name, 0)) matchingEntries.append(String::fromUTF8(f_name)); eina_stringshare_del(f_name); } eina_iterator_free(it); return matchingEntries; }
void ProfileGenerator::didExecute(ExecState* callerCallFrame, const CallIdentifier& callIdentifier) { if (JAVASCRIPTCORE_PROFILE_DID_EXECUTE_ENABLED()) { CString name = callIdentifier.m_name.utf8(); CString url = callIdentifier.m_url.utf8(); JAVASCRIPTCORE_PROFILE_DID_EXECUTE(m_profileGroup, const_cast<char*>(name.data()), const_cast<char*>(url.data()), callIdentifier.m_lineNumber); } if (!m_origin) return; ASSERT(m_currentNode); if (m_currentNode->callIdentifier() != callIdentifier) { RefPtr<ProfileNode> returningNode = ProfileNode::create(callerCallFrame, callIdentifier, m_head.get(), m_currentNode.get()); returningNode->setStartTime(m_currentNode->startTime()); returningNode->didExecute(); m_currentNode->insertNode(returningNode.release()); return; } m_currentNode = m_currentNode->didExecute(); }
void PaintController::checkUnderInvalidation(DisplayItemList::iterator& newIt, DisplayItemList::iterator& currentIt) { ASSERT(RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()); ASSERT(newIt->isCached()); // When under-invalidation-checking is enabled, the forced painting is following the cached display item. DisplayItem::Type nextItemType = DisplayItem::nonCachedType(newIt->type()); ++newIt; ASSERT(newIt->type() == nextItemType); if (newIt->isDrawing()) { checkCachedDisplayItemIsUnchanged("", *newIt, *currentIt); return; } ASSERT(newIt->type() == DisplayItem::Subsequence); #ifndef NDEBUG CString messagePrefix = String::format("(In CachedSubsequence of %s)", newIt->clientDebugString().utf8().data()).utf8(); #else CString messagePrefix = "(In CachedSubsequence)"; #endif DisplayItem::Id endSubsequenceId(newIt->client(), DisplayItem::EndSubsequence, 0); while (true) { ASSERT(newIt != m_newDisplayItemList.end()); if (newIt->isCached()) checkUnderInvalidation(newIt, currentIt); else checkCachedDisplayItemIsUnchanged(messagePrefix.data(), *newIt, *currentIt); if (endSubsequenceId.matches(*newIt)) break; ++newIt; ++currentIt; } }
// Variant value must be released with NPReleaseVariantValue() void convertValueToNPVariant(ExecState* exec, JSValue value, NPVariant* result) { JSLockHolder lock(exec); VOID_TO_NPVARIANT(*result); if (value.isString()) { UString ustring = value.toString(exec)->value(exec); CString cstring = ustring.utf8(); NPString string = { (const NPUTF8*)cstring.data(), static_cast<uint32_t>(cstring.length()) }; NPN_InitializeVariantWithStringCopy(result, &string); } else if (value.isNumber()) { DOUBLE_TO_NPVARIANT(value.toNumber(exec), *result); } else if (value.isBoolean()) { BOOLEAN_TO_NPVARIANT(value.toBoolean(exec), *result); } else if (value.isNull()) { NULL_TO_NPVARIANT(*result); } else if (value.isObject()) { JSObject* object = asObject(value); if (object->classInfo() == &CRuntimeObject::s_info) { CRuntimeObject* runtimeObject = static_cast<CRuntimeObject*>(object); CInstance* instance = runtimeObject->getInternalCInstance(); if (instance) { NPObject* obj = instance->getObject(); _NPN_RetainObject(obj); OBJECT_TO_NPVARIANT(obj, *result); } } else { JSGlobalObject* globalObject = exec->dynamicGlobalObject(); RootObject* rootObject = findRootObject(globalObject); if (rootObject) { NPObject* npObject = _NPN_CreateScriptObject(0, object, rootObject); OBJECT_TO_NPVARIANT(npObject, *result); } } } }
void IClipboard::unmarshall(IClipboard* clipboard, const CString& data, Time time) { assert(clipboard != NULL); const char* index = data.data(); // clear existing data clipboard->open(time); clipboard->empty(); // read the number of formats const UInt32 numFormats = readUInt32(index); index += 4; // read each format for (UInt32 i = 0; i < numFormats; ++i) { // get the format id IClipboard::EFormat format = static_cast<IClipboard::EFormat>(readUInt32(index)); index += 4; // get the size of the format data UInt32 size = readUInt32(index); index += 4; // save the data if it's a known format. if either the client // or server supports more clipboard formats than the other // then one of them will get a format >= kNumFormats here. if (format <IClipboard::kNumFormats) { clipboard->add(format, CString(index, size)); } index += size; } // done clipboard->close(); }
static bool isValidYouTubeVideo(const String& path) { if (!charactersAreAllASCII(path.characters(), path.length())) return false; unsigned int len = path.length(); if (len <= sizeof(slash_v_slash)) // check for more than just /v/ return false; CString str = path.lower().utf8(); const char* data = str.data(); if (memcmp(data, slash_v_slash, sizeof(slash_v_slash)) != 0) return false; // Start after /v/ for (unsigned int i = sizeof(slash_v_slash); i < len; i++) { char c = data[i]; // Check for alpha-numeric characters only. if (WTF::isASCIIAlphanumeric(c) || c == '_' || c == '-') continue; // The url can have more parameters such as &hl=en after the video id. // Once we start seeing extra parameters we can return true. return c == '&' && i > sizeof(slash_v_slash); } return true; }
void FrameLoaderClientEfl::dispatchWillSendRequest(DocumentLoader* loader, unsigned long identifier, ResourceRequest& coreRequest, const ResourceResponse& coreResponse) { CString url = coreRequest.url().string().utf8(); CString firstParty = coreRequest.firstPartyForCookies().string().utf8(); CString httpMethod = coreRequest.httpMethod().utf8(); DBG("Resource url=%s, first_party=%s, http_method=%s", url.data(), firstParty.data(), httpMethod.data()); // We want to distinguish between a request for a document to be loaded into // the main frame, a sub-frame, or the sub-objects in that document. bool isMainFrameRequest = false; if (loader) { const FrameLoader* frameLoader = loader->frameLoader(); isMainFrameRequest = (loader == frameLoader->provisionalDocumentLoader() && frameLoader->isLoadingMainFrame()); } Ewk_Frame_Resource_Request request = { 0, firstParty.data(), httpMethod.data(), identifier, m_frame, isMainFrameRequest }; Ewk_Frame_Resource_Request orig = request; /* Initialize const fields. */ orig.url = request.url = url.data(); Ewk_Frame_Resource_Response* redirectResponse; Ewk_Frame_Resource_Response responseBuffer; CString redirectUrl; if (coreResponse.isNull()) redirectResponse = 0; else { redirectUrl = coreResponse.url().string().utf8(); responseBuffer.url = redirectUrl.data(); responseBuffer.status_code = coreResponse.httpStatusCode(); redirectResponse = &responseBuffer; } Ewk_Frame_Resource_Messages messages = { &request, redirectResponse }; ewk_frame_request_will_send(m_frame, &messages); evas_object_smart_callback_call(m_view, "resource,request,willsend", &messages); if (request.url != orig.url) { coreRequest.setURL(KURL(KURL(), request.url)); // Calling client might have changed our url pointer. // Free the new allocated string. free(const_cast<char*>(request.url)); } }
void MHTMLArchive::generateMHTMLHeader( const String& boundary, const String& title, const String& mimeType, SharedBuffer& outputBuffer) { ASSERT(!boundary.isEmpty()); ASSERT(!mimeType.isEmpty()); DateComponents now; now.setMillisecondsSinceEpochForDateTime(currentTimeMS()); // TODO(lukasza): Passing individual date/time components seems fragile. String dateString = makeRFC2822DateString( now.weekDay(), now.monthDay(), now.month(), now.fullYear(), now.hour(), now.minute(), now.second(), 0); StringBuilder stringBuilder; stringBuilder.appendLiteral("From: <Saved by Blink>\r\n"); stringBuilder.appendLiteral("Subject: "); // We replace non ASCII characters with '?' characters to match IE's behavior. stringBuilder.append(replaceNonPrintableCharacters(title)); stringBuilder.appendLiteral("\r\nDate: "); stringBuilder.append(dateString); stringBuilder.appendLiteral("\r\nMIME-Version: 1.0\r\n"); stringBuilder.appendLiteral("Content-Type: multipart/related;\r\n"); stringBuilder.appendLiteral("\ttype=\""); stringBuilder.append(mimeType); stringBuilder.appendLiteral("\";\r\n"); stringBuilder.appendLiteral("\tboundary=\""); stringBuilder.append(boundary); stringBuilder.appendLiteral("\"\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(); outputBuffer.append(asciiString.data(), asciiString.length()); }
void ProcessLauncher::launchProcess() { GPid pid = 0; int sockets[2]; if (socketpair(AF_UNIX, SOCKET_TYPE, 0, sockets) < 0) { g_printerr("Creation of socket failed: %s.\n", g_strerror(errno)); ASSERT_NOT_REACHED(); return; } String executablePath = m_launchOptions.processType == WebProcess ? executablePathOfWebProcess() : executablePathOfPluginProcess(); CString binaryPath = fileSystemRepresentation(executablePath); GOwnPtr<gchar> socket(g_strdup_printf("%d", sockets[0])); char* argv[3]; argv[0] = const_cast<char*>(binaryPath.data()); argv[1] = socket.get(); argv[2] = 0; GOwnPtr<GError> error; int spawnFlags = G_SPAWN_LEAVE_DESCRIPTORS_OPEN | G_SPAWN_DO_NOT_REAP_CHILD; if (!g_spawn_async(0, argv, 0, static_cast<GSpawnFlags>(spawnFlags), childSetupFunction, GINT_TO_POINTER(sockets[1]), &pid, &error.outPtr())) { g_printerr("Unable to fork a new WebProcess: %s.\n", error->message); ASSERT_NOT_REACHED(); } close(sockets[0]); m_processIdentifier = pid; // Monitor the child process, it calls waitpid to prevent the child process from becomming a zombie, // and it allows us to close the socket when the child process crashes. g_child_watch_add(m_processIdentifier, childFinishedFunction, GINT_TO_POINTER(sockets[1])); // We've finished launching the process, message back to the main run loop. RunLoop::main()->dispatch(bind(&ProcessLauncher::didFinishLaunchingProcess, this, m_processIdentifier, sockets[1])); }
// In KURL.cpp's implementation, this is called by every component getter. // It will unescape every character, including '\0'. This is scary, and may // cause security holes. We never call this function for components, and // just return the ASCII versions instead. // // This function is also used to decode javascript: URLs and as a general // purpose unescaping function. // // FIXME These should be merged to the KURL.cpp implementation. String decodeURLEscapeSequences(const String& str, const TextEncoding& encoding) { // FIXME We can probably use KURL.cpp's version of this function // without modification. However, I'm concerned about // https://bugs.webkit.org/show_bug.cgi?id=20559 so am keeping this old // custom code for now. Using their version will also fix the bug that // we ignore the encoding. // // FIXME b/1350291: This does not get called very often. We just convert // first to 8-bit UTF-8, then unescape, then back to 16-bit. This kind of // sucks, and we don't use the encoding properly, which will make some // obscure anchor navigations fail. CString cstr = str.utf8(); const char* input = cstr.data(); int inputLength = cstr.length(); url_canon::RawCanonOutputT<url_parse::UTF16Char> unescaped; url_util::DecodeURLEscapeSequences(input, inputLength, &unescaped); return String(reinterpret_cast<UChar*>(unescaped.data()), unescaped.length()); }
HANDLE CMSWindowsClipboardAnyTextConverter::fromIClipboard(const CString& data) const { // convert linefeeds and then convert to desired encoding CString text = doFromIClipboard(convertLinefeedToWin32(data)); UInt32 size = (UInt32)text.size(); // copy to memory handle HGLOBAL gData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, size); if (gData != NULL) { // get a pointer to the allocated memory char* dst = (char*)GlobalLock(gData); if (dst != NULL) { memcpy(dst, text.data(), size); GlobalUnlock(gData); } else { GlobalFree(gData); gData = NULL; } } return gData; }
void XMLDocumentParser::initializeParserContext(const CString& chunk) { xmlSAXHandler sax; memset(&sax, 0, sizeof(sax)); sax.error = normalErrorHandler; sax.fatalError = fatalErrorHandler; sax.characters = charactersHandler; sax.processingInstruction = processingInstructionHandler; sax.cdataBlock = cdataBlockHandler; sax.comment = commentHandler; sax.warning = warningHandler; sax.startElementNs = startElementNsHandler; sax.endElementNs = endElementNsHandler; sax.getEntity = getEntityHandler; sax.startDocument = startDocumentHandler; sax.endDocument = endDocumentHandler; sax.internalSubset = internalSubsetHandler; sax.externalSubset = externalSubsetHandler; sax.ignorableWhitespace = ignorableWhitespaceHandler; sax.entityDecl = xmlSAX2EntityDecl; sax.initialized = XML_SAX2_MAGIC; DocumentParser::startParsing(); m_sawError = false; m_sawCSS = false; m_sawXSLTransform = false; m_sawFirstElement = false; XMLDocumentParserScope scope(document()->cachedResourceLoader()); if (m_parsingFragment) m_context = XMLParserContext::createMemoryParser(&sax, this, chunk); else { ASSERT(!chunk.data()); m_context = XMLParserContext::createStringParser(&sax, this); } }
static gchar* dumpFramesAsText(WebKitWebFrame* frame) { gchar* result = 0; // Add header for all but the main frame. bool isMainFrame = (webkit_web_view_get_main_frame(webView) == frame); CString innerText = DumpRenderTreeSupportGtk::getInnerText(frame); if (isMainFrame) result = g_strdup_printf("%s\n", innerText.data()); else { const gchar* frameName = webkit_web_frame_get_name(frame); result = g_strdup_printf("\n--------\nFrame: '%s'\n--------\n%s\n", frameName, innerText.data()); } if (gLayoutTestController->dumpChildFramesAsText()) { GSList* children = DumpRenderTreeSupportGtk::getFrameChildren(frame); for (GSList* child = children; child; child = g_slist_next(child)) appendString(result, dumpFramesAsText(static_cast<WebKitWebFrame* >(child->data))); g_slist_free(children); } 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"); } Document* document = styleSheet->findDocument(); // Some rules have resources associated with them that we need to retrieve. if (rule->isImportRule()) { CSSImportRule* importRule = static_cast<CSSImportRule*>(rule); 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), 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. 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 CDCCSock::ReadData(const char* data, size_t len) { if (!m_pFile) { DEBUG("File not open! closing get."); m_pModule->PutModule(((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File not open!"); Close(); } // DCC specs says the receiving end sends the number of bytes it // received so far as a 4 byte integer in network byte order, so we need // uint32_t to do the job portably. This also means that the maximum // file that we can transfer is 4 GiB big (see OpenFile()). if (m_bSend) { m_sSendBuf.append(data, len); while (m_sSendBuf.size() >= 4) { uint32_t iRemoteSoFar; memcpy(&iRemoteSoFar, m_sSendBuf.data(), sizeof(iRemoteSoFar)); iRemoteSoFar = ntohl(iRemoteSoFar); if ((iRemoteSoFar + 65536) >= m_uBytesSoFar) { SendPacket(); } m_sSendBuf.erase(0, 4); } } else { m_pFile->Write(data, len); m_uBytesSoFar += len; uint32_t uSoFar = htonl(m_uBytesSoFar); Write((char*) &uSoFar, sizeof(uSoFar)); if (m_uBytesSoFar >= m_uFileSize) { Close(); } } }
void FrameLoaderClientEfl::dispatchDidFailLoading(DocumentLoader*, unsigned long identifier, const ResourceError& err) { Ewk_Frame_Load_Error error; CString errorDomain = err.domain().utf8(); CString errorDescription = err.localizedDescription().utf8(); CString failingUrl = err.failingURL().utf8(); DBG("ewkFrame=%p, resource=%ld, error=%s (%d, cancellation=%hhu) \"%s\", url=%s", m_frame, identifier, errorDomain.data(), err.errorCode(), err.isCancellation(), errorDescription.data(), failingUrl.data()); error.code = err.errorCode(); error.is_cancellation = err.isCancellation(); error.domain = errorDomain.data(); error.description = errorDescription.data(); error.failing_url = failingUrl.data(); error.resource_identifier = identifier; error.frame = m_frame; ewk_frame_load_resource_failed(m_frame, &error); evas_object_smart_callback_call(m_view, "load,resource,failed", &error); }
static void testWebKitSettingsUserAgent(WebViewTest* test, gconstpointer) { GRefPtr<WebKitSettings> settings = adoptGRef(webkit_settings_new()); CString defaultUserAgent = webkit_settings_get_user_agent(settings.get()); webkit_web_view_set_settings(test->m_webView, settings.get()); g_assert(g_strstr_len(defaultUserAgent.data(), -1, "AppleWebKit")); g_assert(g_strstr_len(defaultUserAgent.data(), -1, "Safari")); webkit_settings_set_user_agent(settings.get(), 0); g_assert_cmpstr(defaultUserAgent.data(), ==, webkit_settings_get_user_agent(settings.get())); assertThatUserAgentIsSentInHeaders(test, defaultUserAgent.data()); webkit_settings_set_user_agent(settings.get(), ""); g_assert_cmpstr(defaultUserAgent.data(), ==, webkit_settings_get_user_agent(settings.get())); const char* funkyUserAgent = "Funky!"; webkit_settings_set_user_agent(settings.get(), funkyUserAgent); g_assert_cmpstr(funkyUserAgent, ==, webkit_settings_get_user_agent(settings.get())); assertThatUserAgentIsSentInHeaders(test, funkyUserAgent); webkit_settings_set_user_agent_with_application_details(settings.get(), "WebKitGTK+", 0); const char* userAgentWithNullVersion = webkit_settings_get_user_agent(settings.get()); g_assert_cmpstr(g_strstr_len(userAgentWithNullVersion, -1, defaultUserAgent.data()), ==, userAgentWithNullVersion); g_assert(g_strstr_len(userAgentWithNullVersion, -1, "WebKitGTK+")); webkit_settings_set_user_agent_with_application_details(settings.get(), "WebKitGTK+", ""); g_assert_cmpstr(webkit_settings_get_user_agent(settings.get()), ==, userAgentWithNullVersion); webkit_settings_set_user_agent_with_application_details(settings.get(), "WebCatGTK+", "3.4.5"); const char* newUserAgent = webkit_settings_get_user_agent(settings.get()); g_assert(g_strstr_len(newUserAgent, -1, "3.4.5")); g_assert(g_strstr_len(newUserAgent, -1, "WebCatGTK+")); GUniquePtr<char> applicationUserAgent(g_strdup_printf("%s %s", defaultUserAgent.data(), "WebCatGTK+/3.4.5")); g_assert_cmpstr(applicationUserAgent.get(), ==, webkit_settings_get_user_agent(settings.get())); }
void FrameLoaderClientAndroid::dispatchDidFailProvisionalLoad(const ResourceError& error) { ASSERT(m_frame); // Ignore ErrorInterrupted since it is due to a policy interruption. This // is caused by a decision to download the main resource rather than // display it. if (error.errorCode() == InternalErrorInterrupted || error.errorCode() == InternalErrorCancelled) { // If we decided to download the main resource or if the user cancelled // it, make sure we report that the load is done. didFinishLoad(); return; } AssetManager* am = globalAssetManager(); // Check to see if the error code was not generated internally WebCore::PlatformBridge::rawResId id = WebCore::PlatformBridge::NoDomain; if ((error.errorCode() == ErrorFile || error.errorCode() == ErrorFileNotFound) && (!error.localizedDescription().isEmpty())) { id = WebCore::PlatformBridge::LoadError; } String filename = m_webFrame->getRawResourceFilename(id); if (filename.isEmpty()) return; // Grab the error page from the asset manager Asset* a = am->openNonAsset( filename.utf8().data(), Asset::ACCESS_BUFFER); if (!a) return; // Take the failing url and encode html entities so javascript urls are not // executed. CString failingUrl = error.failingURL().utf8(); WTF::Vector<char> url; int len = failingUrl.length(); const char* data = failingUrl.data(); for (int i = 0; i < len; i++) { char c = data[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) url.append(c); else { char buf[16]; int res = sprintf(buf, "&#%d;", c); buf[res] = 0; url.append(buf, res); } } // Replace all occurances of %s with the failing url. String s = UTF8Encoding().decode((const char*)a->getBuffer(false), a->getLength()); // samsung shkim // \frameworks\base\core\res\res\raw-XX\nodomain.html or loaderror.html // These error pages does not have <viewport> tag, it is loaded as low zoom scale if( s.contains( "viewport" ) == false ) s = s.replace( "<head>", "<head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"/>" ); s = s.replace("%s", String(url.data(), url.size())); // Replace all occurances of %e with the error text s = s.replace("%e", error.localizedDescription()); // Create the request and the substitute data and tell the FrameLoader to // load with the replacement data. // use KURL(const char*) as KURL(const String& url) can trigger ASSERT for // invalidate URL string. loadDataIntoFrame(m_frame, KURL(ParsedURLString, data), error.failingURL(), s); // Delete the asset. delete a; }
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()); }