static bool isMultimediaElement(const QWebElement& element) { if (element.tagName().compare(QL1S("video"), Qt::CaseInsensitive) == 0) return true; if (element.tagName().compare(QL1S("audio"), Qt::CaseInsensitive) == 0) return true; return false; }
void ClickToFlash::findElement() { if (!loadButton_) return; QPoint objectPos = page_->view()->mapFromGlobal(loadButton_->mapToGlobal(loadButton_->pos())); QWebFrame* objectFrame = page_->frameAt(objectPos); QWebHitTestResult hitResult; QWebElement hitElement; if (objectFrame) { hitResult = objectFrame->hitTestContent(objectPos); hitElement = hitResult.element(); } if (!hitElement.isNull() && (hitElement.tagName().compare("embed", Qt::CaseInsensitive) == 0 || hitElement.tagName().compare("object", Qt::CaseInsensitive) == 0)) { element_ = hitElement; return; } // HitTestResult failed, trying to find element by src // attribute in elements at all frames on page (less accurate) QList<QWebFrame*> frames; frames.append(objectFrame); frames.append(page_->mainFrame()); while (!frames.isEmpty()) { QWebFrame* frame = frames.takeFirst(); if (!frame) { continue; } QWebElement docElement = frame->documentElement(); QWebElementCollection elements; elements.append(docElement.findAll(QLatin1String("embed"))); elements.append(docElement.findAll(QLatin1String("object"))); foreach (const QWebElement &element, elements) { if (!checkElement(element) && !checkUrlOnElement(element)) { continue; } element_ = element; return; } frames += frame->childFrames(); } }
void MainWindow::finished_loading(bool ok) { if(!ok) std::cout << "LOAD FINISH NOT OK!\n\n"; QString output; QWebElement body; progress = 100; adjust_title(); QWebFrame *frame = uimw->webView->page()->mainFrame(); QWebElement document = frame->documentElement(); QWebElement element = document.firstChild(); while(!element.isNull()) { if(element.tagName() == "BODY") { output = element.toInnerXml(); if(output == "ok\n") { QNetworkCookieJar *cj = uimw->webView->page()->networkAccessManager()->cookieJar(); QList<QNetworkCookie> cookies = cj->cookiesForUrl(testauth); for(QList<QNetworkCookie>::const_iterator i = cookies.begin() ; i != cookies.end() ; i++ ) { std::cout << "Set-Cookie: "; QByteArray ba = i->toRawForm(); std::cout.write(ba.data(), ba.count()); std::cout << "\r\n"; } exit(0); } } element = element.nextSibling(); } this->show(); }
void WebView::addSearchEngine() { QAction *action = qobject_cast<QAction*>(sender()); if (!action) return; QVariant variant = action->data(); if (!variant.canConvert<QWebElement>()) return; QWebElement element = qvariant_cast<QWebElement>(variant); QString elementName = element.attribute(QLatin1String("name")); QWebElement formElement = element; while (formElement.tagName().toLower() != QLatin1String("form")) formElement = formElement.parent(); if (formElement.isNull() || formElement.attribute(QLatin1String("action")).isEmpty()) return; QString method = formElement.attribute(QLatin1String("method"), QLatin1String("get")).toLower(); if (method != QLatin1String("get")) { QMessageBox::warning(this, tr("Method not supported"), tr("%1 method is not supported.").arg(method.toUpper())); return; } QUrl searchUrl(page()->mainFrame()->baseUrl().resolved(QUrl(formElement.attribute(QLatin1String("action"))))); QMap<QString, QString> searchEngines; QWebElementCollection inputFields = formElement.findAll(QLatin1String("input")); foreach (QWebElement inputField, inputFields) { QString type = inputField.attribute(QLatin1String("type"), QLatin1String("text")); QString name = inputField.attribute(QLatin1String("name")); QString value = inputField.evaluateJavaScript(QLatin1String("this.value")).toString(); if (type == QLatin1String("submit")) { searchEngines.insert(value, name); } else if (type == QLatin1String("text")) { if (inputField == element) value = QLatin1String("{searchTerms}"); searchUrl.addQueryItem(name, value); } else if (type == QLatin1String("checkbox") || type == QLatin1String("radio")) { if (inputField.evaluateJavaScript(QLatin1String("this.checked")).toBool()) { searchUrl.addQueryItem(name, value); } } else if (type == QLatin1String("hidden")) { searchUrl.addQueryItem(name, value); } }
//! [traverse document] void Window::examineChildElements(const QWebElement &parentElement, QTreeWidgetItem *parentItem) { QWebElement element = parentElement.firstChild(); while (!element.isNull()) { QTreeWidgetItem *item = new QTreeWidgetItem(); item->setText(0, element.tagName()); parentItem->addChild(item); examineChildElements(element, item); element = element.nextSibling(); } }
QTreeWidgetItem* XPathInspector::createTree(QWebElement root) { QString js = "var arr = []; "; js += "for (var i=0; i<this.childNodes.length; i++) "; js += " if (this.childNodes[i].nodeType == 3 && this.childNodes[i].nodeValue.replace(/^\\s+|\\s+$/g,'') != '') "; js += " arr.push(this.childNodes[i].nodeValue); "; js += " else if (this.childNodes[i].nodeType == 1)"; js += " arr.push(this.childNodes[i].tagName); "; js += "arr; "; QVariant v = root.evaluateJavaScript(js); QStringList nodes = v.toStringList(); QWebElement child = root.firstChild(); QList<QTreeWidgetItem*> list; int i = 0; while (!(i>=nodes.count() && child.isNull())) { while (i<nodes.count() && nodes.at(i) != child.tagName()) { QTreeWidgetItem *item2 = new QTreeWidgetItem(); item2->setText(0, nodes.at(i)); list.append(item2); i++; } if (!child.isNull()) { list.append(createTree(child)); child = child.nextSibling(); i++; } } QString text = "<"+root.tagName().toLower(); QStringList attrs = root.attributeNames(); for (int i=0; i<attrs.count(); i++) text += " "+attrs.at(i)+"=\""+root.attribute(attrs.at(i))+"\""; text += ">"; QTreeWidgetItem *item = new QTreeWidgetItem(); item->setText(0, text); QVariant v2(QVariant::UserType); v2.setValue<QWebElement>(root); item->setData(0, Qt::UserRole, v2); item->addChildren(list); return item; }
FB2_END_KEYHASH FbHeadItem::FbHeadItem(QWebElement &element, FbHeadItem *parent) : QObject(parent) , m_element(element) , m_parent(parent) { m_name = element.tagName().toLower(); if (m_name.left(3) == "fb:") { m_name = m_name.mid(3); if (m_name == "annotation") return; if (m_name == "history") return; } else if (m_name == "img") { m_name = "image"; } addChildren(element); }
static bool isEditableElement(QWebPage* page) { const QWebFrame* frame = (page ? page->currentFrame() : 0); QWebElement element = (frame ? frame->findFirstElement(QL1S(":focus")) : QWebElement()); if (!element.isNull()) { const QString tagName(element.tagName()); if (tagName.compare(QL1S("textarea"), Qt::CaseInsensitive) == 0) { return true; } const QString type(element.attribute(QL1S("type")).toLower()); if (tagName.compare(QL1S("input"), Qt::CaseInsensitive) == 0 && (type.isEmpty() || type == QL1S("text") || type == QL1S("password"))) { return true; } if (element.evaluateJavaScript("this.isContentEditable").toBool()) { return true; } } return false; }
extern QVariantMap toMap(QWebElement el, QStringList css_attrs) { QVariantMap map; map["isNull"] = false; map["classes"] = QVariant(el.classes()); map["tagName"] = QVariant(el.tagName()); QRect rect = el.geometry(); QVariantMap geo; geo["width"] = rect.width(); geo["height"] = rect.height(); geo["x"] = rect.x(); geo["y"] = rect.y(); map["geometry"] = QVariant(geo); QVariantMap attrs; QStringList attributes = el.attributeNames(); foreach(QString name,attributes) { attrs[name] = el.attribute(name); }
void CadastreWrapper::networkFinished(QNetworkReply *reply) { if (m_pendingTiles.contains(reply)) { QFile target(m_pendingTiles[reply]); QByteArray ba = reply->readAll(); // white -> transparent QImage img; img.loadFromData(ba); QImage img2 = img.convertToFormat(QImage::Format_ARGB32); Q_ASSERT(img2.hasAlphaChannel()); int w=0; for (int y=0; y<img2.height(); ++y) { for (int x=0; x<img2.width(); ++x) { QColor col = QColor(img2.pixel(x, y)); if (col == QColor(255, 255, 255)) { col.setAlpha(0); img2.setPixel(x, y, col.rgba()); ++w; } } } //Full transparent if (w == img2.height()*img2.width()) { img2 = QImage(1, 1, QImage::Format_ARGB32); img2.setPixel(0, 0, QColor(0, 0, 0, 0).rgba()); } target.open(QIODevice::WriteOnly); // target.write(reply->readAll()); img2.save(&target, "PNG"); target.close(); m_pendingTiles.remove(reply); if (m_progress) { m_progress->setValue(m_progress->value()+1); if (m_progress->value() > 10) { double ms = m_startTime.secsTo(QDateTime::currentDateTime()); double us = ms/m_progress->value(); int tot = us*(m_progress->maximum() - m_progress->value()); if (tot<3600) m_progress->setLabelText(tr("Downloaded: %1/%2\nRemaining time: %3:%4").arg(m_progress->value()).arg(m_progress->maximum()).arg(int(tot/60)).arg(int(tot%60), 2, 10, QChar('0'))); else m_progress->setLabelText(tr("Downloaded: %1/%2\nRemaining time: %3:%4:%5").arg(m_progress->value()).arg(m_progress->maximum()).arg(int(tot/3600)).arg(int((tot%3600)/60), 2, 10, QChar('0')).arg(int(tot%60), 2, 10, QChar('0'))); } else m_progress->setLabelText(tr("Downloaded: %1/%2").arg(m_progress->value()).arg(m_progress->maximum())); } } else if (reply->url() == QUrl("http://www.cadastre.gouv.fr/scpc/accueil.do")) { qDebug() << "Ok, I've got a cookie... I LOVE COOKIES."; reply->readAll(); m_gotCookie = true; } else if (reply->url() == QUrl("http://www.cadastre.gouv.fr/scpc/rechercherPlan.do")) { QString pageData = reply->readAll(); qDebug() << pageData; QWebPage parsedPage(this); QWebFrame *frame = parsedPage.mainFrame(); frame->setHtml(pageData); QWebElement codeCommune = frame->findFirstElement("#codeCommune"); QMap<QString, QString> results; if (!codeCommune.isNull()) { // If there is a codeCommune object in the DOM, it means that the search was not successfull. if (codeCommune.tagName().toLower() != "select") { qDebug() << "Invalid page ???"; return; } QWebElementCollection options = codeCommune.findAll("option"); foreach (QWebElement option, options) { if (!option.attribute("value").isEmpty()) results[option.attribute("value")] = option.toPlainText(); } } else {
void WebView::contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = new QMenu(this); QWebHitTestResult r = page()->mainFrame()->hitTestContent(event->pos()); if (!r.linkUrl().isEmpty()) { QAction *newWindowAction = menu->addAction(tr("Open in New &Window"), this, SLOT(openActionUrlInNewWindow())); newWindowAction->setData(r.linkUrl()); QAction *newTabAction = menu->addAction(tr("Open in New &Tab"), this, SLOT(openActionUrlInNewTab())); newTabAction->setData(r.linkUrl()); menu->addSeparator(); menu->addAction(tr("Save Lin&k"), this, SLOT(downloadLinkToDisk())); menu->addAction(tr("&Bookmark This Link"), this, SLOT(bookmarkLink()))->setData(r.linkUrl()); menu->addSeparator(); if (!page()->selectedText().isEmpty()) menu->addAction(pageAction(QWebPage::Copy)); menu->addAction(tr("&Copy Link Location"), this, SLOT(copyLinkToClipboard())); } if (!r.imageUrl().isEmpty()) { if (!menu->isEmpty()) menu->addSeparator(); QAction *newWindowAction = menu->addAction(tr("Open Image in New &Window"), this, SLOT(openActionUrlInNewWindow())); newWindowAction->setData(r.imageUrl()); QAction *newTabAction = menu->addAction(tr("Open Image in New &Tab"), this, SLOT(openActionUrlInNewTab())); newTabAction->setData(r.imageUrl()); menu->addSeparator(); menu->addAction(tr("&Save Image"), this, SLOT(downloadImageToDisk())); menu->addAction(tr("&Copy Image"), this, SLOT(copyImageToClipboard())); menu->addAction(tr("C&opy Image Location"), this, SLOT(copyImageLocationToClipboard()))->setData(r.imageUrl().toString()); menu->addSeparator(); menu->addAction(tr("Block Image"), this, SLOT(blockImage()))->setData(r.imageUrl().toString()); } if (!page()->selectedText().isEmpty()) { if (menu->isEmpty()) { menu->addAction(pageAction(QWebPage::Copy)); } else { menu->addSeparator(); } QMenu *searchMenu = menu->addMenu(tr("Search with...")); QList<QString> list = ToolbarSearch::openSearchManager()->allEnginesNames(); for (int i = 0; i < list.count(); ++i) { QString name = list.at(i); OpenSearchEngine *engine = ToolbarSearch::openSearchManager()->engine(name); QAction *action = new OpenSearchEngineAction(engine, searchMenu); searchMenu->addAction(action); action->setData(name); } connect(searchMenu, SIGNAL(triggered(QAction *)), this, SLOT(searchRequested(QAction *))); } QWebElement element = r.element(); if (!element.isNull() && element.tagName().toLower() == QLatin1String("input") && element.attribute(QLatin1String("type"), QLatin1String("text")) == QLatin1String("text")) { if (menu->isEmpty()) { menu->addAction(pageAction(QWebPage::Copy)); } else { menu->addSeparator(); } QVariant variant; variant.setValue(element); menu->addAction(tr("Add to the toolbar search"), this, SLOT(addSearchEngine()))->setData(variant); } if (menu->isEmpty()) { delete menu; menu = page()->createStandardContextMenu(); } else { if (page()->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled)) menu->addAction(pageAction(QWebPage::InspectElement)); } if (!menu->isEmpty()) { if (BrowserMainWindow::parentWindow(tabWidget())->menuBar()->isHidden()) { menu->addSeparator(); menu->addAction(BrowserMainWindow::parentWindow(tabWidget())->showMenuBarAction()); } menu->exec(mapToGlobal(event->pos())); delete menu; return; } delete menu; QWebView::contextMenuEvent(event); }
void SearchEnginesManager::addEngineFromForm(const QWebElement &element, WebView* view) { QWebElement formElement = element.parent(); while (!formElement.isNull()) { if (formElement.tagName().toLower() == QLatin1String("form")) { break; } formElement = formElement.parent(); } if (formElement.isNull()) { return; } const QString method = formElement.hasAttribute("method") ? formElement.attribute("method").toUpper() : "GET"; bool isPost = method == QLatin1String("POST"); QUrl actionUrl = QUrl::fromEncoded(formElement.attribute("action").toUtf8()); if (actionUrl.isRelative()) { actionUrl = view->url().resolved(actionUrl); } QUrl parameterUrl = actionUrl; if (isPost) { parameterUrl = QUrl("http://foo.bar"); } #if QT_VERSION >= 0x050000 QUrlQuery query(parameterUrl); query.addQueryItem(element.attribute("name"), "%s"); QWebElementCollection allInputs = formElement.findAll("input"); foreach (QWebElement e, allInputs) { if (element == e || !e.hasAttribute("name")) { continue; } query.addQueryItem(e.attribute("name"), e.evaluateJavaScript("this.value").toString()); } parameterUrl.setQuery(query); #else QList<QPair<QByteArray, QByteArray> > queryItems; QPair<QByteArray, QByteArray> item; item.first = element.attribute("name").toUtf8(); item.second = "%s"; queryItems.append(item); QWebElementCollection allInputs = formElement.findAll("input"); foreach (QWebElement e, allInputs) { if (element == e || !e.hasAttribute("name")) { continue; } QPair<QByteArray, QByteArray> item; item.first = QUrl::toPercentEncoding(e.attribute("name").toUtf8()); item.second = QUrl::toPercentEncoding(e.evaluateJavaScript("this.value").toByteArray()); queryItems.append(item); } parameterUrl.setEncodedQueryItems(parameterUrl.encodedQueryItems() + queryItems); #endif if (!isPost) { actionUrl = parameterUrl; } SearchEngine engine; engine.name = view->title(); engine.icon = view->icon(); engine.url = actionUrl.toEncoded(); if (isPost) { QByteArray data = parameterUrl.toEncoded(QUrl::RemoveScheme); engine.postData = data.contains('?') ? data.mid(data.lastIndexOf('?') + 1) : QByteArray(); } EditSearchEngine dialog(SearchEnginesDialog::tr("Add Search Engine"), view); dialog.setName(engine.name); dialog.setIcon(engine.icon); dialog.setUrl(engine.url); dialog.setPostData(engine.postData); if (dialog.exec() != QDialog::Accepted) { return; } engine.name = dialog.name(); engine.icon = dialog.icon(); engine.url = dialog.url(); engine.shortcut = dialog.shortcut(); engine.postData = dialog.postData().toUtf8(); if (engine.name.isEmpty() || engine.url.isEmpty()) { return; } addEngine(engine); }
void WBWebTrapWebView::highliteElementAtPos ( const QPoint& pos) { mCurrentContentType = Unknown; if(page() && page()->currentFrame()) { QWebHitTestResult htr = page()->currentFrame()->hitTestContent (pos); QRect pageHtr = htr.boundingRect().translated(htr.frame()->pos()); QRect updateRect = mWebViewElementRect.united(pageHtr); updateRect = updateRect.adjusted(-8, -8, 8, 8); mDomElementRect = htr.boundingRect(); if (!htr.pixmap().isNull()) { mCurrentContentType = Image; qDebug() << "found pixmap at " << htr.boundingRect(); } else { QWebElement element = htr.element(); QString tagName = element.tagName().toLower(); if (tagName == "object" || tagName == "embed") { mCurrentContentType = ObjectOrEmbed; } else if ((tagName == "input") || (tagName == "textarea")) { QString ec = potentialEmbedCodeAtPos(pos); if (ec.length() > 0) { qDebug() << "found input data \n\n" << ec; mCurrentContentType = Input; } } else { QString tagName = htr.element().tagName(); QString id = htr.element().attribute("id", ""); QWebElement el = htr.element(); QString idSelector = tagName + "#" + id; bool idSuccess = (el == el.document().findFirst(idSelector)); if (idSuccess) { mElementQuery = idSelector; mCurrentContentType = ElementByQuery; } else { //bool isValid = true; QWebElement elParent = el.parent(); QWebElement currentEl = el; QString path = tagName; QStringList pathElements; do { QWebElement someSibling = elParent.firstChild(); int index = 0; bool foundIndex = false; do { if (someSibling.tagName() == currentEl.tagName()) { if (someSibling == currentEl) { foundIndex = true; } else index++; } someSibling = someSibling.nextSibling(); } while(!someSibling.isNull() && !foundIndex); QString part; if (index > 0) part = QString("%1:nth-child(%2)").arg(currentEl.tagName()).arg(index); else part = currentEl.tagName(); pathElements.insert(0, part); currentEl = elParent; elParent = elParent.parent(); } while(!elParent.isNull()); //QString idSelector = tagName + "#" + id; QString treeSelector = pathElements.join(" > "); mElementQuery = treeSelector; mCurrentContentType = ElementByQuery; //bool treeSuccess = (el == el.document().findFirst(treeSelector)); //qDebug() << "----------------------------"; //qDebug() << idSuccess << idSelector; //qDebug() << treeSuccess << treeSelector; } } } update(updateRect); } }
void QtWebKitWebWidget::showContextMenu(const QPoint &position) { if (position.isNull() && m_webView->selectedText().isEmpty()) { return; } const QPoint hitPosition = (position.isNull() ? m_webView->mapFromGlobal(QCursor::pos()) : position); MenuFlags flags = NoMenu; m_hitResult = m_webView->page()->frameAt(hitPosition)->hitTestContent(hitPosition); if (m_hitResult.element().tagName().toLower() == QLatin1String("textarea") || m_hitResult.element().tagName().toLower() == QLatin1String("select") || (m_hitResult.element().tagName().toLower() == QLatin1String("input") && (m_hitResult.element().attribute(QLatin1String("type")).isEmpty() || m_hitResult.element().attribute(QLatin1String("type")).toLower() == QLatin1String("text")))) { QWebElement parentElement = m_hitResult.element().parent(); while (!parentElement.isNull() && parentElement.tagName().toLower() != QLatin1String("form")) { parentElement = parentElement.parent(); } if (!parentElement.isNull() && parentElement.hasAttribute(QLatin1String("action")) && !parentElement.findFirst(QLatin1String("input[name], select[name], textarea[name]")).isNull()) { flags |= FormMenu; } } if (m_hitResult.pixmap().isNull() && m_hitResult.isContentSelected() && !m_webView->selectedText().isEmpty()) { updateSearchActions(m_searchEngine); flags |= SelectionMenu; } if (m_hitResult.linkUrl().isValid()) { flags |= LinkMenu; } if (!m_hitResult.pixmap().isNull()) { flags |= ImageMenu; const bool isImageOpened = getUrl().matches(m_hitResult.imageUrl(), (QUrl::NormalizePathSegments | QUrl::RemoveFragment | QUrl::StripTrailingSlash)); getAction(OpenImageInNewTabAction)->setEnabled(!isImageOpened); getAction(InspectElementAction)->setEnabled(!isImageOpened); } if (m_hitResult.mediaUrl().isValid()) { flags |= MediaMenu; const bool isVideo = (m_hitResult.element().tagName().toLower() == QLatin1String("video")); const bool isPaused = m_hitResult.element().evaluateJavaScript(QLatin1String("this.paused")).toBool(); const bool isMuted = m_hitResult.element().evaluateJavaScript(QLatin1String("this.muted")).toBool(); getAction(SaveMediaToDiskAction)->setText(isVideo ? tr("Save Video...") : tr("Save Audio...")); getAction(CopyMediaUrlToClipboardAction)->setText(isVideo ? tr("Copy Video Link to Clipboard") : tr("Copy Audio Link to Clipboard")); getAction(ToggleMediaControlsAction)->setText(tr("Show Controls")); getAction(ToggleMediaLoopAction)->setText(tr("Looping")); getAction(ToggleMediaPlayPauseAction)->setIcon(Utils::getIcon(isPaused ? QLatin1String("media-playback-start") : QLatin1String("media-playback-pause"))); getAction(ToggleMediaPlayPauseAction)->setText(isPaused ? tr("Play") : tr("Pause")); getAction(ToggleMediaMuteAction)->setIcon(Utils::getIcon(isMuted ? QLatin1String("audio-volume-medium") : QLatin1String("audio-volume-muted"))); getAction(ToggleMediaMuteAction)->setText(isMuted ? tr("Unmute") : tr("Mute")); } if (m_hitResult.isContentEditable()) { flags |= EditMenu; getAction(ClearAllAction)->setEnabled(getAction(SelectAllAction)->isEnabled()); } if (flags == NoMenu || flags == FormMenu) { flags |= StandardMenu; if (m_hitResult.frame() != m_webView->page()->mainFrame()) { flags |= FrameMenu; } } WebWidget::showContextMenu(hitPosition, flags); }
void QtWebKitWebWidget::triggerAction(WindowAction action, bool checked) { const QWebPage::WebAction webAction = mapAction(action); if (webAction != QWebPage::NoWebAction) { m_webView->triggerPageAction(webAction, checked); return; } switch (action) { case RewindBackAction: m_webView->page()->history()->goToItem(m_webView->page()->history()->itemAt(0)); break; case RewindForwardAction: m_webView->page()->history()->goToItem(m_webView->page()->history()->itemAt(m_webView->page()->history()->count() - 1)); break; case CopyAddressAction: QApplication::clipboard()->setText(getUrl().toString()); break; case ZoomInAction: setZoom(qMin((getZoom() + 10), 10000)); break; case ZoomOutAction: setZoom(qMax((getZoom() - 10), 10)); break; case ZoomOriginalAction: setZoom(100); break; case ReloadOrStopAction: if (isLoading()) { triggerAction(StopAction); } else { triggerAction(ReloadAction); } break; case OpenLinkInNewTabAction: if (m_hitResult.linkUrl().isValid()) { emit requestedOpenUrl(m_hitResult.linkUrl(), false, false); } break; case OpenLinkInNewTabBackgroundAction: if (m_hitResult.linkUrl().isValid()) { emit requestedOpenUrl(m_hitResult.linkUrl(), true, false); } break; case OpenLinkInNewWindowAction: if (m_hitResult.linkUrl().isValid()) { emit requestedOpenUrl(m_hitResult.linkUrl(), false, true); } break; case OpenLinkInNewWindowBackgroundAction: if (m_hitResult.linkUrl().isValid()) { emit requestedOpenUrl(m_hitResult.linkUrl(), true, true); } break; case BookmarkLinkAction: if (m_hitResult.linkUrl().isValid()) { emit requestedAddBookmark(m_hitResult.linkUrl(), m_hitResult.element().attribute(QLatin1String("title"))); } break; case OpenSelectionAsLinkAction: emit requestedOpenUrl(m_webView->selectedText(), false, false); break; case ImagePropertiesAction: { ImagePropertiesDialog dialog(m_hitResult.imageUrl(), m_hitResult.element().attribute(QLatin1String("alt")), m_hitResult.element().attribute(QLatin1String("longdesc")), m_hitResult.pixmap(), (m_networkAccessManager->cache() ? m_networkAccessManager->cache()->data(m_hitResult.imageUrl()) : NULL), this); QEventLoop eventLoop; m_parent->showDialog(&dialog); connect(&dialog, SIGNAL(finished(int)), &eventLoop, SLOT(quit())); connect(this, SIGNAL(destroyed()), &eventLoop, SLOT(quit())); eventLoop.exec(); m_parent->hideDialog(&dialog); } break; case InspectPageAction: if (!m_inspector) { m_inspector = new QWebInspector(this); m_inspector->setPage(m_webView->page()); m_inspector->setContextMenuPolicy(Qt::NoContextMenu); m_inspector->setMinimumHeight(200); m_splitter->addWidget(m_inspector); } m_inspector->setVisible(checked); getAction(InspectPageAction)->setChecked(checked); emit actionsChanged(); emit progressBarGeometryChanged(); break; case SaveLinkToDownloadsAction: TransfersManager::startTransfer(m_hitResult.linkUrl().toString(), QString(), isPrivate(), true); break; case OpenFrameInThisTabAction: if (m_hitResult.frame()) { setUrl(m_hitResult.frame()->url().isValid() ? m_hitResult.frame()->url() : m_hitResult.frame()->requestedUrl()); } break; case OpenFrameInNewTabBackgroundAction: if (m_hitResult.frame()) { emit requestedOpenUrl((m_hitResult.frame()->url().isValid() ? m_hitResult.frame()->url() : m_hitResult.frame()->requestedUrl()), true, false); } break; case CopyFrameLinkToClipboardAction: if (m_hitResult.frame()) { QGuiApplication::clipboard()->setText((m_hitResult.frame()->url().isValid() ? m_hitResult.frame()->url() : m_hitResult.frame()->requestedUrl()).toString()); } break; case ReloadFrameAction: if (m_hitResult.frame()) { const QUrl url = (m_hitResult.frame()->url().isValid() ? m_hitResult.frame()->url() : m_hitResult.frame()->requestedUrl()); m_hitResult.frame()->setUrl(QUrl()); m_hitResult.frame()->setUrl(url); } break; case SearchAction: search(getAction(SearchAction)); break; case CreateSearchAction: { QWebElement parentElement = m_hitResult.element().parent(); while (!parentElement.isNull() && parentElement.tagName().toLower() != "form") { parentElement = parentElement.parent(); } const QWebElementCollection inputs = parentElement.findAll(QLatin1String("input:not([disabled])[name], select:not([disabled])[name], textarea:not([disabled])[name]")); if (!parentElement.isNull() && parentElement.hasAttribute(QLatin1String("action")) && inputs.count() > 0) { QUrlQuery parameters; for (int i = 0; i < inputs.count(); ++i) { QString value; if (inputs.at(i).tagName().toLower() == QLatin1String("textarea")) { value = inputs.at(i).toPlainText(); } else if (inputs.at(i).tagName().toLower() == QLatin1String("select")) { const QWebElementCollection options = inputs.at(i).findAll(QLatin1String("option")); for (int j = 0; j < options.count(); ++j) { if (options.at(j).hasAttribute(QLatin1String("selected"))) { value = options.at(j).attribute(QLatin1String("value"), options.at(j).toPlainText()); break; } } } else { if ((inputs.at(i).attribute(QLatin1String("type")) == QLatin1String("checkbox") || inputs.at(i).attribute(QLatin1String("type")) == QLatin1String("radio")) && !inputs.at(i).hasAttribute(QLatin1String("checked"))) { continue; } value = inputs.at(i).attribute(QLatin1String("value")); } parameters.addQueryItem(inputs.at(i).attribute(QLatin1String("name")), ((inputs.at(i) == m_hitResult.element()) ? QLatin1String("{searchTerms}") : value)); } const QStringList identifiers = SearchesManager::getSearchEngines(); QStringList shortcuts; QList<SearchInformation*> engines; for (int i = 0; i < identifiers.count(); ++i) { SearchInformation *engine = SearchesManager::getSearchEngine(identifiers.at(i)); if (!engine) { continue; } engines.append(engine); const QString shortcut = engine->shortcut; if (!shortcut.isEmpty()) { shortcuts.append(shortcut); } } QString identifier = getUrl().host().toLower().remove(QRegularExpression(QLatin1String("[^a-z0-9]"))); while (identifier.isEmpty() || identifiers.contains(identifier)) { identifier = QInputDialog::getText(this, tr("Select Identifier"), tr("Input Unique Search Engine Identifier:")); if (identifier.isEmpty()) { return; } } const QIcon icon = m_webView->icon(); const QUrl url(parentElement.attribute(QLatin1String("action"))); QVariantHash engineData; engineData[QLatin1String("identifier")] = identifier; engineData[QLatin1String("isDefault")] = false; engineData[QLatin1String("encoding")] = QLatin1String("UTF-8"); engineData[QLatin1String("selfUrl")] = QString(); engineData[QLatin1String("resultsUrl")] = (url.isEmpty() ? getUrl() : (url.isRelative() ? getUrl().resolved(url) : url)).toString(); engineData[QLatin1String("resultsEnctype")] = parentElement.attribute(QLatin1String("enctype")); engineData[QLatin1String("resultsMethod")] = ((parentElement.attribute(QLatin1String("method"), QLatin1String("get")).toLower() == QLatin1String("post")) ? QLatin1String("post") : QLatin1String("get")); engineData[QLatin1String("resultsParameters")] = parameters.toString(QUrl::FullyDecoded); engineData[QLatin1String("suggestionsUrl")] = QString(); engineData[QLatin1String("suggestionsEnctype")] = QString(); engineData[QLatin1String("suggestionsMethod")] = QLatin1String("get"); engineData[QLatin1String("suggestionsParameters")] = QString(); engineData[QLatin1String("shortcut")] = QString(); engineData[QLatin1String("title")] = getTitle(); engineData[QLatin1String("description")] = QString(); engineData[QLatin1String("icon")] = (icon.isNull() ? Utils::getIcon(QLatin1String("edit-find")) : icon); SearchPropertiesDialog dialog(engineData, shortcuts, this); if (dialog.exec() == QDialog::Rejected) { return; } engineData = dialog.getEngineData(); if (shortcuts.contains(engineData[QLatin1String("shortcut")].toString())) { engineData[QLatin1String("shortcut")] = QString(); } SearchInformation *engine = new SearchInformation(); engine->identifier = engineData[QLatin1String("identifier")].toString(); engine->title = engineData[QLatin1String("title")].toString(); engine->description = engineData[QLatin1String("description")].toString(); engine->shortcut = engineData[QLatin1String("shortcut")].toString(); engine->encoding = engineData[QLatin1String("encoding")].toString(); engine->selfUrl = engineData[QLatin1String("selfUrl")].toString(); engine->resultsUrl.url = engineData[QLatin1String("resultsUrl")].toString(); engine->resultsUrl.enctype = engineData[QLatin1String("resultsEnctype")].toString(); engine->resultsUrl.method = engineData[QLatin1String("resultsMethod")].toString(); engine->resultsUrl.parameters = QUrlQuery(engineData[QLatin1String("resultsParameters")].toString()); engine->icon = engineData[QLatin1String("icon")].value<QIcon>(); engines.append(engine); if (SearchesManager::setSearchEngines(engines) && engineData[QLatin1String("isDefault")].toBool()) { SettingsManager::setValue(QLatin1String("Browser/DefaultSearchEngine"), engineData[QLatin1String("identifier")].toString()); } } } break; case ClearAllAction: triggerAction(SelectAllAction); triggerAction(DeleteAction); break; default: break; } }
/* Take the ENML note and transform it into HTML that WebKit will not complain about */ QByteArray EnmlFormatter::rebuildNoteEnml() { resources.clear(); QByteArray b; qint32 index; content.replace("</input>",""); // Strip off HTML header index = content.indexOf("<body"); index = content.indexOf(">", index)+1; content.remove(0,index); index = content.indexOf("</body"); content.truncate(index); b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); b.append("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>\n"); b.append("<html><head><title></title></head>"); b.append("<body style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\" >"); b.append(content); b.append("</body></html>"); content.clear(); content = b; // Run it through "tidy". It is a program which will fix any invalid HTML // and give us the results back through stdout. In a perfect world this // wouldn't be needed, but WebKit doesn't always give back good HTML. QProcess tidyProcess; tidyProcess.start("tidy -raw -asxhtml -q -m -u -utf8 ", QIODevice::ReadWrite|QIODevice::Unbuffered); QLOG_DEBUG() << "Starting tidy " << tidyProcess.waitForStarted(); tidyProcess.waitForStarted(); tidyProcess.write(content); tidyProcess.closeWriteChannel(); tidyProcess.waitForFinished(); QLOG_DEBUG() << "Stopping tidy " << tidyProcess.waitForFinished() << " Return Code: " << tidyProcess.state(); QLOG_DEBUG() << "Tidy Errors:" << tidyProcess.readAllStandardError(); content.clear(); content.append(tidyProcess.readAllStandardOutput()); if (content == "") { formattingError = true; return ""; } // Tidy puts this in place, but we don't really need it. content.replace("<form>", ""); content.replace("</form>", ""); index = content.indexOf("<body"); content.remove(0,index); content.prepend("<style>img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>"); content.prepend("<head><meta http-equiv=\"content-type\" content=\"text-html; charset=utf-8\"></head>"); content.prepend("<html>"); content.append("</html>"); content = fixEncryptionTags(content); QWebPage page; QEventLoop loop; page.mainFrame()->setContent(content); QObject::connect(&page, SIGNAL(loadFinished(bool)), &loop, SLOT(quit())); QWebElement element = page.mainFrame()->documentElement(); QStringList tags = findAllTags(element); for (int i=0; i<tags.size(); i++) { QString tag = tags[i]; QWebElementCollection anchors = page.mainFrame()->findAllElements(tag); foreach (QWebElement element, anchors) { if (element.tagName().toLower() == "input") { processTodo(element); } else if (element.tagName().toLower() == "a") { fixLinkNode(element); } else if (element.tagName().toLower() == "object") { fixObjectNode(element); } else if (element.tagName().toLower() == "img") { fixImgNode(element); } else if (!isElementValid(element.tagName())) element.removeFromDocument(); } } content.clear(); content.append(element.toOuterXml()); // Strip off HTML header index = content.indexOf("<body"); index = content.indexOf(">", index)+1; content.remove(0,index); index = content.indexOf("</body"); content.truncate(index); b.clear(); b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); b.append("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>"); b.append("<en-note style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\" >"); b.append(content); b.append("</en-note>"); content.clear(); content = b; postXmlFix(); return content; }
bool WebkitPixelStreamer::isWebGLElement(const QWebElement& element) const { return element.tagName() == "CANVAS"; }
void HtmlBookmarksImporter::processElement(const QWebElement &element) { if (element.tagName().toLower() == QLatin1String("h3")) { BookmarksItem *bookmark = BookmarksManager::addBookmark(BookmarksModel::FolderBookmark, QUrl(), element.toPlainText(), getCurrentFolder()); const QString keyword = element.attribute(QLatin1String("SHORTCUTURL")); if (!BookmarksManager::hasKeyword(keyword)) { bookmark->setData(keyword, BookmarksModel::KeywordRole); } if (!element.attribute(QLatin1String("ADD_DATE")).isEmpty()) { const QDateTime time = QDateTime::fromTime_t(element.attribute(QLatin1String("ADD_DATE")).toUInt()); bookmark->setData(time, BookmarksModel::TimeAddedRole); bookmark->setData(time, BookmarksModel::TimeModifiedRole); } setCurrentFolder(bookmark); } else if (element.tagName().toLower() == QLatin1String("a")) { const QUrl url(element.attribute(QLatin1String("href"))); if (!allowDuplicates() && BookmarksManager::hasBookmark(url)) { return; } BookmarksItem *bookmark = BookmarksManager::addBookmark(BookmarksModel::UrlBookmark, url, element.toPlainText(), getCurrentFolder()); const QString keyword = element.attribute(QLatin1String("SHORTCUTURL")); if (!BookmarksManager::hasKeyword(keyword)) { bookmark->setData(keyword, BookmarksModel::KeywordRole); } if (element.parent().nextSibling().tagName().toLower() == QLatin1String("dd")) { bookmark->setData(element.parent().nextSibling().toPlainText(), BookmarksModel::DescriptionRole); } if (!element.attribute(QLatin1String("ADD_DATE")).isEmpty()) { bookmark->setData(QDateTime::fromTime_t(element.attribute(QLatin1String("ADD_DATE")).toUInt()), BookmarksModel::TimeAddedRole); } if (!element.attribute(QLatin1String("LAST_MODIFIED")).isEmpty()) { bookmark->setData(QDateTime::fromTime_t(element.attribute(QLatin1String("LAST_MODIFIED")).toUInt()), BookmarksModel::TimeModifiedRole); } if (!element.attribute(QLatin1String("LAST_VISITED")).isEmpty()) { bookmark->setData(QDateTime::fromTime_t(element.attribute(QLatin1String("LAST_VISITED")).toUInt()), BookmarksModel::TimeVisitedRole); } } else if (element.tagName().toLower() == QLatin1String("hr")) { BookmarksManager::addBookmark(BookmarksModel::SeparatorBookmark, QUrl(), QString(), getCurrentFolder()); } const QWebElementCollection descendants = element.findAll(QLatin1String("*")); for (int i = 0; i < descendants.count(); ++i) { if (descendants.at(i).parent() == element) { processElement(descendants.at(i)); } } if (element.tagName().toLower() == QLatin1String("dl")) { goToParent(); } }
void ClickToFlash::findElement() { if (!m_toolButton) { return; } QWidget* parent = parentWidget(); QWebView* view = 0; while (parent) { if (QWebView* aView = qobject_cast<QWebView*>(parent)) { view = aView; break; } parent = parent->parentWidget(); } if (!view) { return; } QPoint objectPos = view->mapFromGlobal(m_toolButton->mapToGlobal(m_toolButton->pos())); QWebFrame* objectFrame = view->page()->frameAt(objectPos); QWebHitTestResult hitResult; QWebElement hitElement; if (objectFrame) { hitResult = objectFrame->hitTestContent(objectPos); hitElement = hitResult.element(); } if (!hitElement.isNull() && (hitElement.tagName().compare("embed", Qt::CaseInsensitive) == 0 || hitElement.tagName().compare("object", Qt::CaseInsensitive) == 0)) { m_element = hitElement; return; } // HitTestResult failed, trying to find element by src // attribute in elements at all frames on page (less accurate) QList<QWebFrame*> frames; frames.append(objectFrame); m_mainFrame = view->page()->mainFrame(); frames.append(m_mainFrame); while (!frames.isEmpty()) { QWebFrame* frame = frames.takeFirst(); if (!frame) { continue; } QWebElement docElement = frame->documentElement(); QWebElementCollection elements; elements.append(docElement.findAll(QLatin1String("embed"))); elements.append(docElement.findAll(QLatin1String("object"))); foreach(const QWebElement & element, elements) { if (!checkElement(element) && !checkUrlOnElement(element)) { continue; } m_element = element; return; } frames += frame->childFrames(); } }