Пример #1
0
void WebTab::showRSSInfo(const QPoint &pos)
{
    QWebElementCollection col = page()->mainFrame()->findAllElements("link[type=\"application/rss+xml\"]");
    col.append(page()->mainFrame()->findAllElements("link[type=\"application/atom+xml\"]"));

    QMap<KUrl, QString> map;

    foreach(const QWebElement &el, col)
    {
        QString urlString;
        if (el.attribute("href").startsWith(QL1S("http")))
            urlString = el.attribute("href");
        else
        {
            KUrl u = url();
            // NOTE
            // cd() is probably better than setPath() here,
            // for all those url sites just having a path
            if (u.cd(el.attribute("href")))
                urlString = u.toMimeDataString();
        }

        QString title = el.attribute("title");
        if (title.isEmpty())
            title = el.attribute("href");

        map.insert(KUrl(urlString), title);
    }
Пример #2
0
void dilbert::scrap(bool ok)
{
    if (ok)
    {
        ui->progressBar->hide();
        QWebElementCollection imgs = view->page()->mainFrame()->findAllElements("img");
        QWebElement img;
        if (comicid == latest || comicid == QDate(1989, 04, 16))
            img = imgs.at(1);
        else
            img = imgs.at(2);
        QString imgLink = QString("http://dilbert.com").append(img.attribute("src").toAscii().constData());
        ui->webView->setUrl(QUrl(imgLink));
        if (comicid == QDate(1989, 04, 16))
        {
            ui->prev->setEnabled(false);
        }
        else
        {
            ui->prev->setEnabled(true);
        }
        if (comicid == latest)
        {
            ui->next->setEnabled(false);
        }
        else
        {
            ui->next->setEnabled(true);
        }
    }
}
Пример #3
0
void MangaherePlugin::downloadedMangaList(bool ok)
{
    if(!ok)
    {
        qDebug() << tr("There was an error loading the manga list from host 'www.mangahere.co'.");
        return;
    }

    //MangaList successfully downloaded, processing the HTML...

    m_mangaListLoaded = true;
    m_mangaList.clear();

    QWebElement element = m_pPageMangaList.mainFrame()->documentElement();
    QWebElementCollection collAllMangas = element.findAll(".manga_info");

    qDebug() << "Sample Manga:" << collAllMangas.at(0).toPlainText() << " url(" << collAllMangas.at(0).attribute("href", "ERROR") << ")";

    int i = 0;
    foreach (QWebElement oneManga, collAllMangas) {
        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
        Manga::Simple manga;
        manga.title = oneManga.toPlainText();
        manga.url = oneManga.attribute("href", "ERROR");
        m_mangaList << manga;
        i++;
    }
Пример #4
0
//void ArestShopPlugin::SinglePageFound()
//{
//#ifdef USE_WEBKIT
//	QWebFrame * ptrFrame = getWebPage()->mainFrame();
//	parseProductPage(m_stCompData);
//	m_stCompData.strCompURL = ptrFrame->url().toString();
//	emit priceSearchedFinished(m_stCompData);
//	productFoundFinish();
//#endif
//};
void ArestShopPlugin::parseSearchProductPage(SearchResult & stResult,bool & bNextPage)
{
	//run XML search page parse

	bNextPage=false;
#ifdef USE_WEBKIT
	QWebFrame * ptrFrame = getWebPage()->mainFrame();
	//////////////////////////////////////////////////////////////////////////
	QWebElementCollection tableProdRows = ptrFrame->findAllElements("table[class=pricelist]");
	
	for(int iIndex=0;iIndex<tableProdRows.count();++iIndex)
	{
		QWebElement prodNameHeader = tableProdRows.at(iIndex).findFirst("td[class=nazwa]");
		if (prodNameHeader.isNull())
			continue;
		QWebElement productLink = prodNameHeader.findFirst("a");
		QUrl stProductURL = productLink.attribute("href");
		//////////////////////////////////////////////////////////////////////////
		QString strName = productLink.toPlainText();
		stResult.insert(std::make_pair(strName,stProductURL));
	}
	//////////////////////////////////////////////////////////////////////////
	QWebElement tablePageNavi = ptrFrame->findFirstElement("li[class=next]");
	if (tablePageNavi.isNull())
	{
		bNextPage=false;
		return;
	}
	bNextPage=true;
#endif
	stResult.insert(Arest::mSearchResult.begin(),Arest::mSearchResult.end());
	bNextPage=m_bLoadNextPage;
}
Пример #5
0
void QtWebKitWebPage::updateBlockedPageElements(const QStringList domainList, const bool isException)
{
	for (int i = 0; i < domainList.count(); ++i)
	{
		const QList<QString> exceptionList = isException ? ContentBlockingManager::getHidingRulesExceptions().values(domainList.at(i)) : ContentBlockingManager::getSpecificDomainHidingRules().values(domainList.at(i));

		for (int j = 0; j < exceptionList.count(); ++j)
		{
			const QWebElementCollection elements = mainFrame()->documentElement().findAll(exceptionList.at(j));

			for (int k = 0; k < elements.count(); ++k)
			{
				QWebElement element = elements.at(k);

				if (element.isNull())
				{
					continue;
				}

				if (isException)
				{
					element.setStyleProperty(QLatin1String("display"), QLatin1String("block"));
				}
				else
				{
					element.removeFromDocument();
				}
			}
		}
	}
}
Пример #6
0
bool WebTab::hasRSSInfo()
{
    QWebElementCollection col = page()->mainFrame()->findAllElements("link[type=\"application/rss+xml\"]");
    col.append(page()->mainFrame()->findAllElements("link[type=\"application/atom+xml\"]"));
    if (col.count() != 0)
        return true;

    return false;
}
Пример #7
0
void PhpWebView::setTargetBlank()
{
	QWebElementCollection coll = page()->mainFrame()->documentElement().findAll("a");
	for (int i=0; i<coll.count(); i++)
		coll.at(i).setAttribute("target", "_blank");

	QWebElementCollection coll2 = page()->mainFrame()->documentElement().findAll("form");
	for (int i=0; i<coll2.count(); i++)
		coll2.at(i).setAttribute("target", "_blank");
}
Пример #8
0
bool ArestShopPlugin::isSingleProductPage()
{
#ifdef USE_WEBKIT
	QWebFrame * ptrFrame = getWebPage()->mainFrame();
	QWebElementCollection productPage = ptrFrame->findAllElements("h1[class=nazwatowaru]");
	if (productPage.count())
		return true;
#endif
	return false;
}
Пример #9
0
bool ArestShopPlugin::isNotFoundPage()
{
#ifdef USE_WEBKIT
	QWebFrame * ptrFrame = getWebPage()->mainFrame();
	QWebElementCollection notFoundPage = ptrFrame->findAllElements("div[class=searchfailed]");
	if (notFoundPage.count())
		return true;
#endif
	return false;
}
Пример #10
0
    foreach (QWebElement selectField, selectFields) {
        QString name = selectField.attribute(QLatin1String("name"));
        int selectedIndex = selectField.evaluateJavaScript(QLatin1String("this.selectedIndex")).toInt();
        if (selectedIndex == -1)
            continue;

        QWebElementCollection options = selectField.findAll(QLatin1String("option"));
        QString value = options.at(selectedIndex).toPlainText();
        searchUrl.addQueryItem(name, value);
    }
Пример #11
0
RSSWidget::RSSWidget(WebView* view, QWidget* parent)
    : LocationBarPopup(parent)
    , ui(new Ui::RSSWidget)
    , m_view(view)
{
    ui->setupUi(this);

    QWebEngineFrame* frame = m_view->page()->mainFrame();
    QWebElementCollection links = frame->findAllElements("link[type=\"application/rss+xml\"]");

    // Make sure RSS feeds fit into a window, in case there is a lot of feeds from one page
    // See #906
    int cols = links.count() / 10 == 0 ? 1 : links.count() / 10;
    int row = 0;

    for (int i = 0; i < links.count(); i++) {
        QWebElement element = links.at(i);
        QString title = element.attribute("title");
        const QUrl url = QUrl::fromEncoded(element.attribute("href").toUtf8());
        if (url.isEmpty()) {
            continue;
        }

        if (title.isEmpty()) {
            title = tr("Untitled feed");
        }

        QPushButton* button = new QPushButton(this);
        button->setIcon(QIcon(":icons/other/feed.png"));
        button->setStyleSheet("text-align:left");
        button->setText(title);
        button->setProperty("rss-url", url);
        button->setProperty("rss-title", title);

        if (!isRssFeedAlreadyStored(url)) {
            button->setFlat(true);
            button->setToolTip(url.toString());
        }
        else {
            button->setFlat(false);
            button->setEnabled(false);
            button->setToolTip(tr("You already have this feed."));
        }

        int pos = i % cols > 0 ? (i % cols) * 2 : 0;

        ui->gridLayout->addWidget(button, row, pos);
        connect(button, SIGNAL(clicked()), this, SLOT(addRss()));

        if (i % cols == cols - 1) {
            row++;
        }
    }
}
Пример #12
0
void HtmlThread::run()
{
    Helper::Download(this->url);
    QWebElement root;
    QString flag("False");
    emit this->ParseHtml(this->getUrl(),root,flag);
    while("True"==flag){break;}
    QWebElementCollection items;
    items = root.findAll("table");
    qDebug()<<items.count();
}
Пример #13
0
void Browser::loadFinished(bool ok) {
    QUrl current_url(page->currentFrame()->baseUrl());

    // events trottling
    if (current_url == this->last_url)
    {
        qDebug() << this << QString("%1, loadFinished trottled.").arg(QDateTime::currentDateTime().toTime_t());
        return;
    }

    this->last_url = current_url;

    qDebug() << this << QString("%1, '%2', %3 ms.").arg(QDateTime::currentDateTime().toTime_t()).arg(current_url.toString()).arg(page_load_time.elapsed());

    if (!ok) {
        emit(errorHappened(page_load_time.elapsed(), page->currentFrame()->baseUrl()));
        restartTest(QString("its not ok, something wrong happened! (possibly 500) URL: %1").arg(page->currentFrame()->baseUrl().toString()));
        return;
     }

    QWebElement document= page->currentFrame()->documentElement();

    if (page->currentFrame()->baseUrl().host() != base_url.host())
    {
       restartTest("We've got outside the test site. Restarting.");
       return;
    }


    QWebElementCollection collection = document.findAll("a[href]");
    QWebElement link; QString link_href;

    if (collection.count() == 0)
    {
        restartTest("No links found on page. Restarting.");
        return;
    }

    // Ignoring javascript and empty links
    do
    {
       link = collection.at(qrand()%collection.count());
       link_href = link.attribute("href");
    }
    while ((link_href.count() == 0) || (link_href.at(0) == '#') || (link_href.contains("javascript:;")));

    emit(pageLoaded(page_load_time.elapsed(), page->currentFrame()->baseUrl()));

    link.evaluateJavaScript("var evObj = document.createEvent('MouseEvents');evObj.initEvent( 'click', true, true );this.dispatchEvent(evObj);");

    page_load_time.start();
    timeout_countdown->start();
}
Пример #14
0
void WebView::checkRss()
{
    if (m_rssChecked) {
        return;
    }

    m_rssChecked = true;
    QWebFrame* frame = page()->mainFrame();
    const QWebElementCollection links = frame->findAllElements("link[type=\"application/rss+xml\"]");

    m_hasRss = links.count() != 0;
    emit rssChanged(m_hasRss);
}
Пример #15
0
RSSDetectionWidget::RSSDetectionWidget(WebView* view, QWidget* parent)
  : QFrame(parent, Qt::Popup)
  , view_(view)
{
  setAttribute(Qt::WA_DeleteOnClose);
  setFrameStyle(QFrame::StyledPanel | QFrame::Plain);
  setLineWidth(1);
  setMidLineWidth(2);

  gridLayout_ = new QGridLayout(this);
  gridLayout_->setMargin(5);
  gridLayout_->setSpacing(5);

  QWebFrame* frame = view_->page()->mainFrame();
  QWebElementCollection links = frame->findAllElements("link[type=\"application/rss+xml\"]");

  int cols = links.count() / 10 == 0 ? 1 : links.count() / 10;
  int row = 0;

  for (int i = 0; i < links.count(); i++) {
    QWebElement element = links.at(i);
    QString title = element.attribute("title");
    const QUrl url = QUrl::fromEncoded(element.attribute("href").toUtf8());
    if (url.isEmpty()) {
      continue;
    }

    if (title.isEmpty()) {
      title = tr("Untitled feed");
    }

    QPushButton* button = new QPushButton(this);
    button->setStyleSheet("QPushButton {text-align:left; border: none; padding: 0px;}"
                          "QPushButton:hover {color: #1155CC;}");
    button->setCursor(Qt::PointingHandCursor);
    button->setText(title);
    button->setToolTip(url.toString());
    button->setProperty("rss-url", url);
    button->setProperty("rss-title", title);

    int pos = i % cols > 0 ? (i % cols) * 2 : 0;

    gridLayout_->addWidget(button, row, pos);
    connect(button, SIGNAL(clicked()), this, SLOT(addRss()));

    if (i % cols == cols - 1) {
      row++;
    }
  }
}
Пример #16
0
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();
  }
}
Пример #17
0
void tdRenderer::render(QByteArray ba)
{
    bufreset(m_buffer);
    QWebElement element = m_body.findFirst(".__tmp__");

    const char *data = ba.data();
    uint beg = 0;
    size_t e = ba.size();
    int prevsize = 0;
    int pos = m_fframe;

    while (beg < e) {
        const char *offs = data + beg;
        int n = td_markdown_render(m_buffer, (const uint8_t *) offs,
                                   e - beg, m_markdown);

        QByteArray bytes((const char *) m_buffer->data + prevsize, m_buffer->size - prevsize);

        m_sizes.insert(pos, n);
        m_indices.insert(pos++, m_index);

        if (m_pants) {
            bufreset(m_tmpbuffer);
            sdhtml_smartypants(m_tmpbuffer, (const uint8_t *) bytes.constData(), bytes.size());
            QByteArray pants((const char *) m_tmpbuffer->data, m_tmpbuffer->size);
            element.appendInside(pants);
        } else {
            element.appendInside(bytes);
        }

        QWebElementCollection children = element.findAll("*");
        QString klassName = "__" % QString::number(m_index++) % "__";
        QWebElementCollection::const_iterator i = children.constBegin();
        for (; i != children.constEnd(); ++i) {
            QWebElement e = *i;
            e.addClass(klassName);
            if (!e.parent().hasClass(klassName))
                element.prependOutside(e.takeFromDocument());
        }
        if (m_body.findFirst("." % klassName).isNull())
            element.prependOutside("<span class=\"" % klassName % "\"></span>");

        beg += n;
        prevsize = m_buffer->size;
    }
    element.takeFromDocument();
}
static PyObject *meth_QWebElementCollection_count(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        QWebElementCollection *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "B", &sipSelf, sipType_QWebElementCollection, &sipCpp))
        {
            int sipRes;

            Py_BEGIN_ALLOW_THREADS
            sipRes = sipCpp->count();
            Py_END_ALLOW_THREADS

            return SIPLong_FromLong(sipRes);
        }
    }
