// ========================================================================== //
// Select.
// ========================================================================== //
bool AStatisticSqlTableController::select() {
    if(!_model) {
        QSqlDatabase db = QSqlDatabase::database(connectionName());
        if(!db.tables().contains(QStringLiteral("statistic"))) {
            const QString query_str
                = QLatin1String("CREATE TABLE IF NOT EXISTS statistic(" \
                    "statistic_id INTEGER PRIMARY KEY AUTOINCREMENT" \
                    ", username TEXT" \
                    ", period_from INTEGER" \
                    ", period_to INTEGER" \
                    ", is_extra_time INTEGER" \
                    ", is_synced INTEGER)");

            QSqlQuery query(db);
            if(!query.exec(query_str)) {
                QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "database")
                    .warning() << qPrintable(ASqlTableController::tr(
                        "Query: \"%1\"; error: \"%2\"")
                        .arg(query_str).arg(query.lastError().text()));

                return false;
            }
        }

        _model = new QSqlTableModel(this, db);
        _model->setTable(QStringLiteral("statistic"));
        _model->setEditStrategy(QSqlTableModel::OnManualSubmit);

        _model->setHeaderData(
            _model->fieldIndex(QStringLiteral("statistic_id"))
            , Qt::Horizontal, AStatisticSqlTableController::tr("ID"));

        _model->setHeaderData(
            _model->fieldIndex(QStringLiteral("username"))
            , Qt::Horizontal, AStatisticSqlTableController::tr("Username"));

        _model->setHeaderData(
            _model->fieldIndex(QStringLiteral("period_from"))
            , Qt::Horizontal, AStatisticSqlTableController::tr("Period from"));

        _model->setHeaderData(
            _model->fieldIndex(QStringLiteral("period_to"))
            , Qt::Horizontal, AStatisticSqlTableController::tr("Period to"));

        _model->setHeaderData(
            _model->fieldIndex(QStringLiteral("is_extra_time"))
            , Qt::Horizontal
            , AStatisticSqlTableController::tr("Is extra time"));

        _model->setHeaderData(
            _model->fieldIndex(QStringLiteral("is_synced"))
            , Qt::Horizontal, AStatisticSqlTableController::tr("Is synced"));

        _model->setSort(_model->fieldIndex(QStringLiteral("period_from"))
            , Qt::DescendingOrder);
    }

    return _model->select();
}
Ejemplo n.º 2
0
//! [1]
    void statusChanged(QDeclarativeComponent::Status status) {
        if (status == QDeclarativeComponent::Error) {
            foreach (const QDeclarativeError &error, component->errors()) {
                const QByteArray file = error.url().toEncoded();
                QMessageLogger(file.constData(), error.line(), 0).debug() << error.description();
            }
        }
Ejemplo n.º 3
0
LONG SCCall( const char *file, int line, const char *function, Func func, Args... args)
{
	LONG err = func(args...);
	if(SCard().isDebugEnabled())
		QMessageLogger(file, line, function, SCard().categoryName()).debug()
			<< function << hex << (unsigned long)err;
	return err;
}
Ejemplo n.º 4
0
bool PhantomJSHandler::OnConsoleMessage(CefRefPtr<CefBrowser> browser, const CefString& message, const CefString& source, int line)
{
  if (!canEmitSignal(browser)) {
    auto shortSource = QFileInfo(QString::fromStdString(source)).fileName().toStdString();
    QMessageLogger(shortSource.c_str(), line, 0).debug() << message;
  } else {
    emitSignal(browser, QStringLiteral("onConsoleMessage"),
        {QString::fromStdString(message), QString::fromStdString(source), line});
  }
  return true;
}
Ejemplo n.º 5
0
void MainWindow::updateUserDataComponent() {
    QJsonObject* userData = MainWindow::sharedData()->userData();

    ui->usernameLabel->setText(userData->value("name").toString());
    QJsonArray contracts = userData->value("contracts").toArray();

    QMessageLogger().debug() << " Contracts " <<QJsonDocument(contracts).toJson();
    for (int i=0; i< contracts.size(); i++) {
        QJsonObject contract = contracts[i].toObject();
        QString strContract = contract.value("buyer").toString() + " - " + contract.value("title").toString();
        ui->contractsCombo->addItem(strContract, contract.value("id").toInt());
    }
}
Ejemplo n.º 6
0
void QQmlAspectEnginePrivate::_q_continueExecute()
{
    Q_Q(QQmlAspectEngine);

    QObject::disconnect(m_component, SIGNAL(statusChanged(QQmlComponent::Status)),
                        q, SLOT(_q_continueExecute()));

    if (m_component->isError()) {
        const auto errors = m_component->errors();
        for (const QQmlError &error : errors) {
            QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), 0).warning()
                << error;
        }
        emit q->statusChanged(q->status());
        return;
    }

    QObject* obj = m_component->create();

    if (m_component->isError()) {
        const auto errors = m_component->errors();
        for (const QQmlError &error : errors) {
            QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), 0).warning()
                << error;
        }
        emit q->statusChanged(q->status());
        return;
    }

    // Let users know we have loaded the QML file, and the scene has been instantiated.
    // This gives a chance to manipulate the scene before passing it over to the
    // aspect engine. Useful for convenience window classes to set up cameras and surfaces
    // on the framegraph and event sources for the input aspect etc.
    emit q->sceneCreated(obj);
    m_aspectEngine->setRootEntity(QEntityPtr(qobject_cast<QEntity *>(obj)));
    emit q->statusChanged(q->status());
}
Ejemplo n.º 7
0
void HomeWindow::setSource(const QUrl &source)
{
    d->errors.clear();
    if (d->root) {
        delete d->root;
        d->root = 0;
    }

    QQmlComponent component(d->context->engine(), source);
    if (component.isError()) {
        d->errors = component.errors();
        foreach (const QQmlError &error, d->errors) {
            QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), 0).warning()
                    << error;
        }
        return;
    }
