TEST_F(EWK2DownloadJobTest, ewk_download)
{
    OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer);
    httpServer->run(serverCallback);

    // Generate unique name for destination file.
    char destinationPath[] = "/tmp/pdf-file.XXXXXX";
    ASSERT_TRUE(mktemp(destinationPath));

    CString fileUrl = httpServer->getURLForPath(testFilePath);

    DownloadTestData userData = { fileUrl.data(), destinationPath };
    ASSERT_FALSE(fileExists(destinationPath));

    evas_object_smart_callback_add(webView(), "download,request", on_download_requested, &userData);
    evas_object_smart_callback_add(webView(), "download,cancel", on_download_cancelled, &userData);
    evas_object_smart_callback_add(webView(), "download,failed", on_download_failed, &userData);
    evas_object_smart_callback_add(webView(), "download,finished", on_download_finished, &userData);

    // Download test pdf
    ewk_view_url_set(webView(), fileUrl.data());
    ecore_main_loop_begin();

    // Clean up
    unlink(destinationPath);
}
Example #2
0
void TextCheckerEnchant::updateSpellCheckingLanguages(const Vector<String>& languages)
{
    Vector<EnchantDict*> spellDictionaries;

    if (!languages.isEmpty()) {
        for (Vector<String>::const_iterator iter = languages.begin(); iter != languages.end(); ++iter) {
            CString currentLanguage = iter->utf8();
            if (enchant_broker_dict_exists(m_broker, currentLanguage.data())) {
                EnchantDict* dict = enchant_broker_request_dict(m_broker, currentLanguage.data());
                spellDictionaries.append(dict);
            }
        }
    } else {
        const char* language = pango_language_to_string(pango_language_get_default());
        if (enchant_broker_dict_exists(m_broker, language)) {
            EnchantDict* dict = enchant_broker_request_dict(m_broker, language);
            spellDictionaries.append(dict);
        } else {
            // No dictionaries selected, we get one from the list.
            Vector<CString> allDictionaries;
            enchant_broker_list_dicts(m_broker, enchantDictDescribeCallback, &allDictionaries);
            if (!allDictionaries.isEmpty()) {
                EnchantDict* dict = enchant_broker_request_dict(m_broker, allDictionaries[0].data());
                spellDictionaries.append(dict);
            }
        }
    }
    freeEnchantBrokerDictionaries();
    m_enchantDictionaries = spellDictionaries;
}
Example #3
0
CString openTemporaryFile(const char* prefix, PlatformFileHandle& handle)
{
    // BREW does not have a system-wide temporary directory,
    // use "fs:/~/tmp" as our temporary directory.
    String tempPath("fs:/~/tmp");

    PlatformRefPtr<IFileMgr> fileMgr = createRefPtrInstance<IFileMgr>(AEECLSID_FILEMGR);

    // Create the temporary directory if it does not exist.
    IFILEMGR_MkDir(fileMgr.get(), tempPath.utf8().data());

    // Loop until we find a temporary filename that does not exist.
    int number = static_cast<int>(randomNumber() * 10000);
    CString filename;
    do {
        StringBuilder builder;
        builder.append(tempPath);
        builder.append('/');
        builder.append(prefix);
        builder.append(String::number(number));
        filename = builder.toString().utf8();
        number++;
    } while (IFILEMGR_Test(fileMgr.get(), filename.data()) == SUCCESS);

    IFile* tempFile = IFILEMGR_OpenFile(fileMgr.get(), filename.data(), _OFM_CREATE);
    if (tempFile) {
        handle = tempFile;
        return filename;
    }

    return CString();
}
Example #4
0
bool makeAllDirectories(const String& path)
{
    CString fullPath = fileSystemRepresentation(path);
    if (!access(fullPath.data(), F_OK))
        return true;

    char* p = fullPath.mutableData() + 1;
    int length = fullPath.length();

    if(p[length - 1] == '/')
        p[length - 1] = '\0';
    for (; *p; ++p)
        if (*p == '/') {
            *p = '\0';
            if (access(fullPath.data(), F_OK))
                if (mkdir(fullPath.data(), S_IRWXU))
                    return false;
            *p = '/';
        }
    if (access(fullPath.data(), F_OK))
        if (mkdir(fullPath.data(), S_IRWXU))
            return false;

    return true;
}
Example #5
0
String directoryName(const String& path)
{
    CString fsRep = fileSystemRepresentation(path);

    if (!fsRep.data() || fsRep.data()[0] == '\0')
        return String();

    return dirname(fsRep.mutableData());
}
Example #6
0
bool deleteFile(const String& path)
{
    CString fsRep = fileSystemRepresentation(path);

    if (!fsRep.data() || fsRep.data()[0] == '\0')
        return false;

    // unlink(...) returns 0 on successful deletion of the path and non-zero in any other case (including invalid permissions or non-existent file)
    return !unlink(fsRep.data());
}
Example #7
0
void PasteboardHelper::fillSelectionData(GtkSelectionData* selectionData, guint info, DataObjectGtk* dataObject)
{
    if (info == TargetTypeText)
        gtk_selection_data_set_text(selectionData, dataObject->text().utf8().data(), -1);

    else if (info == TargetTypeMarkup) {
        // Some Linux applications refuse to accept pasted markup unless it is
        // prefixed by a content-type meta tag.
        CString markup = String(gMarkupPrefix + dataObject->markup()).utf8();
        gtk_selection_data_set(selectionData, markupAtom, 8,
                               reinterpret_cast<const guchar*>(markup.data()), markup.length());

    } else if (info == TargetTypeURIList) {
        CString uriList = dataObject->uriList().utf8();
        gtk_selection_data_set(selectionData, uriListAtom, 8,
                               reinterpret_cast<const guchar*>(uriList.data()), uriList.length());

    } else if (info == TargetTypeNetscapeURL && dataObject->hasURL()) {
        String url(dataObject->url());
        String result(url);
        result.append("\n");

        if (dataObject->hasText())
            result.append(dataObject->text());
        else
            result.append(url);

        GUniquePtr<gchar> resultData(g_strdup(result.utf8().data()));
        gtk_selection_data_set(selectionData, netscapeURLAtom, 8,
                               reinterpret_cast<const guchar*>(resultData.get()), strlen(resultData.get()));

    } else if (info == TargetTypeImage)
        gtk_selection_data_set_pixbuf(selectionData, dataObject->image());

    else if (info == TargetTypeSmartPaste)
        gtk_selection_data_set_text(selectionData, "", -1);

    else if (info == TargetTypeUnknown) {
        GVariantBuilder builder;
        g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);

        auto types = dataObject->unknownTypes();
        auto end = types.end();
        for (auto it = types.begin(); it != end; ++it) {
            GUniquePtr<gchar> dictItem(g_strdup_printf("{'%s', '%s'}", it->key.utf8().data(), it->value.utf8().data()));
            g_variant_builder_add_parsed(&builder, dictItem.get());
        }

        GRefPtr<GVariant> variant = g_variant_builder_end(&builder);
        GUniquePtr<gchar> serializedVariant(g_variant_print(variant.get(), TRUE));
        gtk_selection_data_set(selectionData, unknownAtom, 1, reinterpret_cast<const guchar*>(serializedVariant.get()), strlen(serializedVariant.get()));
    }
}
Example #8
0
bool PluginProcessProxy::scanPlugin(const String& pluginPath, RawPluginMetaData& result)
{
#if PLATFORM(GTK) || (PLATFORM(EFL) && ENABLE(GLIB_SUPPORT))
    CString binaryPath = fileSystemRepresentation(executablePathOfPluginProcess());
    CString pluginPathCString = fileSystemRepresentation(pluginPath);
    char* argv[4];
    argv[0] = const_cast<char*>(binaryPath.data());
    argv[1] = const_cast<char*>("-scanPlugin");
    argv[2] = const_cast<char*>(pluginPathCString.data());
    argv[3] = 0;

    int status;
    char* stdOut = 0;

    // If the disposition of SIGCLD signal is set to SIG_IGN (default)
    // then the signal will be ignored and g_spawn_sync() will not be
    // able to return the status.
    // As a consequence, we make sure that the disposition is set to
    // SIG_DFL before calling g_spawn_sync().
    struct sigaction action;
    sigaction(SIGCLD, 0, &action);
    if (action.sa_handler == SIG_IGN) {
        action.sa_handler = SIG_DFL;
        sigaction(SIGCLD, &action, 0);
    }

    if (!g_spawn_sync(0, argv, 0, G_SPAWN_STDERR_TO_DEV_NULL, 0, 0, &stdOut, 0, &status, 0))
        return false;

    if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS || !stdOut) {
        free(stdOut);
        return false;
    }

    String stdOutString(reinterpret_cast<const UChar*>(stdOut));
    free(stdOut);

    Vector<String> lines;
    stdOutString.split(UChar('\n'), lines);

    if (lines.size() < 3)
        return false;

    result.name.swap(lines[0]);
    result.description.swap(lines[1]);
    result.mimeDescription.swap(lines[2]);
    return !result.mimeDescription.isEmpty();