Пример #19
0
void downloader::render(QString rawHtml)
{
    currencyLoaded.clear();
    rateLoaded.clear();
    QWebFrame *mainFrame = webPage.mainFrame();
    mainFrame->setHtml(rawHtml);
    QWebElement documentElement = mainFrame->documentElement();
    QWebElementCollection elements = documentElement.findAll("#content > div:nth-child(1) > div > div.col2.pull-right.module.bottomMargin > div.moduleContent > table:nth-child(4) > tbody > tr");

    int i = 0;
    foreach (QWebElement element, elements)
    {
        currency.push_back(element.findFirst("td:nth-child(1)").toInnerXml());
        rate.push_back(element.findFirst("td:nth-child(3) > a").toInnerXml());
//        qDebug()<< currency[i+(elements.count()*downloadCount)]+"\t\t"+rate[i+(elements.count()*downloadCount)]+"\n";

        currencyLoaded.push_back(currency[i+(elements.count()*downloadCount)]);
        rateLoaded.push_back(rate[i+(elements.count()*downloadCount)]);
        i++;
    }
Пример #20
0
void HtmlExtractor::moveTemplates(const QString &path)
{
    MakeDirectory(path);
    QDir dir(path);
    QWebElementCollection elements = getDocument().findAll("[type=\"text/template\"]");
    if(elements.count())
    {
        for(QWebElementCollection::iterator it = elements.begin(), end=elements.end(); it!=end; ++it)
        {
            QWebElement element = *it;
            QString filename = element.attribute("id").replace("_tpl",".tpl");
            qDebug()<<"moving element : "<<filename;
            move(element, dir.filePath(filename), false);
        }
    }
    else
    {
        qDebug()<<"no element found";
    }
}
Пример #21
0
void MarbleLegendBrowser::setRadioCheckedProperty( const QString& value, const QString& name , bool checked )
{
#ifndef MARBLE_NO_WEBKIT
    QWebElement box = page()->mainFrame()->findFirstElement("input[value="+value+']');
    QWebElementCollection boxes = page()->mainFrame()->findAllElements("input[name="+name+']');
    QString currentValue="";
    for(int i=0; i<boxes.count(); ++i) {
        currentValue = boxes.at(i).attribute("value");
        d->m_checkBoxMap[currentValue]=false;
        emit toggledShowProperty( currentValue, false );
    }
    if (!box.isNull()) {
        if (checked != d->m_checkBoxMap[value]) {
            d->m_checkBoxMap[value] = checked;
            emit toggledShowProperty( value, checked );
        }
    }

    update();
#endif
}
static PyObject *meth_QWebElementCollection_append(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        const QWebElementCollection * a0;
        QWebElementCollection *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BJ9", &sipSelf, sipType_QWebElementCollection, &sipCpp, sipType_QWebElementCollection, &a0))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->append(*a0);
            Py_END_ALLOW_THREADS

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QWebElementCollection, sipName_append, NULL);

    return NULL;
}
Пример #23
0
/*
  This will go through and modify some of the ENML tags and turn
  them into HTML tags.  Things like en-media & en-crypt have no
  HTML values, so we turn them into HTML.
  */
