void MainWindow::_loadFinished(bool ok) { if (ok) { QString indexUrl = _appSettings.host(); indexUrl += "index.php"; QString pageUrl = ui->webView->url().toString(); QWebPage* page = ui->webView->page(); QWebFrame* frame = page->currentFrame(); QWebElement root = frame->documentElement(); if (!root.findFirst("#loginForm").isNull()) { QWebElementCollection allInputs = root.findAll("input"); foreach (QWebElement inputElement, allInputs) { if (inputElement.hasAttribute("name")) { QString name = inputElement.attribute("name"); if (name == "username") { inputElement.setAttribute("value", _appSettings.user()); } else if (name == "password") { inputElement.setAttribute("value", _appSettings.password()); } } } root.findFirst("input[type=submit]").evaluateJavaScript("this.click()"); } else if (pageUrl == indexUrl)
StationScheduleItem parseResult(const QWebElement &result) { StationScheduleItem item; QWebElement current = result.findFirst("h2"); if (!current.isNull()) { item.setTrain(current.toPlainText()); } parseDetailsUrl(result, item); current = result.findFirst("div.bloccotreno"); parseDelayClass(current, item); QString rawText = current.toPlainText(); parseTrain(rawText, item); qDebug() << "train:" << item.train(); qDebug() << "delayClass:" << item.delayClass(); qDebug() << "detailsUrl:" << item.detailsUrl(); qDebug() << "departureStation:" << item.departureStation(); qDebug() << "departureTime:" << item.departureTime(); qDebug() << "arrivalStation:" << item.arrivalStation(); qDebug() << "arrivalTime:" << item.arrivalTime(); qDebug() << "expectedPlatform:" << item.expectedPlatform(); qDebug() << "actualPlatform:" << item.actualPlatform(); qDebug() << "delay:" << item.delay(); return item; }
void lmcMessageLog::removeMessageLog(QString divClass) { QWebFrame* frame = page()->mainFrame(); QWebElement document = frame->documentElement(); QWebElement body = document.findFirst("body"); QWebElement element = body.findFirst("div." + divClass); element.removeFromDocument(); }
void CellmlAnnotationViewMetadataNormalViewDetailsWidget::filePermissionsChanged() { // Enable or disable the remove buttons for our RDF triples, depending on // whether the file is un/locked bool fileReadableAndWritable = Core::FileManager::instance()->isReadableAndWritable(mCellmlFile->fileName()); QWebElement documentElement = mOutputOntologicalTerms->page()->mainFrame()->documentElement(); foreach (const QString &rdfTripleInformationSha1, mRdfTripleInformationSha1s) { documentElement.findFirst(QString("td[id=button_%1]").arg(rdfTripleInformationSha1)).setStyleProperty("display", fileReadableAndWritable?"table-cell":"none"); documentElement.findFirst(QString("td[id=disabledButton_%1]").arg(rdfTripleInformationSha1)).setStyleProperty("display", !fileReadableAndWritable?"table-cell":"none"); }
void WebPage::handleUnsupportedContent(QNetworkReply* reply) { if (!reply) { return; } const QUrl url = reply->url(); switch (reply->error()) { case QNetworkReply::NoError: if (reply->header(QNetworkRequest::ContentTypeHeader).isValid()) { QString requestUrl = reply->request().url().toString(QUrl::RemoveFragment | QUrl::RemoveQuery); if (requestUrl.endsWith(QLatin1String(".swf"))) { const QWebElement docElement = mainFrame()->documentElement(); const QWebElement object = docElement.findFirst(QString("object[src=\"%1\"]").arg(requestUrl)); const QWebElement embed = docElement.findFirst(QString("embed[src=\"%1\"]").arg(requestUrl)); if (!object.isNull() || !embed.isNull()) { qDebug() << "WebPage::UnsupportedContent" << url << "Attempt to download flash object on site!"; reply->deleteLater(); return; } } DownloadManager* dManager = mApp->downloadManager(); dManager->handleUnsupportedContent(reply, this); return; } // Falling unsupported content with invalid ContentTypeHeader to be handled as UnknownProtocol case QNetworkReply::ProtocolUnknownError: { if (url.scheme() == QLatin1String("file")) { FileSchemeHandler::handleUrl(url); return; } qDebug() << "WebPage::UnsupportedContent" << url << "ProtocolUnknowError"; desktopServicesOpen(url); reply->deleteLater(); return; } default: break; } qDebug() << "WebPage::UnsupportedContent error" << url << reply->errorString(); reply->deleteLater(); }
//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; }
bool Page_Login::doLogin ( int servNo, const QString& login, const QString& password, bool keep) { Q_ASSERT(!document.isNull()); QWebElement form = document.findFirst("FORM[id=loginForm]"); if (form.isNull()) { qCritical("login form not found"); return false; } //QWebElement submit = form.findFirst("INPUT[type=submit]"); if (submit.isNull()) { qCritical("submit button not found"); return false; } js_setById("server", servNo); js_setByName("email", login); js_setByName("password", password); if (keep) { js("document.getElementsByName('remember')[0].checked=true;"); } qDebug("press login button"); pressSubmit(); return true; }
// --- DIAGNOSE LOAD --- // Verify that the page loaded successfully, else present error message. // If successful, set other data parts and handle filters. void MainWindow::diagnoseLoad(bool ok) { setReloadButton(); if (!ok) { //QMessageBox::critical(this, tr("Error"), tr("Failed to load the URL")); // FIXME: triggers crash with favicon path customized due to QtWebkit bug! // Don't return to the event loop. } else { //QWidget* tab = tabWidget->currentWidget tabWidget->setTabText(tabWidget->currentIndex(), wv->title()); tabWidget->setTabIcon(tabWidget->currentIndex(), wv->icon()); addressBar->setText(wv->url().toString()); QString title = wv->title(); if (title.size() > 200) { title.resize(200); } setWindowTitle(title + " - WildFox"); // check the page URL against the filters if (extFilters.size() < 1) { return; } QWebPage* page = (QWebPage*) sender(); if (page == 0) { return; } QWebFrame* frame = page->mainFrame(); if (frame == 0) { return; } QString url = frame->url().path(); QStringList urlbit = url.split("://"); QDir extension; extension.setPath(manifest.fileName()); if (urlbit.size() > 1) { QString scheme = urlbit[0]; QStringList bits = urlbit[1].split("."); for (int i = 0; i < extFilters.size(); ++i) { if (extFilters[i].scheme != scheme) { continue; } for (int j = 0; extFilters[i].segments.size(); ++j) { if (extFilters[i].segments[j] != bits[j] && extFilters[i].segments[j] != "*") { continue; } } // matched filter, inject associated scripts into the content. QWebElement root = frame->documentElement(); QWebElement head = root.findFirst("head"); head.appendOutside("<script type=\"text/javascript\" src=\"" + extension.absolutePath() + "\" />"); } } } }
void lmcMessageLog::appendPublicMessage(QString* lpszUserId, QString* lpszUserName, QString* lpszMessage, QDateTime *pTime, QFont *pFont, QColor *pColor) { QString html = QString::null; bool localUser = (lpszUserId->compare(localId) == 0); decodeMessage(lpszMessage); QString fontStyle = getFontStyle(pFont, pColor, localUser); if(lpszUserId->compare(lastId) != 0) { outStyle = !outStyle; html = outStyle ? themeData.outMsg : themeData.inMsg; // get the avatar image for this user from the cache folder QString filePath = participantAvatars.value(*lpszUserId); // if image not found, use the default avatar image for this user QString iconPath = QFile::exists(filePath) ? QUrl::fromLocalFile(filePath).toString() : "qrc"AVT_DEFAULT; html.replace("%iconpath%", iconPath); html.replace("%sender%", *lpszUserName); html.replace("%time%", getTimeString(pTime)); html.replace("%style%", fontStyle); html.replace("%message%", *lpszMessage); QWebFrame* frame = page()->mainFrame(); QWebElement document = frame->documentElement(); QWebElement body = document.findFirst("body"); body.appendInside(html); } else { html = outStyle ? themeData.outNextMsg : themeData.inNextMsg; html.replace("%time%", getTimeString(pTime)); html.replace("%style%", fontStyle); html.replace("%message%", *lpszMessage); QWebFrame* frame = page()->mainFrame(); QWebElement document = frame->documentElement(); QWebElement body = document.findFirst("body"); QWebElement last = body.lastChild(); QWebElement insert = last.findFirst("div#insert"); insert.replace(html); } hasData = true; }
static void parseDetailsUrl(const QWebElement &element, StationScheduleItem &item) { if (!element.isNull()) { QWebElement link = element.findFirst("a"); QString url = link.attribute("href"); item.setDetailsUrl(url); } else { qDebug() << "link not found"; } }
//static bool Page_Login::fit(const QWebElement& doc) { // qDebug("* CHECK Page_Login"); QWebElement loginForm = doc.findFirst("FORM[id=loginForm]"); if (loginForm.isNull()) { // qDebug("Page_Login does not fit (has no loginForm)"); return false; } QWebElement do_cmd = loginForm.findFirst("INPUT[name=do_cmd]"); if (do_cmd.isNull()) { // qDebug("Page_Login does not fit (has no do_cmd)"); return false; } if (do_cmd.attribute("value") != "login") { // qDebug("Page_Login does not fit (do_cmd != login)"); return false; } // qDebug("Page_Login fits"); return true; }
void LyricsManiaAPI::onGetLyricPageResult() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); bool found = false; Lyric* lyric = 0; if (reply->error() != QNetworkReply::NoError) { qCritical() << "Cannot fetch lyric"; } else { QWebPage page; page.settings()->setAttribute(QWebSettings::AutoLoadImages, false); page.settings()->setAttribute(QWebSettings::JavascriptEnabled, false); page.mainFrame()->setHtml(reply->readAll()); QWebElement lyricbox = page.mainFrame()->findFirstElement("div[class=lyrics-body]"); if (lyricbox.isNull()) { qCritical() << "Cannot find lyric text in HTML page"; } else { // Remove the video div lyricbox.findFirst(QStringLiteral("div")).removeFromDocument(); // Remove the song title lyricbox.findFirst(QStringLiteral("strong")).removeFromDocument(); lyric = lyrics.take(reply); if (!lyric) { qCritical() << "Got an invalid lyric object!"; } else { lyric->setText(lyricbox.toPlainText()); found = true; } } } qDebug() << "Lyric found:" << found; Q_EMIT lyricFetched(lyric, found); reply->deleteLater(); }
bool Page_Game_Dozor_LowHealth::fit(const QWebElement& doc) { // qDebug("* CHECK Page_Game_Dozor_LowHealth"); if (doc.findFirst("DIV[id=body] DIV[class=grbody]") .toPlainText().trimmed().startsWith( u8("У вас слишком мало здоровья."))) { // qDebug("CHECK Page_Game_Dozor_LowHealth fits"); return true; } // qDebug("CHECK Page_Game_Dozor_LowHealth doesn't fit"); return false; }
/** * @fn sendReportUsingGitreport */ void GitreportModule::sendReportUsingGitreport(const QMap<QString, QString> info) { if (debug) qDebug() << "[GitreportModule]" << "[sendReportUsingGitreport]"; QWebElement document = webView->page()->mainFrame()->documentElement(); QWebElement captchaKey = document.findFirst(QString("input#captcha")); QWebElement emailInput = document.findFirst(QString("input#email")); QWebElement textArea = document.findFirst(QString("textarea#details")); QWebElement usernameInput = document.findFirst(QString("input#name")); // input usernameInput.setAttribute(QString("value"), info[QString("username")]); emailInput.setAttribute(QString("value"), info[QString("password")]); textArea.setPlainText(info[QString("body")]); captchaKey.setAttribute(QString("value"), info[QString("captcha")]); // send request document.findFirst(QString("input[name=commit]")).evaluateJavaScript("this.click()"); disconnect(webView, SIGNAL(loadFinished(bool)), this, SLOT(gitreportLoaded(bool))); disconnect(webView, SIGNAL(loadFinished(bool)), this, SLOT(gitreportFinished(bool))); connect(webView, SIGNAL(loadFinished(bool)), this, SLOT(gitreportFinished(bool))); }
ChromeSnippet *ChromeDOM::getSnippet(const QString &docElementId, QGraphicsItem* parent) { Q_UNUSED(parent) ChromeSnippet * snippet = 0; QWebElement doc = m_page->mainFrame()->documentElement(); QWebElement element = doc.findFirst("#" + docElementId); QRect rect = element.geometry(); //TODO: This may not be accurate since final heights may not have been computed at this point!! m_height += rect.height(); // qDebug() << "Snippet: ID: " << docElementId << " Owner Area: " << rect << " Element Rect: " << element.geometry(); if (!rect.isNull()) { QString className = element.attribute("data-GinebraNativeClass", "__NO_CLASS__"); if (className == "__NO_CLASS__") { if (element.attribute("data-GinebraContainer", "false") == "true") { snippet = new WebChromeContainerSnippet(docElementId, m_chrome, element); snippet->setChromeWidget(new ChromeItem(snippet)); } else { snippet = new WebChromeSnippet(docElementId, m_chrome, element); m_renderer->addRenderItem((static_cast<WebChromeSnippet*> (snippet))->item()); } } else { snippet = nativeSnippetForClassName(className, docElementId, element); //TODO: Is the following still needed? QGraphicsWidget * widget = snippet->widget(); //Have snippet determine its own size when in anchor layout. Again, these will not //necessarily be accurate at this point. widget->resize(rect.width(), rect.height()); widget->setPreferredSize(rect.width(), rect.height()); widget->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred)); //Have snippet determine its own location when NOT in anchor layout widget->setPos(rect.x(), rect.y()); } QWebElement parentElem; if (!(parentElem = findChromeParent(element)).isNull()) { snippet->setParentId(parentElem.attribute("id")); } //Set auto-layout attributes snippet->setAnchor(element.attribute("data-GinebraAnchor", "AnchorNone"), false); snippet->setAnchorOffset(element.attribute("data-GinebraAnchorOffset", "0").toInt()); snippet->setInitiallyVisible(element.attribute("data-GinebraVisible", "false") == "true"); snippet->setHidesContent(element.attribute("data-GinebraHidesContent", "false") == "true"); } return snippet; }
void lmcMessageLog::updateFileMessage(FileMode mode, FileOp op, QString fileId) { QString szMessage = getFileStatusMessage(mode, op); QWebFrame* frame = page()->mainFrame(); QWebElement document = frame->documentElement(); QWebElement body = document.findFirst("body"); QString selector = "span#"; QString tempId = (mode == FM_Send) ? "send" : "receive"; tempId.append(fileId); selector.append(tempId); QWebElement span = body.findFirst(selector); span.setPlainText(szMessage); // update the entry in message log for(int index = 0; index < messageLog.count(); index++) { SingleMessage msg = messageLog.at(index); if(tempId.compare(msg.id) == 0) { XmlMessage xmlMessage = msg.message; xmlMessage.removeData(XN_FILEOP); xmlMessage.addData(XN_FILEOP, FileOpNames[op]); msg.message = xmlMessage; break; } } }
/** * @fn gitreportLoaded */ void GitreportModule::gitreportLoaded(const bool state) { if (debug) qDebug() << "[GitreportModule]" << "[gitreportLoaded]"; if (debug) qDebug() << "[GitreportModule]" << "[gitreportLoaded]" << ":" << "State" << state; if (state) { webView->setHidden(!debug); // captcha QWebElement document = webView->page()->mainFrame()->documentElement(); QWebElement captchaImg = document.findFirst(QString("input#captcha_key")); QString captchaUrl = QString(dynamic[QString("CAPTCHA_URL")]) + captchaImg.attribute(QString("value")); QNetworkRequest request(captchaUrl); manager.get(request); disconnect(&manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(setCaptcha(QNetworkReply *))); connect(&manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(setCaptcha(QNetworkReply *))); } else {
FightBox MWBotWin::getGroupResult() { FightBox res; QWebElement elm; QString str; elm = frm->findFirstElement("form#fightGroupForm h3 div.group2"); str = elm.toPlainText(); res.enemy.name = str.split("(").first().trimmed(); res.enemy.type = elm.findFirst("i").attribute("class"); res.enemy.level = -1; res.result = str.contains("(0/") ? 1 : 0; res.items = getGroupResultMain(); elm = frm->findFirstElement("td.log div.result div.button div.c"); if (!elm.isNull()) { clickElement(elm); } res.items.append(getDuelResultExtra()); return res; }
static void parseDelayClass(const QWebElement &element, StationScheduleItem &item) { if (!element.isNull()) { QWebElement image = element.findFirst("img"); if (!image.isNull()) { int delayClass = 42; QString imageName = image.attribute("src"); if (!imageName.isEmpty()) { QRegExp delayClassRegexp("pallinoRit([0-9])\\.png"); int pos = delayClassRegexp.indexIn(imageName); qDebug() << "regexp matched at pos:" << pos << "match:" << delayClassRegexp.cap(0); delayClass = (pos >= 0) ? delayClassRegexp.cap(1).toInt() : 0; } item.setDelayClass(delayClass); } else { qDebug() << "img not found"; } } else { qDebug() << "div.bloccotreno not found"; } }
void WelcomePageWidget::updateRecentFilesContainer(const QString &id, const QStringList &files, const QString &message) { static const QString divTemplate = "<div id=\"%1\" class=\"recent_items_content\">%2</div>"; static const QString linkTemplate = "<a class=\"recentLink\" href=\"#\" onclick=\"ugene.openFile('%1')\" title=\"%1\">- %2</a>"; QWebElement doc = page()->mainFrame()->documentElement(); QWebElement recentFilesDiv = doc.findFirst("#" + id); SAFE_POINT(!recentFilesDiv.isNull(), "No recent files container", ); recentFilesDiv.removeAllChildren(); QStringList links; foreach (const QString &file, files.mid(0, MAX_RECENT)) { if (file.isEmpty()) { continue; } links << linkTemplate.arg(file).arg(QFileInfo(file).fileName()); } QString result = message; if (!links.isEmpty()) { result = links.join("\n"); } recentFilesDiv.setOuterXml(divTemplate.arg(id).arg(result)); }
void DisplayWidget::appendText(const QString &output) { _scrollToBottom = true; // Maximum Amount of Permitted Characters/Sections _currentCharacterCount += output.size(); if (_currentCharacterCount >= _maxCharacterCount) { _currentCharacterCount = 0; if (_currentSection >= _maxSections) _currentSection = 0; else _currentSection++; // Replace/Blank Section #ifdef USE_JQUERY QString code = QString("$('.section:first').appendTo('.container').html('%1').show();").arg(output); qDebug() << "* Blanking Section:" << code; #endif } else { // Append text to Section QTime t; t.start(); #ifdef USE_JQUERY QString code = QString("$('.section').append('%1');").arg(output); page()->mainFrame()->evaluateJavaScript(code); #else QWebElement doc = page()->mainFrame()->documentElement(); doc.findFirst(".section").appendInside(output); #endif //qDebug() << "* Displaying (" << t.elapsed() << "ms):" << output; } //scrollToBottom(); }
static QList<GagObject> parseGAG(const QWebElementCollection &entryItems) { QList<GagObject> gagList; foreach (const QWebElement &element, entryItems) { GagObject gag; gag.setId(element.attribute("data-entry-id")); gag.setUrl(element.attribute("data-entry-url")); gag.setVotesCount(element.attribute("data-entry-votes").toInt()); gag.setCommentsCount(element.attribute("data-entry-comments").toInt()); gag.setTitle(element.findFirst("a").toPlainText().trimmed()); gag.setIsLiked(!element.findFirst("ul.badge-item-vote-container.up").isNull()); gag.setIsDisliked(!element.findFirst("ul.badge-item-vote-container.down").isNull()); const QWebElement postContainer = element.findFirst("div.post-container"); if (!postContainer.findFirst("div.nsfw-post").isNull()) { gag.setIsNSFW(true); } else if (!postContainer.findFirst("div.badge-animated-container-animated").isNull()) { gag.setIsGIF(true); gag.setImageUrl(postContainer.findFirst("img.badge-item-img").attribute("src")); gag.setGifImageUrl(postContainer.findFirst("div.badge-animated-container-animated").attribute("data-image")); } else if (postContainer.hasClass("with-button")) { //not full pic, we'll need to go deeper for the full lenght image const QUrl regularImgUrl = postContainer.findFirst("img.badge-item-img").attribute("src"); const QUrl imgUrl = QString("%1/photo/%2_700b.jpg").arg(regularImgUrl.toString(QUrl::RemovePath)).arg(gag.id()); Q_ASSERT(imgUrl.isValid()); gag.setFullImageUrl(imgUrl); gag.setImageUrl(regularImgUrl); gag.setIsPartialImage(true); } else { gag.setImageUrl(postContainer.findFirst("img.badge-item-img").attribute("src")); } gagList.append(gag); }
void StationScheduleModel::parse(const QByteArray &htmlReply, const QUrl &baseUrl) { Q_UNUSED(baseUrl); qDebug() << "--- start of query result --- cut here ------"; qDebug() << QString::fromUtf8(htmlReply.constData()); qDebug() << "--- end of query result ----- cut here ------"; emit layoutAboutToBeChanged(); beginResetModel(); QWebPage page; page.mainFrame()->setContent(htmlReply, "text/html", baseUrl); QWebElement doc = page.mainFrame()->documentElement(); // Check if the page is reporting an error before parsing it QWebElement errorElement = doc.findFirst("span.errore"); if (!errorElement.isNull()) { m_departureSchedules.clear(); m_arrivalSchedules.clear(); QString errorText = errorElement.toPlainText().trimmed(); if (errorText == "localita' non trovata") { setError(tr("Unknown station")); } else { setError(tr("Unknown error")); } qDebug() << "error:" << error(); return; } // Find the first div QWebElement current = doc.findFirst("div"); qDebug() << "skipping to the departures"; // Skip to the first div of class corpocentrale, which contains the first // departure-related contents while (!current.classes().contains("corpocentrale")) { current = current.nextSibling(); qDebug() << "skipping to the next element"; if (current.isNull()) break; } // Mark every div as a departure class element; the next corpocentrale // marks the start of the arrivals section qDebug() << "marking departures"; do { if (current.classes().contains("bloccorisultato")) { StationScheduleItem schedule = parseResult(current); if (schedule.isValid()) { m_departureSchedules << schedule; } } current = current.nextSibling(); qDebug() << "marking as departures"; if (current.isNull()) break; } while (!current.classes().contains("corpocentrale")); // Mark everything as an arrival, until reaching the footer while (!current.classes().contains("footer")) { if (current.classes().contains("bloccorisultato")) { StationScheduleItem schedule = parseResult(current); if (schedule.isValid()) { m_arrivalSchedules << schedule; } } current = current.nextSibling(); qDebug() << "marking as arrival"; if (current.isNull()) break; } endResetModel(); emit layoutChanged(); }
// This function is called to display a file request message on chat box void lmcMessageLog::appendFileMessage(MessageType type, QString* lpszUserName, XmlMessage* pMessage, bool bReload) { QString htmlMsg; QString caption; QString fileId = pMessage->data(XN_FILEID); QString tempId; QString szStatus; htmlMsg = themeData.reqMsg; htmlMsg.replace("%iconpath%", "qrc"IDR_FILEMSG); FileOp fileOp = (FileOp) Helper::indexOf(FileOpNames, FO_Max, pMessage->data(XN_FILEOP)); if(type == MT_LocalFile) { tempId = "send" + fileId; caption = tr("Sending '%1' to %2."); htmlMsg.replace("%sender%", caption.arg(pMessage->data(XN_FILENAME), *lpszUserName)); htmlMsg.replace("%message%", ""); htmlMsg.replace("%fileid%", tempId); switch(fileOp) { case FO_Request: sendFileMap.insert(fileId, *pMessage); pMessage->addData(XN_TEMPID, tempId); htmlMsg.replace("%links%", "<a href='lmc://filecancel/" + fileId + "'>" + tr("Cancel") + "</a>"); break; case FO_Cancel: case FO_Accept: case FO_Decline: szStatus = getFileStatusMessage(FM_Send, fileOp); htmlMsg.replace("%links%", szStatus); break; default: return; break; } } else if(type == MT_File) { tempId = "receive" + fileId; if(autoFile) { caption = tr("%1 is sending you a file:"); htmlMsg.replace("%sender%", caption.arg(*lpszUserName)); htmlMsg.replace("%message%", pMessage->data(XN_FILENAME) + " (" + Helper::formatSize(pMessage->data(XN_FILESIZE).toLongLong()) + ")"); htmlMsg.replace("%fileid%", ""); } else { caption = tr("%1 sends you a file:"); htmlMsg.replace("%sender%", caption.arg(*lpszUserName)); htmlMsg.replace("%message%", pMessage->data(XN_FILENAME) + " (" + Helper::formatSize(pMessage->data(XN_FILESIZE).toLongLong()) + ")"); htmlMsg.replace("%fileid%", tempId); } switch(fileOp) { case FO_Request: receiveFileMap.insert(fileId, *pMessage); pMessage->addData(XN_TEMPID, tempId); if(autoFile) { htmlMsg.replace("%links%", tr("File has been accepted automatically.")); } else { htmlMsg.replace("%links%", "<a href='lmc://fileaccept/" + fileId + "'>" + tr("Accept") + "</a> " + "<a href='lmc://filedecline/" + fileId + "'>" + tr("Decline") + "</a>"); } if(autoFile && !bReload) fileOperation(fileId, "fileaccept"); break; case FO_Cancel: case FO_Accept: case FO_Decline: szStatus = getFileStatusMessage(FM_Receive, fileOp); htmlMsg.replace("%links%", szStatus); break; default: return; break; } } QWebFrame* frame = page()->mainFrame(); QWebElement document = frame->documentElement(); QWebElement body = document.findFirst("body"); body.appendInside(htmlMsg); }
void lmcMessageLog::appendMessageLog(QString *lpszHtml) { QWebFrame* frame = page()->mainFrame(); QWebElement document = frame->documentElement(); QWebElement body = document.findFirst("body"); body.appendInside(*lpszHtml); }
void CellmlAnnotationViewMetadataEditDetailsWidget::updateGui(iface::cellml_api::CellMLElement *pElement, const bool &pResetItemsGui) { // Keep track of the CellML element mElement = pElement; // Enable/disable our add term button, depending on whether the direct term // is already associated with the CellML element bool fileReadableAndWritableAndNoIssues = Core::FileManager::instance()->isReadableAndWritable(mCellmlFile->fileName()) && !mCellmlFile->issues().count(); bool termIsDirect = isDirectTerm(mTermValue->text()); if (termIsDirect) { QStringList termInformation = mTermValue->text().split("/"); if (mQualifierValue->currentIndex() < CellMLSupport::CellmlFileRdfTriple::LastBioQualifier) mAddTermButton->setEnabled( fileReadableAndWritableAndNoIssues && !mCellmlFile->rdfTriple(mElement, CellMLSupport::CellmlFileRdfTriple::BioQualifier(mQualifierValue->currentIndex()+1), termInformation[0], termInformation[1])); else mAddTermButton->setEnabled( fileReadableAndWritableAndNoIssues && !mCellmlFile->rdfTriple(mElement, CellMLSupport::CellmlFileRdfTriple::ModelQualifier(mQualifierValue->currentIndex()-CellMLSupport::CellmlFileRdfTriple::LastBioQualifier+1), termInformation[0], termInformation[1])); } else { mAddTermButton->setEnabled(false); } // Reset our items' GUI, if needed and if our busy widget is not already // visible // Note: the reason for checking whether our busy widget is visible is that // we come here every time the user modifies the term to look up. So, // we don't want to call updateItemsGui() for no reasons. Indeed, if // we were then our busy widget would get 'reset' every time, which // doesn't look nice... if ( (pResetItemsGui && !mParent->parent()->isBusyWidgetVisible()) || termIsDirect) { updateItemsGui(CellmlAnnotationViewMetadataEditDetailsItems(), !termIsDirect, QString()); } // Enable or disable the add buttons for our retrieved terms, depending on // whether the file is un/locked and whether they are already associated // with the CellML element QWebElement documentElement = mOutputOntologicalTerms->page()->mainFrame()->documentElement(); foreach (const QString &itemInformationSha1, mItemInformationSha1s) { CellmlAnnotationViewMetadataEditDetailsItem item = mItemsMapping.value(itemInformationSha1); bool enabledButton; if (mQualifierValue->currentIndex() < CellMLSupport::CellmlFileRdfTriple::LastBioQualifier) enabledButton = fileReadableAndWritableAndNoIssues && !mCellmlFile->rdfTriple(mElement, CellMLSupport::CellmlFileRdfTriple::BioQualifier(mQualifierValue->currentIndex()+1), item.resource(), item.id()); else enabledButton = fileReadableAndWritableAndNoIssues && !mCellmlFile->rdfTriple(mElement, CellMLSupport::CellmlFileRdfTriple::ModelQualifier(mQualifierValue->currentIndex()-CellMLSupport::CellmlFileRdfTriple::LastBioQualifier+1), item.resource(), item.id()); if (enabledButton != mEnabledItems.value(itemInformationSha1)) { mEnabledItems.insert(itemInformationSha1, enabledButton); documentElement.findFirst(QString("td[id=button_%1]").arg(itemInformationSha1)).setStyleProperty("display", enabledButton?"table-cell":"none"); documentElement.findFirst(QString("td[id=disabledButton_%1]").arg(itemInformationSha1)).setStyleProperty("display", !enabledButton?"table-cell":"none"); } }
void CellmlAnnotationViewMetadataNormalViewDetailsWidget::genericLookUp(const QString &pRdfTripleInformation, const InformationType &pInformationType) { // Retrieve the RDF triple information QStringList rdfTripleInformation = pRdfTripleInformation.split("|"); QString qualifier = pRdfTripleInformation.isEmpty()?QString():rdfTripleInformation[0]; QString resource = pRdfTripleInformation.isEmpty()?QString():rdfTripleInformation[1]; QString id = pRdfTripleInformation.isEmpty()?QString():rdfTripleInformation[2]; // Keep track of the RDF triple information and type mRdfTripleInformation = pRdfTripleInformation; // (Un)highlight/(un)select our various RDF triple information static const QString Highlighted = "highlighted"; static const QString Selected = "selected"; QWebElement documentElement = mOutputOntologicalTerms->page()->mainFrame()->documentElement(); QString rdfTripleInformationSha1 = pRdfTripleInformation.isEmpty()?QString():Core::sha1(pRdfTripleInformation); if (rdfTripleInformationSha1.compare(mRdfTripleInformationSha1)) { if (!mRdfTripleInformationSha1.isEmpty()) { documentElement.findFirst(QString("tr[id=item_%1]").arg(mRdfTripleInformationSha1)).removeClass(Highlighted); if (mInformationType == Qualifier) documentElement.findFirst(QString("td[id=qualifier_%1]").arg(mRdfTripleInformationSha1)).removeClass(Selected); else if (mInformationType == Resource) documentElement.findFirst(QString("td[id=resource_%1]").arg(mRdfTripleInformationSha1)).removeClass(Selected); else if (mInformationType == Id) documentElement.findFirst(QString("td[id=id_%1]").arg(mRdfTripleInformationSha1)).removeClass(Selected); } if (!rdfTripleInformationSha1.isEmpty()) { documentElement.findFirst(QString("tr[id=item_%1]").arg(rdfTripleInformationSha1)).addClass(Highlighted); if (pInformationType == Qualifier) documentElement.findFirst(QString("td[id=qualifier_%1]").arg(rdfTripleInformationSha1)).addClass(Selected); else if (pInformationType == Resource) documentElement.findFirst(QString("td[id=resource_%1]").arg(rdfTripleInformationSha1)).addClass(Selected); else if (pInformationType == Id) documentElement.findFirst(QString("td[id=id_%1]").arg(rdfTripleInformationSha1)).addClass(Selected); } mRdfTripleInformationSha1 = rdfTripleInformationSha1; } else if (!rdfTripleInformationSha1.isEmpty()) { if (pInformationType == Qualifier) { documentElement.findFirst(QString("td[id=qualifier_%1]").arg(rdfTripleInformationSha1)).addClass(Selected); documentElement.findFirst(QString("td[id=resource_%1]").arg(rdfTripleInformationSha1)).removeClass(Selected); documentElement.findFirst(QString("td[id=id_%1]").arg(rdfTripleInformationSha1)).removeClass(Selected); } else if (pInformationType == Resource) { documentElement.findFirst(QString("td[id=qualifier_%1]").arg(rdfTripleInformationSha1)).removeClass(Selected); documentElement.findFirst(QString("td[id=resource_%1]").arg(rdfTripleInformationSha1)).addClass(Selected); documentElement.findFirst(QString("td[id=id_%1]").arg(rdfTripleInformationSha1)).removeClass(Selected); } else if (pInformationType == Id) { documentElement.findFirst(QString("td[id=qualifier_%1]").arg(rdfTripleInformationSha1)).removeClass(Selected); documentElement.findFirst(QString("td[id=resource_%1]").arg(rdfTripleInformationSha1)).removeClass(Selected); documentElement.findFirst(QString("td[id=id_%1]").arg(rdfTripleInformationSha1)).addClass(Selected); } } mInformationType = pInformationType; // Check whether we have something to look up // Note: there is nothing nothing do for Any... if (mLookUpRdfTripleInformation == First) mOutputOntologicalTerms->page()->triggerAction(QWebPage::MoveToStartOfDocument); else if (mLookUpRdfTripleInformation == Last) // Note #1: normally, we would use // mOutputOntologicalTerms->page()->triggerAction(QWebPage::MoveToEndOfDocument); // but this doesn't work... // Note #2: another option would be to use // QWebFrame *outputFrame = mOutputOntologicalTerms->page()->mainFrame(); // // outputFrame->setScrollBarValue(Qt::Vertical, outputFrame->scrollBarMaximum(Qt::Vertical)); // but this doesnt' get us exactly to the bottom of the page... QTimer::singleShot(1, this, SLOT(showLastRdfTriple())); else if (mLookUpRdfTripleInformation == No) return; // Let people know that we want to look something up switch (pInformationType) { case Qualifier: emit qualifierLookUpRequested(qualifier); break; case Resource: emit resourceLookUpRequested(resource); break; case Id: emit idLookUpRequested(resource, id); break; default: // None emit noLookUpRequested(); } }
void MWBotWin::atkRat() { QWebElement elm; setBusy(true); // go to page loadPath(QStringList() << "square" << "metro"); // select dark/normal rats elm = frm->findFirstElement("div.metro-branch div.metro-rats-light__dark-block"); if (!elm.isNull()) { log(trUtf8("Dark/Normal select"),"bug.png"); if (opt.ratk.dark) { elm = frm->findFirstElement("a.f[href='/metro/select/1/']"); } else { elm = frm->findFirstElement("a.f[href='/metro/select/0/']"); } elm = elm.findFirst("div.c"); if (elm.isNull()) { log(trUtf8("DEBUG: Rat selection error")); return; } clickElement(elm); } // check timer & atk rat int time = getRatTimer(); if (opt.ratk.ratlev > opt.ratk.maxlev) { elm = frm->findFirstElement("div#action-rat-fight div small small.dashedlink"); if (elm.isNull()) { time = 60; } else { time = elm.attribute("timer").toInt() + 60; } opt.ratk.time = QDateTime::currentDateTime().addSecs(time); opt.ratk.ratlev = 1; log(trUtf8("Хватит крыс. Ждём обвала. До обвала <b>%0</b> мин.").arg(time/60 + 1),"rat.png"); } else if (time < 1) { log(trUtf8("Уровень крысы: <b>%0</b>").arg(opt.ratk.ratlev),"rat.png"); restoreHP(); clickElement("div#action-rat-fight div.button-big div.c"); clickElement("div#welcome-rat button.button div.c"); if (opt.ratk.ratlev % 5 == 0) { groupFight(); } else { fightResult(); } getRatTimer(); } else { time += 30 + random() % 30; opt.ratk.time = QDateTime::currentDateTime().addSecs(time); log(trUtf8("До следующей крысы <b>%0</b> мин.").arg(time/60 + 1),"rat.png"); } // take tails prize elm = frm->findFirstElement("div.metro-branch table.collectbar td.actions button.button"); if (!elm.isNull()) { if (!elm.classes().contains("disabled")) { elm = elm.findFirst("div.c"); clickElement(elm); log(trUtf8("Получен приз за крысинные хвосты"),"rattail.png"); } } setBusy(false); }
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 MWBotWin::doTaxi() { if (curTime.date().dayOfWeek() != 1) return; if (opt.taxi.time > curTime) return; QWebElement elm; QWebElement sub; int time; int count; int loop; setBusy(true); loadPage("arbat"); // check taxi chest and take it elm = frm->findFirstElement("div.auto-bombila table.collectbar td.actions button.button"); if (elm.isNull()) { count = 0; } else { count = elm.classes().contains("disabled") ? 0 : 1; } if (count) { sub = elm.findFirst("div.c"); clickElement(sub); log(trUtf8("Забран сундук бомбилы"),"chest.png"); } // check taxi timer, send a car & charge it if it needs elm = frm->findFirstElement("div.auto-bombila table.process td#cooldown"); if (elm.styleProperty("display",QWebElement::ComputedStyle) == "none") { time = 0; } else { time = elm.attribute("timer").toInt(); } if (time != 0) { time += (30 + (random() % 30)); opt.taxi.time = curTime.addSecs(time); log(trUtf8("До следующей бомбилки %0 сек").arg(time),"taxi.png"); } else { do { loop = 0; elm= frm->findFirstElement("div.auto-bombila table.action button.ride-button span.f div.c"); clickElement(elm); elm = frm->findFirstElement("div.alert.alert-error h2#alert-title"); if (elm.isNull()) { elm = frm->findFirstElement("div.auto-bombila table.process td#cooldown"); time = elm.attribute("timer").toInt(); time += 30 + random() % 30; opt.taxi.time = curTime.addSecs(time); log(trUtf8("Авто отправлено бомбить. До следующего раза %0 сек").arg(time),"taxi.png"); } else { elm = frm->findFirstElement("div.alert.alert-error div.actions div.button div.c"); sub = elm.findFirst("span"); count = sub.toPlainText().remove("\"").toInt(); getFastRes(); if (sub.classes().contains("ruda")) { count = (info.ore >= count) ? 1 : 0; } else if (sub.classes().contains("oil")) { count = (info.oil >= count) ? 1 : 0; } else { count = 0; } if (count) { clickElement(elm); log(trUtf8("Машина заправлена"),"taxi.png"); loop = 1; } else { time = 15 * 60; opt.taxi.time = curTime.addSecs(time); log(trUtf8("Не хватает ресурсов для заправки. Ждём 15 мин"),"taxi.png"); } } } while (loop); } setBusy(false); }