#else // PLATFORM(GTK) || (PLATFORM(EFL) && ENABLE(GLIB_SUPPORT))
    return false;
#endif // PLATFORM(GTK) || (PLATFORM(EFL) && ENABLE(GLIB_SUPPORT))
}
Example #9
0
static void expectMD5(CString input, CString expected)
{
    MD5 md5;
    md5.addBytes(reinterpret_cast<const uint8_t*>(input.data()), input.length());
    MD5::Digest digest;
    md5.checksum(digest);
    char* buf = 0;
    CString actual = CString::newUninitialized(32, buf);
    for (size_t i = 0; i < MD5::hashSize; i++, buf += 2)
        snprintf(buf, 3, "%02x", digest[i]);

    ASSERT_EQ(expected.length(), actual.length());
    ASSERT_STREQ(expected.data(), actual.data());
}
Example #10
0
bool getFileModificationTime(const String& path, time_t& result)
{
    CString fsRep = fileSystemRepresentation(path);

    if (!fsRep.data() || fsRep.data()[0] == '\0')
        return false;

    struct stat fileInfo;

    if (stat(fsRep.data(), &fileInfo))
        return false;

    result = fileInfo.st_mtime;
    return true;
}
Example #11
0
bool fileExists(const String& path)
{
    if (path.isNull())
        return false;

    CString fsRep = fileSystemRepresentation(path);

    if (!fsRep.data() || fsRep.data()[0] == '\0')
        return false;

    struct stat fileInfo;

    // stat(...) returns 0 on successful stat'ing of the file, and non-zero in any case where the file doesn't exist or cannot be accessed
    return !stat(fsRep.data(), &fileInfo);
}
Example #12
0
bool getFileSize(const String& path, long long& result)
{
    CString fsRep = fileSystemRepresentation(path);

    if (!fsRep.data() || fsRep.data()[0] == '\0')
        return false;

    struct stat fileInfo;

    if (stat(fsRep.data(), &fileInfo))
        return false;

    result = fileInfo.st_size;
    return true;
}
void WebInspectorServer::buildPageList(Vector<char>& data, String& contentType)
{
    StringBuilder builder;
    builder.appendLiteral("[ ");
    ClientMap::iterator end = m_clientMap.end();
    for (ClientMap::iterator it = m_clientMap.begin(); it != end; ++it) {
        WebPageProxy* webPage = it->value->page();
        if (it != m_clientMap.begin())
            builder.appendLiteral(", ");
        builder.appendLiteral("{ \"id\": ");
        builder.appendNumber(it->key);
        builder.appendLiteral(", \"title\": \"");
        builder.append(webPage->pageTitle());
        builder.appendLiteral("\", \"url\": \"");
        builder.append(webPage->activeURL());
        builder.appendLiteral("\", \"inspectorUrl\": \"");
        builder.appendLiteral("/inspector.html?page=");
        builder.appendNumber(it->key);
        builder.appendLiteral("\" }");
    }
    builder.appendLiteral(" ]");
    CString cstr = builder.toString().utf8();
    data.append(cstr.data(), cstr.length());
    contentType = "application/json; charset=utf-8";
}
static Vector<OwnArrayPtr<char>> createArgsArray(const String& prefix, const String& executablePath, const String& socket, const String& pluginPath)
{
    ASSERT(!executablePath.isEmpty());
    ASSERT(!socket.isEmpty());

    Vector<String> splitArgs;
    prefix.split(' ', splitArgs);

    splitArgs.append(executablePath);
    splitArgs.append(socket);
    if (!pluginPath.isEmpty())
        splitArgs.append(pluginPath);

    Vector<OwnArrayPtr<char>> args;
    args.resize(splitArgs.size() + 1); // Extra room for null.

    size_t numArgs = splitArgs.size();
    for (size_t i = 0; i < numArgs; ++i) {
        CString param = splitArgs[i].utf8();
        args[i] = adoptArrayPtr(new char[param.length() + 1]); // Room for the terminating null coming from the CString.
        strncpy(args[i].get(), param.data(), param.length() + 1); // +1 here so that strncpy copies the ending null.
    }
    // execvp() needs the pointers' array to be null-terminated.
    args[numArgs] = nullptr;

    return args;
}
xmlDocPtr XSLStyleSheet::locateStylesheetSubResource(xmlDocPtr parentDoc, const xmlChar* uri)
{
    bool matchedParent = (parentDoc == document());
    for (unsigned i = 0; i < m_children.size(); ++i) {
        XSLImportRule* import = m_children.at(i).get();
        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();
            }
            continue;
        }
        xmlDocPtr result = import->styleSheet()->locateStylesheetSubResource(parentDoc, uri);
        if (result)
            return result;
    }

    return 0;
}
Example #16
0
bool EditorClientEfl::shouldInsertText(const String& text, Range* range, EditorInsertAction action)
{
    CString protectedText = text.utf8();
    Ewk_Should_Insert_Text_Event shouldInsertTextEvent = { protectedText.data(), range, action };
    evas_object_smart_callback_call(m_view, "editorclient,text,insert", &shouldInsertTextEvent);
    return true;
}
Example #17
0
void ChromeClient::mouseDidMoveOverElement(const HitTestResult& hit, unsigned modifierFlags)
{
    // check if the element is a link...
    bool isLink = hit.isLiveLink();
    if (isLink) {
        KURL url = hit.absoluteLinkURL();
        if (!url.isEmpty() && url != m_hoveredLinkURL) {
            TextDirection dir;
            CString titleString = hit.title(dir).utf8();
            CString urlString = url.string().utf8();
            g_signal_emit_by_name(m_webView, "hovering-over-link", titleString.data(), urlString.data());
            m_hoveredLinkURL = url;
        }
    } else if (!isLink && !m_hoveredLinkURL.isEmpty()) {
        g_signal_emit_by_name(m_webView, "hovering-over-link", 0, 0);
        m_hoveredLinkURL = KURL();
    }

    if (Node* node = hit.innerNonSharedNode()) {
        Frame* frame = node->document()->frame();
        FrameView* view = frame ? frame->view() : 0;
        m_webView->priv->tooltipArea = view ? view->contentsToWindow(node->pixelSnappedBoundingBox()) : IntRect();
    } else
        m_webView->priv->tooltipArea = IntRect();
}
Example #18
0
TEST(WTF, StringASCII)
{
    CString output;

    // Null String.
    output = String().ascii();
    ASSERT_STREQ("", output.data());

    // Empty String.
    output = emptyString().ascii();
    ASSERT_STREQ("", output.data());

    // Regular String.
    output = String(ASCIILiteral("foobar")).ascii();
    ASSERT_STREQ("foobar", output.data());
}
PassRefPtr<FormData> WMLGoElement::createFormData(const CString& boundary)
{
    CString key;
    CString value;

    Vector<char> encodedData;
    TextEncoding encoding = FormDataBuilder::encodingFromAcceptCharset(m_formAttributes.acceptCharset(), document()).encodingForFormSubmission();

    Vector<WMLPostfieldElement*>::iterator it = m_postfieldElements.begin();
    Vector<WMLPostfieldElement*>::iterator end = m_postfieldElements.end();

    RefPtr<FormData> result = FormData::create();
    for (; it != end; ++it) {
        (*it)->encodeData(encoding, key, value);

        if (m_formAttributes.isMultiPartForm()) {
            Vector<char> header;
            FormDataBuilder::beginMultiPartHeader(header, boundary, key);
            FormDataBuilder::finishMultiPartHeader(header);
            result->appendData(header.data(), header.size());

            if (size_t dataSize = value.length())
                result->appendData(value.data(), dataSize);

            result->appendData("\r\n", 2);
        } else
            FormDataBuilder::addKeyValuePairAsFormData(encodedData, key, value);
    }

    if (m_formAttributes.isMultiPartForm())
        FormDataBuilder::addBoundaryToMultiPartHeader(encodedData, boundary, true);

    result->appendData(encodedData.data(), encodedData.size());
    return result;
}
Example #20
0
/**
 * webkit_web_frame_get_name:
 * @frame: a #WebKitWebFrame
 *
 * Returns the @frame's name
 *
 * Return value: the name of @frame. This method will return NULL if
 * the #WebKitWebFrame is invalid or an empty string if it is not backed
 * by a live WebCore frame.
 */
