bool SafeApiFactory::authUser(QString login, QString password)
{
    QEventLoop loop;
    auto api = new SafeApi(this->host);
    bool success;

    connect(api, &SafeApi::authUserComplete, [&](ulong id, QString user_id){
        qDebug() << "Authentication complete (user id:" << user_id << ")";
        this->sharedState = api->state();
        this->m_login = login;
        this->password = password;
        success = true;
        loop.exit();
    });
    connect(api, &SafeApi::errorRaised, [&](ulong id, quint16 code, QString text){
        this->sharedState.clear();
        api = NULL;
        qWarning() << "Authentication error:" << text;
        loop.exit();
    });

    api->authUser(login, password);
    loop.exec();
    return success;
}
TCmdButton waitForProjectorsStateOrCancel(QList<ProjectorQuery*> &pqList, TProjState stateWaitFor)
{
    QMap<int, QString> projStateName;
    projStateName[onState] = "On";
    projStateName[offState] = "Off";
    projStateName[coolingState] = "Cooling";
    projStateName[warmUpState] = "WarmUp";

    extern CommandController cmdCtl;
    QEventLoop el;

    QMetaObject::Connection m_conn1, m_conn2;
    m_conn1 = QObject::connect(&cmdCtl, &CommandController::buttonCancel, [&el]() { el.exit(cmdButtonCancel); });

    TCmdButton ret;
    foreach (ProjectorQuery* pq, pqList) {
        TProjState ps = pq->getState();
        if(ps == stateWaitFor){
            ret = cmdFinished;
            qInfo() << "proj" << pq->ip << "in state"<< projStateName[ps] <<". Nothing to do.";
        }
        else{
            qInfo() << "proj" << pq->ip << "in state"<< projStateName[ps] <<". Changing state.";
            if(stateWaitFor == offState)
                pq->off();
            else if(stateWaitFor == onState)
                pq->on();
        }
    }
Exemple #3
0
QPair<bool, QByteArray> blockDownloadExtractData(QNetworkReply & reply) {
    QEventLoop pause;
    QObject::connect(&reply, &QNetworkReply::finished, [&pause]() {
        pause.exit();
    });

    QProgressDialog progress("Network Operation…", "Abort", 0, 100, state->mainWindow);
    progress.setModal(true);
    QObject::connect(&progress, &QProgressDialog::canceled, &reply, &QNetworkReply::abort);
    auto processProgress = [&progress](qint64 bytesReceived, qint64 bytesTotal){
        progress.setRange(0, bytesTotal);
        progress.setValue(bytesReceived);
    };
    QObject::connect(&reply, &QNetworkReply::downloadProgress, processProgress);
    QObject::connect(&reply, &QNetworkReply::uploadProgress, processProgress);
    QTimer::singleShot(400, &progress, &QProgressDialog::show);

    pause.exec();

    if (reply.error() != QNetworkReply::NoError) {
        qDebug() << reply.errorString();
    }
    reply.deleteLater();
    return {reply.error() == QNetworkReply::NoError, reply.readAll()};
}
Exemple #4
0
/*!
    Tells the thread's event loop to exit with a return code.

    After calling this function, the thread leaves the event loop and
    returns from the call to QEventLoop::exec(). The
    QEventLoop::exec() function returns \a returnCode.

    By convention, a \a returnCode of 0 means success, any non-zero value
    indicates an error.

    Note that unlike the C library function of the same name, this
    function \e does return to the caller -- it is event processing
    that stops.

    This function does nothing if the thread does not have an event
    loop.

    \sa quit() QEventLoop
*/
void QThread::exit(int returnCode)
{
    Q_D(QThread);
    QMutexLocker locker(&d->mutex);
    d->data->quitNow = true;
    for (int i = 0; i < d->data->eventLoops.size(); ++i) {
        QEventLoop *eventLoop = d->data->eventLoops.at(i);
        eventLoop->exit(returnCode);
    }
}
TCmdButton waitForTimeoutOrCancelCmd(int secTimeout)
{
    extern CommandController cmdCtl;

    QEventLoop el;

    QMetaObject::Connection m_conn1, m_conn2;
    m_conn1 = QObject::connect(&cmdCtl, &CommandController::buttonCancel, [&el]() { el.exit(cmdButtonCancel); });

    QTimer timer;
    timer.setSingleShot(true);
    timer.setInterval(secTimeout * 1000);
    m_conn2 = QObject::connect(&timer, &QTimer::timeout, [&el]() { el.exit(cmdTimeout); });
    timer.start();

    TCmdButton ret = (TCmdButton)el.exec();

    QObject::disconnect(m_conn1);
    QObject::disconnect(m_conn2);

    return ret;
}
Exemple #6
0
/* exit from url loop */
void url_exit(void)
{
    QEventLoop loop;
    loop.exit();

    foreach (QSocketNotifier *notifier, gReadNotifiers) {
        delete notifier;
    }
    foreach (QSocketNotifier *notifier, gWriteNotifiers) {
        delete notifier;
    }
    QApplication::quit();
}
Exemple #7
0
std::pair<int, int> Network::checkOnlineMags(const QUrl & url) {
    int lowestAvailableMag = NUM_MAG_DATASETS;
    int highestAvailableMag = 0;
    int maxMagCount = int_log(NUM_MAG_DATASETS) + 1;

    QProgressDialog progress("Network Operation…", "Abort", 0, 100, state->mainWindow);
    progress.setModal(true);
    std::vector<qint64> bytesReceivedAll(maxMagCount);
    std::vector<qint64> bytesTotalAll(maxMagCount);
    std::vector<std::unique_ptr<QNetworkReply>> replies(maxMagCount);
    QTimer::singleShot(400, &progress, &QProgressDialog::show);

    QEventLoop pause;
    for (int currMag = 1; currMag <= NUM_MAG_DATASETS; currMag *= 2) {
        QUrl magUrl = url;
        magUrl.setPath(QString("%1/mag%2/knossos.conf").arg(url.path()).arg(currMag));
        auto * replyPtr = manager.get(QNetworkRequest{magUrl});
        replies[int_log(currMag)] = decltype(replies)::value_type{replyPtr};
        QObject::connect(replyPtr, &QNetworkReply::finished, [magUrl, &pause, &maxMagCount, currMag, replyPtr, &lowestAvailableMag, &highestAvailableMag]() {
            auto & reply = *replyPtr;
            if (reply.error() == QNetworkReply::NoError) {
                lowestAvailableMag = std::min(lowestAvailableMag, currMag);
                highestAvailableMag = std::max(highestAvailableMag, currMag);
            }
            if (--maxMagCount == 0) {
                pause.exit();
            }
        });
        auto processProgress = [&progress, currMag, &bytesReceivedAll, &bytesTotalAll](qint64 bytesReceived, qint64 bytesTotal){
            bytesReceivedAll[int_log(currMag)] = bytesReceived;
            bytesTotalAll[int_log(currMag)] = bytesTotal;
            const auto received = std::accumulate(std::begin(bytesReceivedAll), std::end(bytesReceivedAll), qint64{0});
            const auto total = std::accumulate(std::begin(bytesTotalAll), std::end(bytesTotalAll), qint64{0});
            progress.setRange(0, total);
            progress.setValue(received);
        };
        QObject::connect(replyPtr, &QNetworkReply::downloadProgress, processProgress);
        QObject::connect(replyPtr, &QNetworkReply::uploadProgress, processProgress);
        QObject::connect(&progress, &QProgressDialog::canceled, replyPtr, &QNetworkReply::abort);
    }

    pause.exec();

    if (lowestAvailableMag > highestAvailableMag) {
        throw std::runtime_error{"no mags detected"};
    }

    return {lowestAvailableMag, highestAvailableMag};
}
Exemple #8
0
void behaviorOfPendingTimeouts()
{
  QEventLoop eventloop;
  TpTimer timer;
  timer.setPassedTimepointsTrigger(true); /* allow startToTimePoint(tp) to take timepoints lying in the past
                                             - these will cause the timer to fire immediately */
  
  timer.startToTimePoint(TpTimer::nowTimePoint()-1000); // timepoint in the past
  QObject::connect(&timer, &QTimer::timeout,
                   [&]() {                     
                     std::cout << "millisSinceEpoch planned-alarm: " << timer.expiryTimePoint() << "\n"
                                  "actual:                         "
                               << TpTimer::nowTimePoint() << '\n' << std::endl;
                     eventloop.exit();
                   });
  eventloop.exec();
}
TCmdButton waitForBut1CmdOrBut2Cmd()
{
    extern CommandController cmdCtl;

    QEventLoop el;

    QMetaObject::Connection m_conn1, m_conn2;
    m_conn1 = QObject::connect(&cmdCtl, &CommandController::button1, [&el]() { el.exit(cmdButton1); });
    m_conn2 = QObject::connect(&cmdCtl, &CommandController::button2, [&el]() { el.exit(cmdButton2); });

    TCmdButton ret = (TCmdButton)el.exec();

    QObject::disconnect(m_conn1);
    QObject::disconnect(m_conn2);

    return ret;
}
void OsmAnd::OnlineMapRasterTileProvider_P::replyFinishedHandler( QNetworkReply* reply, const std::shared_ptr<TileEntry>& tileEntry, QEventLoop& eventLoop, QNetworkAccessManager& networkAccessManager )
{
    auto redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if(!redirectUrl.isEmpty())
    {
        reply->deleteLater();

        QNetworkRequest newRequest;
        newRequest.setUrl(redirectUrl);
        newRequest.setRawHeader("User-Agent", "OsmAnd Core");
        auto newReply = networkAccessManager.get(newRequest);
        QObject::connect(newReply, &QNetworkReply::finished,
            [this, newReply, tileEntry, &eventLoop, &networkAccessManager]()
        {
            replyFinishedHandler(newReply, tileEntry, eventLoop, networkAccessManager);
        });
        return;
    }

    // Remove current download and process pending queue
    {
        QMutexLocker scopedLock(&_currentDownloadsCounterMutex);
        _currentDownloadsCount--;
    }

    // Enqueue other downloads
    _tiles.obtainTileEntries(nullptr, [this](const std::shared_ptr<TileEntry>& entry, bool& cancel) -> bool
    {
        if(_currentDownloadsCount == owner->maxConcurrentDownloads)
        {
            cancel = true;
            return false;
        }

        if(entry->state == TileState::EnqueuedForDownload)
            obtainTileDeffered(entry);

        return false;
    });

    handleNetworkReply(reply, tileEntry);

    reply->deleteLater();
    eventLoop.exit();
}
//0 - exit on finish, 1 - exit on cancel
TCmdButton waitForFinishPlayOrCancel(QProcess *videoPlayer)
{
    //extern QProcess videoPlayer;
    extern CommandController cmdCtl;

    QEventLoop el;

    QMetaObject::Connection m_conn1, m_conn2;

    m_conn1 = QObject::connect(&cmdCtl, &CommandController::buttonCancel, [&el]() { el.exit(cmdButtonCancel); });
    //QObject::connect((QObject*)&videoPlayer, &QProcess::finished, [&el]() { el.exit(0); });
    m_conn2 = QObject::connect(videoPlayer, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
          [&el](int exitCode, QProcess::ExitStatus exitStatus){ qDebug() <<"video finished signal exit code " << exitCode; el.exit(cmdFinished); });

    TCmdButton ret = (TCmdButton)el.exec();

    QObject::disconnect(m_conn1);
    QObject::disconnect(m_conn2);

    return ret;
}
/**
 * Take the WebKit HTML and transform it into ENML
 * */
void EnmlFormatter::rebuildNoteEnml() {
    QLOG_INFO() << "===== Rebuilding note ENML";
    QLOG_DEBUG_FILE("fmt-html-input.html", getContent());

    // list of referenced LIDs
    resources.clear();


    tidyHtml(HtmlCleanupMode::Tidy);
    if (isFormattingError()) {
        QLOG_ERROR() << "Got no output from tidy - cleanup failed";
        return;
    }
    removeHtmlHeader();

    //QRegularExpression reInput("<!--.*-->");
    //content.replace(reInput, "");


    content.prepend(DEFAULT_HTML_HEAD);
    content.prepend(DEFAULT_HTML_TYPE);

    // Tidy puts this in place, but we don't really need it.
    content.replace("<form>", "");
    content.replace("</form>", "");

    content = fixEncryptionTags(content);

    QLOG_DEBUG_FILE("fmt-pre-dt-check.html", getContent());
    if (global.guiAvailable) {
        QWebPage page;
        QEventLoop loop;
        page.mainFrame()->setContent(getContentBytes());
        QObject::connect(&page, SIGNAL(loadFinished(bool)), &loop, SLOT(quit()));
        loop.exit();

        QWebElement elementRoot = page.mainFrame()->documentElement();
        QStringList tags = findAllTags(elementRoot);

        for (int i = 0; i < tags.size(); i++) {
            QString tag = tags[i];
            QLOG_DEBUG() << "== processing tag " << tag;

            QWebElementCollection anchors = page.mainFrame()->findAllElements(tag);
                foreach(QWebElement
                            element, anchors) {
                    QString tagname = element.tagName().toLower();
                    if (tagname == "input") {
                        fixInputNode(element);
                    } else if (tagname == "a") {
                        fixANode(element);
                    } else if (tagname == "object") {
                        fixObjectNode(element);
                    } else if (tagname == "img") {
                        fixImgNode(element);
                    } else if (tagname == "span") {
                        fixSpanNode(element);
                    } else if (tagname == "div") {
                        fixDivNode(element);
                    } else if (tagname == "pre") {
                        fixPreNode(element);
                    } else if (!isElementValid(element)) {
                        QLOG_DEBUG() << "Removing element: " << tagname;
                        element.removeFromDocument();
                    }
                }
        }
Exemple #13
0
/*!
 * \brief Handle doc translation
 */
void Translator::fileTranslate(QString filePath)
{

    QDir outputDocDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    QString dirName = tr("Apertium Translated Documents");
    outputDocDir.mkdir(dirName);
    if (!outputDocDir.cd(dirName)) {
        emit fileTranslateRejected();
        return;
    }
    QFileInfo fileInfo(filePath);
#ifdef Q_OS_LINUX
    auto multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
                       QVariant("form-data; filename=\"" + fileInfo.fileName() + "\"; name=\"file\""));
    auto file = new QFile(filePath);
    if (!file->open(QIODevice::ReadOnly)) {
        emit fileTranslateRejected();
        return;
    }
    filePart.setBodyDevice(file);
    file->setParent(multiPart);
    multiPart->append(filePart);

    QUrlQuery query;
    query.addQueryItem("langpair",
                       parent->getCurrentSourceLang() + "|" + parent->getCurrentTargetLang());
    QUrl url("http://localhost:2737/translateDoc?");
    QNetworkRequest request(QUrl(url.url() + query.query()));
    QNetworkAccessManager mngr;
    QEventLoop loop;
    QNetworkReply *reply = mngr.post(request, multiPart);
    connect(reply, &QNetworkReply::finished, [&]() {
        loop.exit();
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << reply->errorString();
            emit fileTranslateRejected();
            return;
        }
        QFile outDoc(outputDocDir.absoluteFilePath(fileInfo.baseName() + "_" +
                                                   parent->getCurrentSourceLang()
                                                   + "-" + parent->getCurrentTargetLang() + "." + fileInfo.completeSuffix()));
        if (!outDoc.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
            emit fileTranslateRejected();
            reply->deleteLater();
            return;
        }
        outDoc.write(reply->readAll());
        outDoc.close();
        emit fileTranslated(outDoc.fileName());
        reply->deleteLater();
    });
    loop.exec();
#else
    if (fileInfo.suffix() == "txt")
        translateTxt(filePath, outputDocDir);
    else if (fileInfo.suffix() == "docx")
        translateDocx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "pptx")
        translatePptx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "xlsx")
        translateXlsx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "html")
        translateHtml(filePath, outputDocDir);
    else if (fileInfo.suffix() == "rtf")
        translateRtf(filePath, outputDocDir);
#endif
}
void WebCoreSynchronousLoader::didFinishLoading(ResourceHandle*, double)
{
    if (!m_replyFinished)
        m_eventLoop.exit();
}
void WebCoreSynchronousLoader::didFail(ResourceHandle*, const ResourceError& error)
{
    m_error = error;
    if (!m_replyFinished)
        m_eventLoop.exit();
}
void WebCoreSynchronousLoader::didFail(ResourceHandle*, const ResourceError& error)
{
    m_error = error;
    m_eventLoop.exit();
}
void WebCoreSynchronousLoader::didFinishLoading(ResourceHandle*)
{
    m_eventLoop.exit();
}