bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut)
{
    Q_D(QNativeSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForRead(), false);
    Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForRead(),
                      QAbstractSocket::UnconnectedState, false);

    if (timedOut)
        *timedOut = false;

    QElapsedTimer timer;
    timer.start();
    while (msecs > timer.elapsed()) {
        // Servers with active connections are ready for reading
        if (!d->currentConnections.isEmpty())
            return true;

        // If we are a client, we are ready to read if our buffer has data
        QMutexLocker locker(&d->readMutex);
        if (!d->readBytes.atEnd())
            return true;

        // Nothing to do, wait for more events
        d->eventLoop.processEvents();
    }

    d->setError(QAbstractSocket::SocketTimeoutError,
                QNativeSocketEnginePrivate::TimeOutErrorString);

    if (timedOut)
        *timedOut = true;
    return false;
}
Exemple #2
0
void CameraOpenCV::startCapture()
{
    m_videoCap.open(m_devNum);
    std::cout << "Exposure: " << m_videoCap.get(CV_CAP_PROP_EXPOSURE) << std::endl;
    m_videoCap.set(CV_CAP_PROP_EXPOSURE, 10);
    std::cout << "Exposure: " << m_videoCap.get(CV_CAP_PROP_EXPOSURE) << std::endl;

    capturing = m_videoCap.isOpened();

    if (capturing)
    {
        cv::Mat frame, out;
        m_videoCap >> frame;
        QElapsedTimer timer;
        timer.start();
        m_grabTimeMS = 0;
        for (int i = 0; i < 30; ++i)
        {
            m_videoCap >> frame;
            m_grabTimeMS += timer.restart();
        }
        m_grabTimeMS /= 30;
        cout << "Measured grab time: " << m_grabTimeMS << endl;
        cv::cvtColor(frame, out, cv::COLOR_BGR2GRAY);
        m_bytes = out.step * out.rows;
    }
}
Exemple #3
0
void wait(int ms)
{
    Q_ASSERT(ms >= 0);

    if (ms == 0) {
        return;
    }

    QElapsedTimer timer;
    timer.start();

    if (ms <= 50) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, ms);
        sleep(qMax(ms - static_cast<int>(timer.elapsed()), 0));
    }
    else {
        int timeLeft;
        do {
            timeLeft = ms - timer.elapsed();
            if (timeLeft > 0) {
                QCoreApplication::processEvents(QEventLoop::AllEvents, timeLeft);
                sleep(10);
            }
        } while (!timer.hasExpired(ms));
    }
}
Exemple #4
0
/*!
    \reimp
*/
void QScrollBar::mousePressEvent(QMouseEvent *e)
{
    Q_D(QScrollBar);

    if (d->repeatActionTimer.isActive())
        d->stopRepeatAction();

    bool midButtonAbsPos = style()->styleHint(QStyle::SH_ScrollBar_MiddleClickAbsolutePosition,
                                             0, this);
    QStyleOptionSlider opt;
    initStyleOption(&opt);

    if (d->maximum == d->minimum // no range
        || (e->buttons() & (~e->button())) // another button was clicked before
        || !(e->button() == Qt::LeftButton || (midButtonAbsPos && e->button() == Qt::MidButton)))
        return;

    d->pressedControl = style()->hitTestComplexControl(QStyle::CC_ScrollBar, &opt, e->pos(), this);
    d->pointerOutsidePressedControl = false;

    QRect sr = style()->subControlRect(QStyle::CC_ScrollBar, &opt,
                                       QStyle::SC_ScrollBarSlider, this);
    QPoint click = e->pos();
    QPoint pressValue = click - sr.center() + sr.topLeft();
    d->pressValue = d->orientation == Qt::Horizontal ? d->pixelPosToRangeValue(pressValue.x()) :
        d->pixelPosToRangeValue(pressValue.y());
    if (d->pressedControl == QStyle::SC_ScrollBarSlider) {
        d->clickOffset = HORIZONTAL ? (click.x()-sr.x()) : (click.y()-sr.y());
        d->snapBackPosition = d->position;
    }

    if ((d->pressedControl == QStyle::SC_ScrollBarAddPage
          || d->pressedControl == QStyle::SC_ScrollBarSubPage)
        && ((midButtonAbsPos && e->button() == Qt::MidButton)
            || (style()->styleHint(QStyle::SH_ScrollBar_LeftClickAbsolutePosition, &opt, this)
                && e->button() == Qt::LeftButton))) {
        int sliderLength = HORIZONTAL ? sr.width() : sr.height();
        setSliderPosition(d->pixelPosToRangeValue((HORIZONTAL ? e->pos().x()
                                                              : e->pos().y()) - sliderLength / 2));
        d->pressedControl = QStyle::SC_ScrollBarSlider;
        d->clickOffset = sliderLength / 2;
    }
    const int initialDelay = 500; // default threshold
    QElapsedTimer time;
    time.start();
    d->activateControl(d->pressedControl, initialDelay);
    repaint(style()->subControlRect(QStyle::CC_ScrollBar, &opt, d->pressedControl, this));
    if (time.elapsed() >= initialDelay && d->repeatActionTimer.isActive()) {
        // It took more than 500ms (the initial timer delay) to process
        // the control activation and repaint(), we therefore need
        // to restart the timer in case we have a pending mouse release event;
        // otherwise we'll get a timer event right before the release event,
        // causing the repeat action to be invoked twice on a single mouse click.
        // 50ms is the default repeat time (see activateControl/setRepeatAction).
        d->repeatActionTimer.start(50, this);
    }
    if (d->pressedControl == QStyle::SC_ScrollBarSlider)
        setSliderDown(true);
}
Exemple #5
0
void TestQgsSvgCache::changeImage()
{
  bool inCache;
  QgsSvgCache cache;
  // no minimum time between checks
  cache.mFileModifiedCheckTimeout = 0;

  //copy an image to the temp folder
  QString tempImagePath = QDir::tempPath() + "/svg_cache.svg";

  QString originalImage = TEST_DATA_DIR + QStringLiteral( "/test_symbol_svg.svg" );
  if ( QFileInfo::exists( tempImagePath ) )
    QFile::remove( tempImagePath );
  QFile::copy( originalImage, tempImagePath );

  //render it through the cache
  QImage img = cache.svgAsImage( tempImagePath, 200, QColor( 0, 0, 0 ), QColor( 0, 0, 0 ), 1.0,
                                 1.0, inCache );
  QVERIFY( imageCheck( "svgcache_changed_before", img, 30 ) );

  // wait a second so that modified time is different
  QElapsedTimer t;
  t.start();
  while ( !t.hasExpired( 1000 ) )
  {}

  //replace the image in the temp folder
  QString newImage = TEST_DATA_DIR + QStringLiteral( "/test_symbol_svg2.svg" );
  QFile::remove( tempImagePath );
  QFile::copy( newImage, tempImagePath );

  //re-render it
  img = cache.svgAsImage( tempImagePath, 200, QColor( 0, 0, 0 ), QColor( 0, 0, 0 ), 1.0,
                          1.0, inCache );
  QVERIFY( imageCheck( "svgcache_changed_after", img, 30 ) );

  // repeat, with minimum time between checks
  QgsSvgCache cache2;
  QFile::remove( tempImagePath );
  QFile::copy( originalImage, tempImagePath );
  img = cache2.svgAsImage( tempImagePath, 200, QColor( 0, 0, 0 ), QColor( 0, 0, 0 ), 1.0,
                           1.0, inCache );
  QVERIFY( imageCheck( "svgcache_changed_before", img, 30 ) );

  // wait a second so that modified time is different
  t.restart();
  while ( !t.hasExpired( 1000 ) )
  {}

  //replace the image in the temp folder
  QFile::remove( tempImagePath );
  QFile::copy( newImage, tempImagePath );

  //re-render it - not enough time has elapsed between checks, so file modification time will NOT be rechecked and
  // existing cached image should be used
  img = cache2.svgAsImage( tempImagePath, 200, QColor( 0, 0, 0 ), QColor( 0, 0, 0 ), 1.0,
                           1.0, inCache );
  QVERIFY( imageCheck( "svgcache_changed_before", img, 30 ) );
}
void qAnimationDlg::preview()
{
	//we'll take the rendering time into account!
	QElapsedTimer timer;
	timer.start();

	setEnabled(false);

	//reset the interpolators and count the total number of frames
	int frameCount = countFrameAndResetInterpolators();

	//show progress dialog
	QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
	progressDialog.setWindowTitle("Preview");
	progressDialog.show();
	QApplication::processEvents();

	double fps = fpsSpinBox->value();
	
	int frameIndex = 0;
	for ( size_t i=0; i<m_videoSteps.size(); ++i )
	{
		VideoStepItem& currentVideoStep = m_videoSteps[i];

		//theoretical waiting time per frame
		qint64 delay_ms = static_cast<int>(1000 * currentVideoStep.duration_sec / fps);

		cc2DViewportObject currentParams;
		while ( currentVideoStep.interpolator.nextView( currentParams ) )
		{
			timer.restart();
			applyViewport ( &currentParams );
			qint64 dt_ms = timer.elapsed();

			progressDialog.setValue(++frameIndex);
			QApplication::processEvents();
			if (progressDialog.wasCanceled())
			{
				break;
			}

			//remaining time
			if (dt_ms < delay_ms)
			{
				int wait_ms = static_cast<int>(delay_ms - dt_ms);
#if defined(CC_WINDOWS)
				::Sleep( wait_ms );
#else
				usleep( wait_ms * 1000 );
#endif
			}
		}
	}

	//reset view
	onCurrentStepChanged( getCurrentStepIndex() );

	setEnabled(true);
}
void BleWindowsCaptureSource::run()
{
    // TODO make could select screen
    // QGuiApplication::screens();
    while (!m_stop) {
        QElapsedTimer elapsedTimer;
        elapsedTimer.start();

        QScreen *screen = QGuiApplication::primaryScreen();

        if (screen) {
            QPixmap pixmap = screen->grabWindow(m_wid, m_x, m_y, m_width, m_height);
#if 1
            // TODO to draw cursor to image
            QRect desktopRect = QRect(QPoint(0, 0), screen->size());
            if (desktopRect.contains(QCursor::pos())) {
                drawCursor(&pixmap);
            }
#endif
            QImage image = pixmap.toImage();

            m_modifyMutex.lock();           // Start lock

            BleImage be;
            be.width = image.width();
            be.height = image.height();

            int imageSize = be.width * be.height * 3;
            be.data = new char[imageSize];

            IplImage *oriImage = cvCreateImageHeader(cvSize(image.width(), image.height()), IPL_DEPTH_8U, 4);
            cvSetData(oriImage, image.bits(), image.bytesPerLine());

            IplImage *dstImage = cvCreateImageHeader(cvSize(image.width(), image.height()), IPL_DEPTH_8U, 3);
            cvSetData(dstImage, be.data, be.width * 3);

            cvCvtColor(oriImage, dstImage, CV_BGRA2BGR);

            be.dataSize = imageSize;
            be.format = BleImage_Format_BGR24;

            m_image = be;

            cvReleaseImageHeader(&oriImage);
            cvReleaseImageHeader(&dstImage);

            m_modifyMutex.unlock();        // End unlock
        }

        int elapsedMs = elapsedTimer.elapsed();
        int needSleepMs = m_interval - elapsedMs;
        if (needSleepMs < 0) {
            needSleepMs = 0;
        }
        msleep(needSleepMs);
    }

    log_trace("BleWindowsCaptureSource exit normally.");
}
void delay(unsigned int msecs)
{
	QElapsedTimer t;
	t.start();
	while ( t.elapsed() < msecs )
    {}
        //QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
void tst_QElapsedTimer::statics()
{
    qDebug() << "Clock type is" << QElapsedTimer::clockType();
    qDebug() << "Said clock is" << (QElapsedTimer::isMonotonic() ? "monotonic" : "not monotonic");
    QElapsedTimer t;
    t.start();
    qDebug() << "Current time is" << t.msecsSinceReference();
}
Exemple #10
0
 void toggleRunning() {
    if (timer.isActive())
       timer.stop();
    else {
       timer.start(10, this);
       el.start();
    }
 }
//![2]
void executeOperationsForTime(int ms)
{
    QElapsedTimer timer;
    timer.start();

    while (!timer.hasExpired(ms))
        slowOperation1();
}
double monotonicallyIncreasingTime()
{
    ASSERT(QElapsedTimer::isMonotonic());
    static QElapsedTimer timer;
    if (!timer.isValid())
        timer.start();
    return timer.nsecsElapsed() / 1.0e9;
}
Exemple #13
0
void Execut_window::waitTaskInfo(int tim)//延时ms
{
    QElapsedTimer t;
    t.start();
    while(t.elapsed()<tim)
    {
        QCoreApplication::processEvents();
    }
}
Exemple #14
0
void waitTaskInfo()
{
    QElapsedTimer t;
    t.start();
        while(t.elapsed()<300)
        {
            QCoreApplication::processEvents();
        }
}
Exemple #15
0
void tst_qnetworkconfiguration::bearerType()
{
    QNetworkConfigurationManager m;
    QList<QNetworkConfiguration> allConfs = m.allConfigurations();
    QElapsedTimer timer;
    for (int a = 0; a < allConfs.count(); a++) {
        timer.start();
        QNetworkConfiguration::BearerType type = allConfs.at(a).bearerType();
        qint64 elapsed = timer.elapsed();
        QString typeString;
        switch (type) {
        case QNetworkConfiguration::BearerUnknown:
            typeString = QLatin1String("Unknown");
            break;
        case QNetworkConfiguration::BearerEthernet:
            typeString = QLatin1String("Ethernet");
            break;
        case QNetworkConfiguration::BearerWLAN:
            typeString = QLatin1String("WLAN");
            break;
        case QNetworkConfiguration::Bearer2G:
            typeString = QLatin1String("2G");
            break;
        case QNetworkConfiguration::BearerCDMA2000:
            typeString = QLatin1String("CDMA2000");
            break;
        case QNetworkConfiguration::BearerWCDMA:
            typeString = QLatin1String("WCDMA");
            break;
        case QNetworkConfiguration::BearerHSPA:
            typeString = QLatin1String("HSPA");
            break;
        case QNetworkConfiguration::BearerBluetooth:
            typeString = QLatin1String("Bluetooth");
            break;
        case QNetworkConfiguration::BearerWiMAX:
            typeString = QLatin1String("WiMAX");
            break;
        case QNetworkConfiguration::BearerEVDO:
            typeString = QLatin1String("EVDO");
            break;
        case QNetworkConfiguration::BearerLTE:
            typeString = QLatin1String("LTE");
            break;
        default:
            typeString = "unknown bearer (?)";
        }

        const char *isDefault = (allConfs.at(a) == m.defaultConfiguration())
                ? "*DEFAULT*" : "";
        qDebug() << isDefault << "identifier:" << allConfs.at(a).identifier()
                 << "bearer type name:" << allConfs.at(a).bearerTypeName()
                 << "bearer type:" << type << "(" << typeString << ")"
                 << "elapsed:" << elapsed;
        QCOMPARE(allConfs.at(a).bearerTypeName(), typeString);
    }
}
Exemple #16
0
void PN532::sleep(quint16 msec)
{
    QElapsedTimer t;
    t.start();
    while(t.elapsed() < msec)
    {
        QCoreApplication::processEvents();
    }
}
Exemple #17
0
/*
 * use when update config,e.g. change wifi name or password or access point
*/
void Wifi::restartWifi()
{
    stopWifi();
    QElapsedTimer t;
    t.start();
    while(t.elapsed()<5000)
        QCoreApplication::processEvents();
    startWifi();
}
// the entry point for painting
int SceneXrender::paint(QRegion damage, ToplevelList toplevels)
{
    QElapsedTimer renderTimer;
    renderTimer.start();

    foreach (Toplevel * c, toplevels) {
        assert(windows.contains(c));
        stacking_order.append(windows[ c ]);
    }
/*------------------------------------------------------------------------------
|    OMX_CameraSurfaceElement::updatePaintNode
+-----------------------------------------------------------------------------*/
QSGNode* OMX_CameraSurfaceElement::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData*)
{
    QSGGeometryNode* node = 0;
    QSGGeometry* geometry = 0;

    if (!oldNode) {
        // Create the node.
        node = new QSGGeometryNode;
        geometry = new QSGGeometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4);
        geometry->setDrawingMode(GL_TRIANGLE_STRIP);
        node->setGeometry(geometry);
        node->setFlag(QSGNode::OwnsGeometry);

        // TODO: Who is freeing this?
        // TODO: I cannot know the texture size here.
        QSGOpaqueTextureMaterial* material = new QSGOpaqueTextureMaterial;
        m_sgtexture = new OMX_SGTexture(0, QSize(640, 480));
        material->setTexture(m_sgtexture);
        node->setMaterial(material);
        node->setFlag(QSGNode::OwnsMaterial);

        QtConcurrent::run(this, &OMX_CameraSurfaceElement::videoAcquire);
    }
    else {
        node = static_cast<QSGGeometryNode*>(oldNode);
        geometry = node->geometry();
        geometry->allocate(4);

        // Update texture in the node if needed.
        QSGOpaqueTextureMaterial* material = (QSGOpaqueTextureMaterial*)node->material();
        QElapsedTimer timer;
        timer.start();
        QSGTexture* texture = window()->createTextureFromImage(m_frame);
        LOG_VERBOSE(LOG_TAG, "Timer tex: %lld.", timer.elapsed());
        material->setTexture(texture);
        m_semAcquire.release();
#if 0
        if (m_texture != (GLuint)material->texture()->textureId()) {
            // TODO: Does setTextureId frees the prev texture?
            // TODO: I should the given the texture size.
            LOG_ERROR(LOG_TAG, "Updating texture to %u!", m_texture);
            material = new QSGOpaqueTextureMaterial;
            m_sgtexture->setTexture(m_texture, QSize(1920, 1080));
        }
#endif
    }

    // Create the vertices and map to texture.
    QRectF bounds = boundingRect();
    QSGGeometry::TexturedPoint2D* vertices = geometry->vertexDataAsTexturedPoint2D();
    vertices[0].set(bounds.x(), bounds.y() + bounds.height(), 0.0f, 0.0f);
    vertices[1].set(bounds.x() + bounds.width(), bounds.y() + bounds.height(), 1.0f, 0.0f);
    vertices[2].set(bounds.x(), bounds.y(), 0.0f, 1.0f);
    vertices[3].set(bounds.x() + bounds.width(), bounds.y(), 1.0f, 1.0f);
    return node;
}
Exemple #20
0
/**
 * @brief Network::step Orders a single evolution of the model.
 */