void NoteFormatter::modifyTags(QWebPage &doc) {
    tempFiles.clear();

    // Modify en-media tags
    QLOG_TRACE() << "Searching for all en-media tags;";
    QWebElementCollection anchors = doc.mainFrame()->findAllElements("en-media");
    QLOG_TRACE() << "Search complete: " << anchors.toList().size();
    foreach (QWebElement enmedia, anchors) {
        if (enmedia.hasAttribute("type")) {
            QString attr = enmedia.attribute("type");
            QString hash = enmedia.attribute("hash");
            QStringList type = attr.split("/");
            if (type.size() >= 2) {
                QString appl = type[1];
                QLOG_TRACE() << "En-Media tag type: " << type[0];
                if (type[0] == "image")
                    modifyImageTags(enmedia, hash);
                else
                    modifyApplicationTags(enmedia, hash, appl);
                QLOG_TRACE() << "Type modified";
            }
        }
    }

    // Modify todo tags
    anchors = doc.mainFrame()->findAllElements("en-todo");
    qint32 enTodoCount = anchors.count();
    for (qint32 i=enTodoCount-1; i>=0; i--) {
            QWebElement enmedia = anchors.at(i);
            modifyTodoTags(enmedia);
    }

    anchors = doc.mainFrame()->findAllElements("en-crypt");
    qint32 enCryptLen = anchors.count();
    for (qint32 i=enCryptLen-1; i>=0; i--) {
        QWebElement enmedia = anchors.at(i);
        QString hint = enmedia.attribute("hint");
        QString cipher = enmedia.attribute("cipher", "RC2");
        QString length = enmedia.attribute("length","64");

        enmedia.setAttribute("contentEditable","false");
        enmedia.setAttribute("src", QString("file://")+global.fileManager.getImageDirPath("encrypt.png"));
        enmedia.setAttribute("en-tag","en-crypt");
        enmedia.setAttribute("cipher", cipher);
        enmedia.setAttribute("length", length);
        enmedia.setAttribute("hint", hint);
        enmedia.setAttribute("alt", enmedia.toInnerXml());
        global.cryptCounter++;
        enmedia.setAttribute("id", "crypt"+QString().number(global.cryptCounter));
        QString encryptedText = enmedia.toInnerXml();

        // If the encryption string contains crlf at the end, remove them because they mess up the javascript.
        if (encryptedText.endsWith("\n"))
                encryptedText.truncate(encryptedText.length()-1);
        if (encryptedText.endsWith("\r"))
                encryptedText.truncate(encryptedText.length()-1);

        // Add the commands
        hint = hint.replace("'","&apos;");
        enmedia.setAttribute("onClick", "window.browserWindow.decryptText('crypt"+
                             QString().number(global.cryptCounter)+
                             "', '"+encryptedText+"', '"+
                             hint +"', '" +
                             cipher+ "', " +
                             length +
                             ");");
        enmedia.setAttribute("onMouseOver", "style.cursor='hand'");
        enmedia.setInnerXml("");
        QString k = enmedia.toOuterXml();
        k.replace("<en-crypt", "<img");
        k.replace("img>", "<en-crypt");
        enmedia.setOuterXml(k);
    }


    // Modify link tags
    anchors = doc.mainFrame()->findAllElements("a");
    enCryptLen = anchors.count();
    for (qint32 i=0; i<anchors.count(); i++) {
        QWebElement element = anchors.at(i);
        if (!element.attribute("href").toLower().startsWith("latex://"))
            element.setAttribute("title", element.attribute("href"));
        else {
            element.setAttribute("title", element.attribute("title").toLower().replace("http://latex.codecogs.com/gif.latex?",""));
        }
    }

}
Пример #24
0
void Printer::render(int Pages = 0)
{
	// keep original preferences
	QPointer<ProfileWidget2> profile = MainWindow::instance()->graphics();
	int profileFrameStyle = profile->frameStyle();
	int animationOriginal = prefs.animation_speed;
	double fontScale = profile->getFontPrintScale();
	double printFontScale = 1.0;

	// apply printing settings to profile
	profile->setFrameStyle(QFrame::NoFrame);
	profile->setPrintMode(true, !printOptions->color_selected);
	profile->setToolTipVisibile(false);
	prefs.animation_speed = 0;

	// render the Qwebview
	QPainter painter;
	QRect viewPort(0, 0, pageSize.width(), pageSize.height());
	painter.begin(paintDevice);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);

	// get all refereces to diveprofile class in the Html template
	QWebElementCollection collection = webView->page()->mainFrame()->findAllElements(".diveprofile");

	QSize originalSize = profile->size();
	if (collection.count() > 0) {
		printFontScale = (double)collection.at(0).geometry().size().height() / (double)profile->size().height();
		profile->resize(collection.at(0).geometry().size());
	}
	profile->setFontPrintScale(printFontScale);

	int elemNo = 0;
	for (int i = 0; i < Pages; i++) {
		// render the base Html template
		webView->page()->mainFrame()->render(&painter, QWebFrame::ContentsLayer);

		// render all the dive profiles in the current page
		while (elemNo < collection.count() && collection.at(elemNo).geometry().y() < viewPort.y() + viewPort.height()) {
			// dive id field should be dive_{{dive_no}} se we remove the first 5 characters
			QString diveIdString = collection.at(elemNo).attribute("id");
			int diveId = diveIdString.remove(0, 5).toInt(0, 10);
			putProfileImage(collection.at(elemNo).geometry(), viewPort, &painter, get_dive_by_uniq_id(diveId), profile);
			elemNo++;
		}

		// scroll the webview to the next page
		webView->page()->mainFrame()->scroll(0, pageSize.height());
		viewPort.adjust(0, pageSize.height(), 0, pageSize.height());

		// rendering progress is 4/5 of total work
		emit(progessUpdated((i * 80.0 / Pages) + done));
		if (i < Pages - 1 && printMode == Printer::PRINT)
			static_cast<QPrinter*>(paintDevice)->newPage();
	}
	painter.end();

	// return profle settings
	profile->setFrameStyle(profileFrameStyle);
	profile->setPrintMode(false);
	profile->setFontPrintScale(fontScale);
	profile->setToolTipVisibile(true);
	profile->resize(originalSize);
	prefs.animation_speed = animationOriginal;

	//replot the dive after returning the settings
	profile->plotDive(0, true);
}
Пример #25
0
void tdRenderer::parseMarkdown(int at, int removed, int added)
{
    QTextCursor cursor = m_editor->textCursor();
    cursor.beginEditBlock();

    int steps = m_editor->document()->availableUndoSteps();
    bool undoStepsChanged = (steps != m_undoSteps);
    m_undoSteps = steps;

    if (undoStepsChanged && !m_isUndoRedo)
        m_undoStack->push(new tdRendererCursorCommand(this, at, removed, added));
    m_isUndoRedo = false;

    int start;
    int end;
    if (m_sizes.isEmpty()) {
        start = end = 0;
    } else {
        int i = 0, n = 0;
        while (i < m_fframe)
            n += m_sizes.at(i++);
        start = n;
        while (i <= m_lframe)
            n += m_sizes.at(i++);
        end = n;
    }

    int diff = added - removed;
    m_count += diff;
    if (m_sizes.isEmpty()) end = m_count;
    else end += diff;

    cursor.setPosition(start);
    cursor.setPosition(qMin(end, m_count), QTextCursor::KeepAnchor);

    int c = m_fframe;
    int klass = 0;
    QWebElementCollection collection;
    while (c++ <= m_lframe && !m_sizes.isEmpty()) {
        m_sizes.takeAt(m_fframe);
        klass = m_indices.takeAt(m_fframe);
        collection.append(m_body.findAll(".__" % QString::number(klass) % "__"));
    }
    QList<QWebElement> list = collection.toList();
    QWebElement element;

    if (klass) {
        QString k = "__" % QString::number(klass) % "__";
        element = list.last();
        while (element.parent().hasClass(k))
            element = element.parent();
        list.removeAll(element);
        element.setOuterXml("<div class=\"__tmp__\"></div>");

        QList<QWebElement>::iterator i = list.begin();
        for (; i != list.end(); ++i)
            i->takeFromDocument();
    } else {
        m_body.prependInside("<div class=\"__tmp__\"></div>");
    }

    render(cursor.selection().toPlainText().toAscii());

    cursor.endEditBlock();
    updateFrameInterval();
    emit parsingDone();
}
Пример #26
0
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;
	}
}
Пример #27
0
void AutoFillModel::post(const QNetworkRequest &request, const QByteArray &outgoingData)
{
    //Dont save in private browsing
    if (mApp->webSettings()->testAttribute(QWebSettings::PrivateBrowsingEnabled)) {
        return;
    }

    m_lastOutgoingData = outgoingData;

    QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
    WebPage* webPage = static_cast<WebPage*>(v.value<void*>());
    if (!webPage) {
        return;
    }
    WebView* webView = qobject_cast<WebView*>(webPage->view());
    if (!webView) {
        return;
    }

    v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 101));
    QWebPage::NavigationType type = (QWebPage::NavigationType)v.toInt();

    if (type != QWebPage::NavigationTypeFormSubmitted) {
        return;
    }

    QString usernameName;
    QString usernameValue;
    QString passwordName;
    QString passwordValue;
    QUrl siteUrl = webPage->url();

    if (!isStoringEnabled(siteUrl)) {
        return;
    }

    QWebElementCollection allForms; // All form elements on page
    QWebElement foundForm;          // Sent form element

    QList<QWebFrame*> frames;
    frames.append(webPage->mainFrame());  // Find all form elements
    while (!frames.isEmpty()) {
        QWebFrame* frame = frames.takeFirst();
        allForms.append(frame->findAllElements("form"));
        frames += frame->childFrames();
    }

    foreach(const QWebElement & formElement, allForms) {
        foreach(const QWebElement &inputElement, formElement.findAll("input[type=\"password\"]")) {
            passwordName = inputElement.attribute("name");
            passwordValue = getValueFromData(outgoingData, inputElement);

            if (!passwordValue.isEmpty() && dataContains(outgoingData, passwordName)) {
                foundForm = formElement;
                break;
            }
        }

        if (!foundForm.isNull()) {
            break;
        }
    }