Ejemplo n.º 8
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    isLogin = false;
    isTracking = false;
    timeOffset = 0;
    nextSnapTime = 0;
    isUploadingCache = false;

    createActions();
    createTrayIcon();
    ui->setupUi(this);
    ui->contractsCombo->view()->setTextElideMode(Qt::ElideRight);
    ui->contractsCombo->view()->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

    // Network Manager Config
    networkManager = new MNetworkManager(this);
    connect(networkManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(handleNetworkData(QNetworkReply*)));
    // Timer Config
    timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(trackEvent()));

    activities = new QJsonObject();

    // ---------- Windows ----------
    library = new QLibrary ("WawTracker.dll");
    if (library->load()) {
        RegisterHook = (RegisterHookProc)library->resolve("RegisterHook");
        UnregisterHook = (UnregisterHookProc)library->resolve("UnregisterHook");
        GetKeyStrokeCount = (GetKeyStrokeCountProc)library->resolve("GetKeyStrokeCount");
        GetMouseClickCount = (GetMouseClickCountProc)library->resolve("GetMouseClickCount");
    } else {
        QMessageLogger().debug() << library->errorString();
    }
    // ---------- ~Windows ----------

    QDir dir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
    if (!dir.exists()) {
        dir.mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
    }
}
Ejemplo n.º 9
0
void log::logt(const QString & s)
{
	QDateTime now = QDateTime::currentDateTimeUtc();
	QString s1 = now.toString("yyyy-MM-dd-HH-mm-ss ") + s;
#ifndef NDEBUG
	QMessageLogger(__FILE__, __LINE__, 0).debug() << s1;
#endif
	s1 +=  + "\n";
	QFile ff(PathHelper::Instance()->LogPfn());
	if (ff.open(QIODevice::Append))
	{
		ff.write(s1.toLatin1());
		ff.flush();
		ff.close();
	}

	Scr_Logs::Instance()->Log(s1);
}
Ejemplo n.º 10
0
void MainWindow::uploadCacheData() {
    QSettings settings("WawJob", "WawTracker");
    settings.beginGroup("cache");
    QStringList caches = settings.childGroups();
    if (caches.size() > 0) {
        QString timestamp = caches.first();
        settings.beginGroup(timestamp);
        QString imagePath = settings.value("imagePath").toString();

        QByteArray jwt = settings.value("jwt").toByteArray();
        QJsonObject params = QJsonDocument::fromJson(QByteArray::fromBase64(jwt.split('.').at(1))).object();
        params["token"] = MainWindow::sharedData()->token();
        QMessageLogger().debug() << params;
        isUploadingCache = true;
        networkManager->sendJWT(TIMELOG_API_URL, params, "post", imagePath, (quint32)timestamp.toLong())->setObjectName("timelog_cache");
        settings.endGroup();
    } else {
        isUploadingCache = false;
    }
    settings.endGroup();
}
Ejemplo n.º 11
0
void BotIrcDiceParser::readData()
{
    qDebug() << "Reply";
    QString readLine= m_socket->readLine();

    if(readLine.startsWith("!"))
        readLine= readLine.remove(0, 1);

    if(readLine.contains("!"))
    {
        // qDebug()<< "in /dice";
        QString dice= ".*PRIVMSG.*!(.*)";
        QRegExp exp(dice);
        exp.indexIn(readLine);

        QStringList list= exp.capturedTexts();
        qDebug() << list;
        if(list.size() == 2)
        {
            QString cmd= list[1];
            if(!cmd.isEmpty())
            {
                cmd= cmd.simplified();
                QString result= startDiceParsing(cmd, true);
                if(!result.isEmpty())
                {
                    QString msg("PRIVMSG #RolisteamOfficial :%1 \r\n");
                    m_socket->write(msg.arg(result).toLatin1());
                }
            }
        }
        else
        {
            return;
        }
        //
    }
    else if(readLine.contains("PING :"))
    {
        QString dice= "PING :(.*)";
        QRegExp exp(dice);
        exp.indexIn(readLine);
        QStringList list= exp.capturedTexts();
        if(list.size() == 2)
        {
            QString resp= "PONG :" + list[1];

            m_socket->write(resp.toLatin1());
        }
    }
    if(readLine.contains(QLatin1String("Found your hostname")))
    {
        authentificationProcess();
    }
    if(readLine.contains(QLatin1String("msg NickServ identify")))
    {
        setRegisterName();
    }
    // Add to ouput
    // ui->m_output->append(readLine.trimmed());
    QMessageLogger().debug() << readLine.trimmed();
    // Next data??
    if(m_socket->canReadLine())
        readData();
}
Ejemplo n.º 12
0
void MainWindow::trackEvent() {
    double timestamp = MainWindow::sharedData()->timestamp;
    timeOffset += 60;
    int kCount = 0, mCount = 0;

    GetKeyStrokeCount = (GetKeyStrokeCountProc)library->resolve("GetKeyStrokeCount");
    if (GetKeyStrokeCount) {
        kCount = GetKeyStrokeCount();
    }

    GetMouseClickCount = (GetMouseClickCountProc)library->resolve("GetMouseClickCount");
    if (GetMouseClickCount) {
        mCount = GetMouseClickCount();
    }

    QDateTime datetime;
    datetime.setMSecsSinceEpoch((timestamp + timeOffset) * 1000);
    QString key = datetime.time().toString("hh:mm");

    QJsonObject act;
    act["k"] = kCount; act["m"] = mCount;
    activities->insert(key, act);

    if (timeOffset >= nextSnapTime ){
        QScreen *screen = QGuiApplication::primaryScreen();
        if (screen)
            originalPixmap = screen->grabWindow(0);
        ui->screenshotLabel->setPixmap(originalPixmap.scaled(ui->screenshotLabel->size(),
                                                             Qt::KeepAspectRatio,
                                                             Qt::SmoothTransformation));

        quint32 synctime = (timestamp + timeOffset);
        QString synctime_str = QString("%1").arg(synctime);
        QString filename = QCryptographicHash::hash(synctime_str.toUtf8(), QCryptographicHash::Md5).toHex() + ".png";
        QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/" + filename;

        QFile data("logging.txt");
        if (data.open(QFile::WriteOnly | QFile::Append)) {
            QTextStream out(&data);
            out << "Save Image:" << path <<"\n";
        }

        if (!originalPixmap.save(path, "PNG")) {
            QFile data("logging.txt");
            if (data.open(QFile::WriteOnly | QFile::Append)) {
                QTextStream out(&data);
                out << "Fail to save Image";
            }
        }

        QJsonObject params, logs, snapshot;
        snapshot["contract"] = currentContractId;
        snapshot["comment"] = ui->commentText->toPlainText();
        snapshot["active_window"] = "Test";
        snapshot["activities"] = *activities;

        logs.insert(QString("%1").arg(synctime), snapshot);
        params["token"] = MainWindow::sharedData()->token();
        params["logs"] = logs;

        networkManager->sendJWT(TIMELOG_API_URL, params, "post", path, synctime)->setObjectName("timelog");

        QDateTime datetime;
        datetime.setMSecsSinceEpoch((quint64)synctime * 1000);
        QMessageLogger().debug() << " Take Snapshot - " <<datetime.toString();
        QMessageLogger().debug() << QJsonDocument(*activities).toJson();
        int mins = datetime.time().minute();
        quint32 offset = (((mins / 10) + 1) * 10 + (qrand() % 9)) - mins;
        nextSnapTime = timeOffset + (offset * 60);
//        nextSnapTime = timeOffset + 60;

        QStringList keys = activities->keys();
        for (int i=0; i<keys.count(); i++) {
            activities->remove(keys.at(i));
        }
    }
}
Ejemplo n.º 13
0
void MainWindow::handleNetworkData(QNetworkReply *networkReply) {
    if (!networkReply->error()) {
        QByteArray response(networkReply->readAll());
        QJsonDocument jsonDoc = QJsonDocument::fromJson(response);

        QJsonObject result = jsonDoc.object();
        QMessageLogger().debug() <<networkReply->objectName();
        if (networkReply->objectName() == "logout") {
            if (result.value("error").toBool(true)) {
                QMessageBox msgBox;
                msgBox.setText(result["error"].toString());
                msgBox.exec();
                QMessageLogger().debug() << response;
            }
        } else if (networkReply->objectName() == "sync") {
            if (result.value("time") != QJsonValue::Undefined) {
                MainWindow::sharedData()->timestamp = (quint32)result.value("time").toDouble();
                timer->start(60000);
            } else {
                if (result.value("error") != QJsonValue::Undefined) {
                    QMessageBox msgBox;
                    msgBox.setText(result["error"].toString());
                    msgBox.exec();
                    QMessageLogger().debug() << response;
                }

                ui->trackBtn->setText("Start");
                isTracking = false;
                this->updateActionsStatus();
                ui->contractsCombo->setEnabled(true);
            }
        } else if (networkReply->objectName() == "timelog") {
            QJsonObject status = result.value("status").toObject();
            QStringList list = status.keys();
            bool success = false;
            int errorCode = 0;
            for (int i=0; i<list.count(); i++) {
                QString key = list.value(i);
                QJsonObject snap = status.value(key).toObject();
                if (snap.value("error").toInt() == 0) {
                    success = true;
                } else {
                    errorCode = snap.value("error").toInt();
                }
            }

            if (success || (errorCode == 2)) {
                trayIcon->showMessage("Screenshot", "Just uploaded screenshot and logs of keyboard and mouse.",QSystemTrayIcon::Information, 5000);
                QString imagePath = networkReply->property("imagePath").toString();
                QFile file(imagePath);
                file.remove();
                if (!isUploadingCache)
                    uploadCacheData();
            } else {
                quint32 timestamp = (quint32)networkReply->property("timestamp").toDouble();
                QString imagePath = networkReply->property("imagePath").toString();
                QByteArray jwt = networkReply->request().rawHeader("JWT");

                QSettings settings("WawJob", "WawTracker");
                settings.setValue("cache/" + QString("%1").arg(timestamp) + "/imagePath", imagePath);
                settings.setValue("cache/" + QString("%1").arg(timestamp) + "/jwt", jwt);
            }
            QFile data("logging.txt");
            if (data.open(QFile::WriteOnly | QFile::Append)) {
                QTextStream out(&data);
                out << response;
            }
            QMessageLogger().debug() << response;
        } else if (networkReply->objectName() == "timelog_cache") {
            QMessageLogger().debug() << response;
            QJsonObject status = result.value("status").toObject();
            QStringList list = status.keys();
            bool success = false;
            int errorCode = 0;
            for (int i=0; i<list.count(); i++) {
                QString key = list.value(i);
                QJsonObject snap = status.value(key).toObject();
                if (snap.value("error").toInt() == 0) {
                    success = true;
                } else {
                    errorCode = snap.value("error").toInt();
                }
            }

            if (success || (errorCode == 2)) {
                QString imagePath = networkReply->property("imagePath").toString();
                QFile file(imagePath);
                file.remove();

                QString timestamp = networkReply->property("timestamp").toString();
                QSettings settings("WawJob", "WawTracker");
                settings.remove("cache/"+timestamp);

                uploadCacheData();
            } else {
                isUploadingCache = false;
            }
        }
    } else {
        if (networkReply->objectName() == "sync") {
            stopTrack();
        } else if (networkReply->objectName() == "timelog") {
            quint32 timestamp = (quint32)networkReply->property("timestamp").toDouble();
            QString imagePath = networkReply->property("imagePath").toString();
            QByteArray jwt = networkReply->request().rawHeader("JWT");

            QSettings settings("WawJob", "WawTracker");
            settings.setValue("cache/" + QString("%1").arg(timestamp) + "/imagePath", imagePath);
            settings.setValue("cache/" + QString("%1").arg(timestamp) + "/jwt", jwt);
        }else if (networkReply->objectName() == "timelog_cache") {
            isUploadingCache = false;
        }else {
            QMessageBox msgBox;
            msgBox.setText(networkReply->errorString());
            msgBox.exec();
        }
        QMessageLogger().debug() <<networkReply->objectName() << networkReply->errorString();
        QFile data("logging.txt");
        if (data.open(QFile::WriteOnly | QFile::Append)) {
            QTextStream out(&data);
            out <<networkReply->objectName() << networkReply->errorString();
        }

    }

    networkReply->deleteLater();
}
Ejemplo n.º 14
0
// ========================================================================== //
// Run.
// ========================================================================== //
void ACaptureThread::run() {
    _mutex.lock();
    const QString dev_fmt_name = _dev_fmt_name;
    _mutex.unlock();

    AVInputFormat *av_inp_fmt = NULL;
    if(!dev_fmt_name.isEmpty()) {
        av_inp_fmt = av_find_input_format(dev_fmt_name.toLatin1());
        if(!av_inp_fmt) {
            QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
                << qPrintable(ACaptureThread::tr("Unable to find input video" \
                    " format \"%1\"!").arg(dev_fmt_name));

            QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

            return;
        }
    }

    _mutex.lock();
    const QString dev_name = _dev_name;
    _mutex.unlock();

    AVFormatContext *av_fmt_ctx = NULL;
    if(avformat_open_input(&av_fmt_ctx, dev_name.toLatin1()
        , av_inp_fmt, NULL) < 0) {

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Unable to open video" \
                " device \"%1\"!").arg(dev_name));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    if(avformat_find_stream_info(av_fmt_ctx, NULL) < 0) {
        avformat_close_input(&av_fmt_ctx);

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Unable to find video stream!"));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    int vid_strm_idx = -1;
    for(int i = 0, n = av_fmt_ctx->nb_streams; i < n; ++i) {
        if(av_fmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
            vid_strm_idx = i; break;
        }
    }

    if(vid_strm_idx == -1) {
        avformat_close_input(&av_fmt_ctx);

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Unable to find video stream!"));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    AVStream *av_vid_strm = av_fmt_ctx->streams[vid_strm_idx];

    AVCodec *av_dec = avcodec_find_decoder(av_vid_strm->codec->codec_id);
    if(!av_dec) {
        avformat_close_input(&av_fmt_ctx);

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Unable to find video decoder!"));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    if(avcodec_open2(av_vid_strm->codec, av_dec, NULL) < 0) {
        avformat_close_input(&av_fmt_ctx);

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Unable to open video decoder!"));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    AVCodecContext *av_dec_ctx = av_vid_strm->codec;

    SwsContext *av_sws_ctx
        = sws_getCachedContext(NULL
            , av_dec_ctx->width, av_dec_ctx->height, av_dec_ctx->pix_fmt
            , av_dec_ctx->width, av_dec_ctx->height, AV_PIX_FMT_RGB24
            , SWS_FAST_BILINEAR, NULL, NULL, NULL);

    if(!av_sws_ctx) {
        sws_freeContext(av_sws_ctx);
        avcodec_close(av_vid_strm->codec);
        avformat_close_input(&av_fmt_ctx);

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Unable to open cached context!"));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    AVFrame *av_cap_frm = av_frame_alloc();
    av_cap_frm->format = AV_PIX_FMT_RGB24;
    av_cap_frm->width  = av_dec_ctx->width;
    av_cap_frm->height = av_dec_ctx->height;
    if(av_frame_get_buffer(av_cap_frm, 32) < 0) {
        av_frame_free(&av_cap_frm);
        sws_freeContext(av_sws_ctx);
        avcodec_close(av_vid_strm->codec);
        avformat_close_input(&av_fmt_ctx);

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Unable to open capture frame!"));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    AVFrame *av_vid_frm = av_frame_alloc();

    _mutex.lock();
    const QString det_fname = _det_fname;
    _mutex.unlock();

    QTemporaryFile *dst_file = QTemporaryFile::createNativeFile(det_fname);
    if(!dst_file) {
        av_frame_free(&av_vid_frm);
        av_frame_free(&av_cap_frm);
        sws_freeContext(av_sws_ctx);
        avcodec_close(av_vid_strm->codec);
        avformat_close_input(&av_fmt_ctx);

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Can not create temporary file!"));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    const QString dst_fname = QDir::toNativeSeparators(dst_file->fileName());

    cv::CascadeClassifier classifier;
    if(!classifier.load(dst_fname.toStdString())) {
        av_frame_free(&av_vid_frm);
        av_frame_free(&av_cap_frm);
        sws_freeContext(av_sws_ctx);
        avcodec_close(av_vid_strm->codec);
        avformat_close_input(&av_fmt_ctx);

        delete dst_file;

        QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "video").warning()
            << qPrintable(ACaptureThread::tr("Load classifier failed!"));

        QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

        return;
    }

    delete dst_file;

    cv::Mat acc_mat, src_mat
        = cv::Mat::zeros(av_dec_ctx->height, av_dec_ctx->width, CV_8UC3);

    AVPacket av_pkt;
    while(av_read_frame(av_fmt_ctx, &av_pkt) >= 0
        && !isInterruptionRequested()) {

        int pkt_rdy = -1;
        if(avcodec_decode_video2(av_dec_ctx, av_vid_frm
            , &pkt_rdy, &av_pkt) < 0) {

            QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, "app").warning()
                << qPrintable(ACaptureThread::tr("Capturing failed!"));

            QMetaObject::invokeMethod(this, "failed", Qt::QueuedConnection);

            break;
        }

        if(!pkt_rdy) {av_free_packet(&av_pkt); continue;}

        sws_scale(av_sws_ctx
            , av_vid_frm->data, av_vid_frm->linesize, 0, av_vid_frm->height
            , av_cap_frm->data, av_cap_frm->linesize);

        for(int y = 0, rows = av_dec_ctx->height; y < rows; ++y) {
            for(int x = 0, cols = av_dec_ctx->width; x < cols; ++x) {
                cv::Vec3b &d = src_mat.at<cv::Vec3b>(y,x);
                d[0] = av_cap_frm->data[0][y*av_cap_frm->linesize[0]+x*3+0];
                d[1] = av_cap_frm->data[0][y*av_cap_frm->linesize[0]+x*3+1];
                d[2] = av_cap_frm->data[0][y*av_cap_frm->linesize[0]+x*3+2];
            }
        }

        av_free_packet(&av_pkt);

        cv::Mat gry_mat;
        cv::cvtColor(src_mat, gry_mat, cv::COLOR_RGB2GRAY);

        if(acc_mat.rows != gry_mat.rows || acc_mat.cols != gry_mat.cols)
            acc_mat = cv::Mat(gry_mat.size(), CV_64F);

        cv::accumulateWeighted(gry_mat, acc_mat, 0.75);
        cv::convertScaleAbs(acc_mat, gry_mat);

        _mutex.lock();
        const int det_min = _det_min;
        const int det_max = _det_max;
        _mutex.unlock();

        const int hrz_min = gry_mat.cols * det_min / 100;
        const int vrt_min = gry_mat.rows * det_min / 100;
        const int hrz_max = gry_mat.cols * det_max / 100;
        const int vrt_max = gry_mat.rows * det_max / 100;

        std::vector<cv::Rect> rois;
        classifier.detectMultiScale(gry_mat, rois, 1.1, 3, 0
            , cv::Size(hrz_min,vrt_min), cv::Size(hrz_max,vrt_max));

        if(isHiddenCapture()) {
            QMetaObject::invokeMethod(this, "captured", Qt::QueuedConnection);

        } else {
            QImage img(src_mat.data, src_mat.cols, src_mat.rows
                , src_mat.step, QImage::Format_RGB888);

            img = img.convertToFormat(QImage::Format_ARGB32_Premultiplied);

            QMetaObject::invokeMethod(this, "captured"
                , Qt::QueuedConnection, Q_ARG(QImage,img));
        }

        if(rois.size() > 0) {
            if(isHiddenDetect()) {
                const cv::Rect &roi = rois.at(0);
                QMetaObject::invokeMethod(this, "detected"
                    , Qt::QueuedConnection
                    , Q_ARG(QRect,QRect(roi.x,roi.y,roi.width,roi.height)));

            } else {
                cv::Mat roi_mat = src_mat(rois.at(0));

                QImage img(roi_mat.data, roi_mat.cols, roi_mat.rows
                    , roi_mat.step, QImage::Format_RGB888);

                img = img.convertToFormat(QImage::Format_ARGB32_Premultiplied);

                QMetaObject::invokeMethod(this, "detected"
                    , Qt::QueuedConnection, Q_ARG(QImage,img));
            }
        }
    }

    av_frame_free(&av_vid_frm);
    av_frame_free(&av_cap_frm);
    sws_freeContext(av_sws_ctx);
    avcodec_close(av_vid_strm->codec);
    avformat_close_input(&av_fmt_ctx);

    if(!isHiddenCapture()) {
        QMetaObject::invokeMethod(this, "captured"
            , Qt::QueuedConnection, Q_ARG(QImage,QImage()));
    }
}
Ejemplo n.º 15
0
QDebug PhDebug::debug(const char *fileName, int lineNumber, const char *functionName, int messageLogLevel)
{
	instance()->_currentLogLevel = messageLogLevel;
	return QMessageLogger(fileName, lineNumber, functionName).debug();
}
Ejemplo n.º 16
0
QDebug PhDebug::error(const char *fileName, int lineNumber, const char *functionName)
{
	instance()->_currentLogLevel = 0;
	return QMessageLogger(fileName, lineNumber, functionName).critical();
}