void Network::step()
{
    QElapsedTimer timer;
    timer.start();

    this->process();
    this->synthesize_traffic();

    this->last_evolution_time = timer.elapsed();
}
void AssignmentClientMonitor::simultaneousWaitOnChildren(int waitMsecs) {
    QElapsedTimer waitTimer;
    waitTimer.start();

    // loop as long as we still have processes around and we're inside the wait window
    while(_childProcesses.size() > 0 && !waitTimer.hasExpired(waitMsecs)) {
        // continue processing events so we can handle a process finishing up
        QCoreApplication::processEvents();
    }
}
Exemple #22
0
void Cam::newFrame() {
   timer.start();
   frame.fill(Qt::blue);
   QPainter p{&frame};
   p.setFont({"Helvetica", 48});
   p.setPen(Qt::white);
   p.drawText(frame.rect(), Qt::AlignCenter,
              QStringLiteral("Hello,\nWorld!\n%1").arg(
                 QTime::currentTime().toString(QStringLiteral("hh:mm:ss.zzz"))));
}
void QFESPIMB040SimpleCameraConfig::stop() {
    //qDebug()<<"stop";
    restartPreview=actStartStopPreview->isChecked();
    stopPreview();
    QElapsedTimer timer;
    timer.start();
    while (timer.elapsed()<150) {
        QApplication::processEvents();
    }
}
//![1]
void executeSlowOperations(int timeout)
{
    QElapsedTimer timer;
    timer.start();
    slowOperation1();

    int remainingTime = timeout - timer.elapsed();
    if (remainingTime > 0)
        slowOperation2(remainingTime);
}
void RemoteFileInfoGatherer::fetch(const QFileInfo &fileInfo, QElapsedTimer &base, bool &firstTime, QVector<QPair<QString, FileInfo> > &updatedFiles, const QString &path) {
    updatedFiles.append(QPair<QString, FileInfo>(fileInfo.fileName(), toFileInfo(fileInfo)));
    QElapsedTimer current;
    current.start();
    if ((firstTime && updatedFiles.count() > 100) || base.msecsTo(current) > 1000) {
        emit updates(path, updatedFiles);
        updatedFiles.clear();
        base = current;
        firstTime = false;
    }
}
ConsoleLineBuffer::ConsoleLineBuffer(HighlightingsModel* highlightingsModel)
    : QAbstractListModel()
    , highlightingsModel_(highlightingsModel)
    , logFile_(nullptr)
    , bInsertStarted_(false)
{
    clear();
    timer.start();

    connect(highlightingsModel_, &HighlightingsModel::highlightingChanged, this, &ConsoleLineBuffer::refreshHighlighting);
}
/*
    Get specific file info's, batch the files so update when we have 100
    items and every 200ms after that
 */