Пример #28
0
void AutoFillModel::completePage(WebPage* page)
{
    if (!page) {
        return;
    }

    QUrl pageUrl = page->url();
    if (!isStored(pageUrl)) {
        return;
    }

    QWebElementCollection inputs;
    QList<QWebFrame*> frames;
    frames.append(page->mainFrame());
    while (!frames.isEmpty()) {
        QWebFrame* frame = frames.takeFirst();
        inputs.append(frame->findAllElements("input"));
        frames += frame->childFrames();
    }

    QString server = pageUrl.host();
    if (server.isEmpty()) {
        server = pageUrl.toString();
    }

    QSqlQuery query;
    query.prepare("SELECT data FROM autofill WHERE server=?");
    query.addBindValue(server);
    query.exec();
    query.next();
    QByteArray data = query.value(0).toByteArray();
    if (data.isEmpty()) {
        return;
    }

    // Why not to use encodedQueryItems = QByteArrays ?
    // Because we need to filter "+" characters that must be spaces
    // (not real "+" characters "%2B")

    QueryItems arguments = QUrl::fromEncoded("http://bla.com/?" + data).queryItems();
    for (int i = 0; i < arguments.count(); i++) {
        QString key = arguments.at(i).first;
        QString value = arguments.at(i).second;
        key.replace("+", " ");
        value.replace("+", " ");

        key = QUrl::fromEncoded(key.toUtf8()).toString();
        value = QUrl::fromEncoded(value.toUtf8()).toString();

        for (int i = 0; i < inputs.count(); i++) {
            QWebElement element = inputs.at(i);

            if (element.attribute("type") != "text" && element.attribute("type") != "password" && element.attribute("type") != "") {
                continue;
            }
            if (key == element.attribute("name")) {
                element.setAttribute("value", value);
            }
        }
    }
}
Пример #29
0
void WebPage::handleBase64Download(QWebFrame* pWebFrame, QUrl url)
{
    // look for beginning of base64 data
    QString base64 = QString::fromUtf8("base64,");
    int pos = url.path().indexOf(base64);
    if (pos == -1)
    {
        LOG_ERROR_MESSAGE("Base64 designator not found in data url");
        return;
    }

    // extract the base64 data from the uri
    QString base64Data = url.path();
    base64Data.remove(0, pos + base64.length());
    QByteArray base64ByteArray(base64Data.toStdString().c_str());
    QByteArray byteArray = QByteArray::fromBase64(base64ByteArray);

    // find the a tag in the page with this href
    QWebElement aTag;
    QString urlString = url.toString(QUrl::None);
    QWebElementCollection aElements = pWebFrame->findAllElements(
                                          QString::fromUtf8("a"));
    for (int i=0; i<aElements.count(); i++)
    {
        QWebElement a = aElements.at(i);
        QString href = a.attribute(QString::fromUtf8("href"));
        href.replace(QChar::fromAscii('\n'), QString::fromUtf8(""));
        if (href == urlString)
        {
            aTag = a;
            break;
        }
    }

    // if no a tag was found then bail
    if (aTag.isNull())
    {
        LOG_ERROR_MESSAGE("Unable to finding matching a tag for data url");
        return;
    }

    // get the download attribute (default filename)
    QString download = aTag.attribute(QString::fromUtf8("download"));
    QString defaultFilename = defaultSaveDir_.absoluteFilePath(download);

    // prompt for filename
    QString filename = QFileDialog::getSaveFileName(
                           NULL,
                           tr("Download File"),
                           defaultFilename,
                           defaultSaveDir_.absolutePath(),
                           0,
                           standardFileDialogOptions());
    if (!filename.isEmpty())
    {
        // see if we need to force the extension
        FilePath defaultFilePath(defaultFilename.toUtf8().constData());
        FilePath chosenFilePath(filename.toUtf8().constData());
        if (chosenFilePath.extension().empty() &&
                !defaultFilePath.extension().empty())
        {
            filename += QString::fromStdString(defaultFilePath.extension());
        }

        // write the file
        QFile file(filename);
        if (file.open(QIODevice::WriteOnly))
        {
            if (file.write(byteArray) == -1)
            {
                showFileError(QString::fromUtf8("writing"),
                              filename,
                              file.errorString());
            }

            file.close();
        }
        else
        {
            showFileError(QString::fromUtf8("writing"),
                          filename,
                          file.errorString());
        }

        // persist the defaultSaveDir
        defaultSaveDir_ = QFileInfo(file).dir();
    }
}
Пример #30
0
SiteInfo::SiteInfo(WebView* view, QWidget* parent)
    : QDialog(parent)
    , ui(new Ui::SiteInfo)
    , m_certWidget(0)
    , m_view(view)
{
    setAttribute(Qt::WA_DeleteOnClose);
    ui->setupUi(this);

    ui->listWidget->item(0)->setIcon(QIcon::fromTheme("document-properties", QIcon(":/icons/preferences/document-properties.png")));
    ui->listWidget->item(1)->setIcon(QIcon::fromTheme("applications-graphics", QIcon(":/icons/preferences/applications-graphics.png")));
    ui->listWidget->item(2)->setIcon(QIcon::fromTheme("text-x-sql", QIcon(":/icons/preferences/text-x-sql.png")));
    ui->listWidget->item(3)->setIcon(QIcon::fromTheme("dialog-password", QIcon(":/icons/preferences/dialog-password.png")));
    ui->listWidget->item(0)->setSelected(true);

    WebPage* webPage = view->page();
    QWebFrame* frame = view->page()->mainFrame();
    QString title = view->title();
    QSslCertificate cert = webPage->sslCertificate();
    m_baseUrl = frame->baseUrl();

    //GENERAL
    ui->heading->setText(QString("<b>%1</b>:").arg(title));
    ui->siteAddress->setText(view->url().toString());
    ui->sizeLabel->setText(qz_fileSizeToString(webPage->totalBytes()));
    QString encoding;

    //Meta
    QWebElementCollection meta = frame->findAllElements("meta");
    for (int i = 0; i < meta.count(); i++) {
        QWebElement element = meta.at(i);

        QString content = element.attribute("content");
        QString name = element.attribute("name");
        if (name.isEmpty()) {
            name = element.attribute("http-equiv");
        }
        if (!element.attribute("charset").isEmpty()) {
            encoding = element.attribute("charset");
        }
        if (content.contains(QLatin1String("charset="))) {
            encoding = content.mid(content.indexOf(QLatin1String("charset=")) + 8);
        }

        if (content.isEmpty() || name.isEmpty()) {
            continue;
        }
        QTreeWidgetItem* item = new QTreeWidgetItem(ui->treeTags);
        item->setText(0, name);
        item->setText(1, content);
        ui->treeTags->addTopLevelItem(item);
    }
    if (encoding.isEmpty()) {
        encoding = mApp->webSettings()->defaultTextEncoding();
    }
    ui->encodingLabel->setText(encoding.toUpper());

    //MEDIA
    QWebElementCollection img = frame->findAllElements("img");
    for (int i = 0; i < img.count(); i++) {
        QWebElement element = img.at(i);

        QString src = element.attribute("src");
        QString alt = element.attribute("alt");
        if (alt.isEmpty()) {
            if (src.indexOf(QLatin1Char('/')) == -1) {
                alt = src;
            }
            else {
                int pos = src.lastIndexOf(QLatin1Char('/'));
                alt = src.mid(pos);
                alt.remove(QLatin1Char('/'));
            }
        }
        if (src.isEmpty() || alt.isEmpty()) {
            continue;
        }
        QTreeWidgetItem* item = new QTreeWidgetItem(ui->treeImages);
        item->setText(0, alt);
        item->setText(1, src);
        ui->treeImages->addTopLevelItem(item);
    }

    //DATABASES
    const QList<QWebDatabase> &databases = frame->securityOrigin().databases();

    int counter = 0;
    foreach(const QWebDatabase & b, databases) {
        QListWidgetItem* item = new QListWidgetItem(ui->databaseList);
        item->setText(b.displayName());
        item->setData(Qt::UserRole + 10, counter);

        ++counter;
    }