const gchar* webkit_web_frame_get_name(WebKitWebFrame* frame)
{
    g_return_val_if_fail(WEBKIT_IS_WEB_FRAME(frame), 0);
    Frame* coreFrame = core(frame);
    if (!coreFrame)
        return "";

    WebKitWebFramePrivate* priv = frame->priv;
    CString frameName = coreFrame->tree()->uniqueName().string().utf8();
    if (!g_strcmp0(frameName.data(), priv->name))
        return priv->name;

    g_free(priv->name);
    priv->name = g_strdup(frameName.data());
    return priv->name;
}
Example #21
0
Vector<String> listDirectory(const String& path, const String& filter)
{
    Vector<String> entries;
    CString cpath = path.utf8();
    CString cfilter = filter.utf8();
    char filePath[PATH_MAX];
    char* fileName;
    size_t fileNameSpace;
    DIR* dir;

    if (cpath.length() + NAME_MAX >= sizeof(filePath))
        return entries;
    // loop invariant: directory part + '/'
    memcpy(filePath, cpath.data(), cpath.length());
    fileName = filePath + cpath.length();
    if (cpath.length() > 0 && filePath[cpath.length() - 1] != '/') {
        fileName[0] = '/';
        fileName++;
    }
    fileNameSpace = sizeof(filePath) - (fileName - filePath) - 1;

    dir = opendir(cpath.data());
    if (!dir)
        return entries;

    struct dirent* de;
    while (de = readdir(dir)) {
        size_t nameLen;
        if (de->d_name[0] == '.') {
            if (de->d_name[1] == '\0')
                continue;
            if (de->d_name[1] == '.' && de->d_name[2] == '\0')
                continue;
        }
        if (fnmatch(cfilter.data(), de->d_name, 0))
            continue;

        nameLen = strlen(de->d_name);
        if (nameLen >= fileNameSpace)
            continue; // maybe assert? it should never happen anyway...

        memcpy(fileName, de->d_name, nameLen + 1);
        entries.append(filePath);
    }
    closedir(dir);
    return entries;
}
static void testGetFaviconURI(FaviconDatabaseTest* test)
{
    WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(test->m_webContext);

    CString baseURI = kServer->getURIForPath("/foo");
    GOwnPtr<char> iconURI(webkit_favicon_database_get_favicon_uri(database, baseURI.data()));
    ASSERT_CMP_CSTRING(iconURI.get(), ==, kServer->getURIForPath("/icon/favicon.ico"));
}
Example #23
0
static PassRefPtr<SharedBuffer> loadResourceSharedBuffer(CString name)
{
    GOwnPtr<gchar> content;
    gsize length;
    if (!g_file_get_contents(name.data(), &content.outPtr(), &length, 0))
        return SharedBuffer::create();

    return SharedBuffer::create(content.get(), length);
}
Example #24
0
static bool addFontDirectory(const CString& fontDirectory, FcConfig* config)
{
    const char* path = fontDirectory.data();
    if (!FcConfigAppFontAddDir(config, reinterpret_cast<const FcChar8*>(path))) {
        fprintf(stderr, "Could not add font directory %s!\n", path);
        return false;
    }
    return true;
}
Example #25
0
CString webkitDownloadDecideDestinationWithSuggestedFilename(WebKitDownload* download, const CString& suggestedFilename, bool& allowOverwrite)
{
    if (download->priv->isCancelled)
        return "";
    gboolean returnValue;
    g_signal_emit(download, signals[DECIDE_DESTINATION], 0, suggestedFilename.data(), &returnValue);
    allowOverwrite = download->priv->allowOverwrite;
    return download->priv->destinationURI;
}
Example #26
0
void Bridge::send(const CString& message)
{
    ASSERT(m_peer);
    OwnPtr<Vector<char>> data = adoptPtr(new Vector<char>(message.length()));
    if (message.length())
        memcpy(data->data(), static_cast<const char*>(message.data()), message.length());

    m_loaderProxy->postTaskToLoader(createCrossThreadTask(&Peer::sendTextAsCharVector, m_peer.get(), data.release()));
}
JSRetainPtr<JSStringRef> LayoutTestController::markerTextForListItem(JSContextRef context, JSValueRef nodeObject) const
{
    CString markerTextGChar = DumpRenderTreeSupportGtk::markerTextForListItem(mainFrame, context, nodeObject);
    if (markerTextGChar.isNull())
        return 0;

    JSRetainPtr<JSStringRef> markerText(Adopt, JSStringCreateWithUTF8CString(markerTextGChar.data()));
    return markerText;
}
JSRetainPtr<JSStringRef> LayoutTestController::counterValueForElementById(JSStringRef id)
{
    gchar* idGChar = JSStringCopyUTF8CString(id);
    CString counterValueGChar = DumpRenderTreeSupportGtk::counterValueForElementById(mainFrame, idGChar);
    g_free(idGChar);
    if (counterValueGChar.isNull())
        return 0;
    JSRetainPtr<JSStringRef> counterValue(Adopt, JSStringCreateWithUTF8CString(counterValueGChar.data()));
    return counterValue;
}
Example #29
0
static void addFontFiles(const Vector<String>& fontFiles, FcConfig* config)
{
    for (Vector<String>::const_iterator it = fontFiles.begin(); it != fontFiles.end(); ++it) {
        const CString currentFile = (*it).utf8();
        const char* path = currentFile.data();

        if (!FcConfigAppFontAddFile(config, reinterpret_cast<const FcChar8*>(path)))
            fprintf(stderr, "Could not load font at %s!\n", path);
    }
}
Example #30
0
float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
{
    if (!glyph || !platformData().size())
        return 0;

    float escapements[1];
    CString encoded = UTF8Encoding().encode((UChar *)&glyph, 1, URLEncodedEntitiesForUnencodables);
    m_platformData.font()->GetEscapements(encoded.data(), 1, escapements);
    return escapements[0] * m_platformData.font()->Size();
}