void RemoteFileInfoGatherer::getFileInfos(const QString &path, const QStringList &files)
{
    // List drives
    if (path.isEmpty()) {
#ifdef QT_BUILD_INTERNAL
        fetchedRoot.store(true);
#endif
        QFileInfoList infoList;
        if (files.isEmpty()) {
            infoList = QDir::drives();
        } else {
            infoList.reserve(files.count());
            for (const auto &file : files)
                infoList << QFileInfo(file);
        }
        for (int i = infoList.count() - 1; i >= 0; --i) {
            QString driveName = translateDriveName(infoList.at(i));
            QVector<QPair<QString,FileInfo> > updatedFiles;
            updatedFiles.append(QPair<QString,FileInfo>(driveName, toFileInfo(infoList.at(i))));
            emit updates(path, updatedFiles);
        }
        return;
    }

    QElapsedTimer base;
    base.start();
    QFileInfo fileInfo;
    bool firstTime = true;
    QVector<QPair<QString, FileInfo> > updatedFiles;
    QStringList filesToCheck = files;

    QStringList allFiles;
    if (files.isEmpty()) {
        QDirIterator dirIt(path, QDir::AllEntries | QDir::System | QDir::Hidden);
        while (!abort.load() && dirIt.hasNext()) {
            dirIt.next();
            fileInfo = dirIt.fileInfo();
            allFiles.append(fileInfo.fileName());
            fetch(fileInfo, base, firstTime, updatedFiles, path);
        }
    }
    if (!allFiles.isEmpty())
        emit newListOfFiles(path, allFiles);

    QStringList::const_iterator filesIt = filesToCheck.constBegin();
    while (!abort.load() && filesIt != filesToCheck.constEnd()) {
        fileInfo.setFile(path + QDir::separator() + *filesIt);
        ++filesIt;
        fetch(fileInfo, base, firstTime, updatedFiles, path);
    }
    if (!updatedFiles.isEmpty())
        emit updates(path, updatedFiles);
    emit directoryLoaded(path);
}
Exemple #28
0
QByteArray TcpSocket::handleData(QByteArray data, const QString &ip, quint16 port) {
    QTime time;
    time.start();

    QElapsedTimer tm;
    tm.start();
    while(tm.elapsed() < 100) {}

    data = ip.toUtf8() + ":" + QByteArray::number(port)+ " " + QTime::currentTime().toString().toUtf8() + " " + data ;
    return data;
}
void startExample()
{
//![0]
    QElapsedTimer timer;
    timer.start();

    slowOperation1();

    qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
//![0]
}
void tst_QElapsedTimer::validity()
{
    QElapsedTimer t;

    QVERIFY(!t.isValid()); // non-POD now, it should always start invalid

    t.start();
    QVERIFY(t.isValid());

    t.invalidate();
    QVERIFY(!t.isValid());
}