Exemple #1
0
    DEBUGER_EXPORT int debuger_exec(int (*fn)(int, char**), void (*exit_fn)()) {
        if (fn) {
            debuger_thread_runner runner(fn, app_argc, app_argv);
            debuger_thread_actor actor;
            QThread child;

            QObject::connect(&actor, SIGNAL(start()), &runner, SLOT(start()));
            QObject::connect(&runner, SIGNAL(finished()), &actor, SLOT(finished()));

            runner.moveToThread(&child);
            child.start();
            actor.start();

            int ret = debuger::app->exec();

            if (exit_fn)
                exit_fn();

            // ==== child join
            child.quit();
            child.wait();
            return ret;
        }

        return debuger::app->exec();
    }
Exemple #2
0
void ArchiveCA_Plugin::handleResults(indexes indexNew, int nbVal, QVector<double> TimerN, QVector<double> YValsN, QString backend)
{
    //qDebug() << "in CA handle results" << nbVal << TimerN.count();

    if(nbVal > 0) {
        TimerN.resize(nbVal);
        YValsN.resize(nbVal);
        archiverCommon->updateCartesian(nbVal, indexNew, TimerN, YValsN, backend);
        TimerN.resize(0);
        YValsN.resize(0);
    }

    QList<QString> removeKeys;
    removeKeys.clear();

    QMap<QString, QThread *>::iterator j = listOfThreads.find(indexNew.key);
    while (j !=listOfThreads.end() && j.key() == indexNew.key) {
        QThread *tmpThread = (QThread*) j.value();
        tmpThread->quit();
        removeKeys.append(indexNew.key);
        //qDebug() << tmpThread << "ca quit";
        ++j;
    }

    for(int i=0; i< removeKeys.count(); i++) {
        listOfThreads.remove(removeKeys.at(i));
    }
}
Exemple #3
0
void tst_QDjango::databaseThreaded()
{
    if (QDjango::database().databaseName() == QLatin1String(":memory:"))
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        QSKIP("Threaded test cannot work with in-memory SQLite database.");
#else
        QSKIP("Threaded test cannot work with in-memory SQLite database.", SkipAll);
#endif

    QDjangoQuerySet<Author> qs;
    QCOMPARE(qs.count(), 0);

    QEventLoop loop;
    Worker worker;
    QThread workerThread;

    // fire up worker
    worker.moveToThread(&workerThread);
    connect(&worker, SIGNAL(done()), &loop, SLOT(quit()));

    workerThread.start();
    QTimer::singleShot(0, &worker, SLOT(doIt()));
    loop.exec();

    // check database
    QCOMPARE(qs.count(), 1);

    // stop thread
    workerThread.quit();
    workerThread.wait();
}
Exemple #4
0
int main(int argc, char* argv[])
{
#ifdef Q_WS_X11
  QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

  QGuiApplication app(argc,argv);
  SettingsRef     settings;
  MainWindow      *window;
  int             result;

  app.setOrganizationName("libosmscout");
  app.setOrganizationDomain("libosmscout.sf.net");
  app.setApplicationName("OSMScout");

  settings=new Settings();

  //qRegisterMetaType<RenderMapRequest>();
  qRegisterMetaType<DatabaseLoadedResponse>();

  qmlRegisterType<MapWidget>("net.sf.libosmscout.map", 1, 0, "Map");
  qmlRegisterType<Location>("net.sf.libosmscout.map", 1, 0, "Location");
  qmlRegisterType<LocationListModel>("net.sf.libosmscout.map", 1, 0, "LocationListModel");
  qmlRegisterType<RouteStep>("net.sf.libosmscout.map", 1, 0, "RouteStep");
  qmlRegisterType<RoutingListModel>("net.sf.libosmscout.map", 1, 0, "RoutingListModel");

  qmlRegisterSingletonType<Theme>("net.sf.libosmscout.map", 1, 0, "Theme", ThemeProvider);

  QThread thread;

  if (!DBThread::InitializeInstance()) {
    std::cerr << "Cannot initialize DBThread" << std::endl;
  }

  DBThread* dbThread=DBThread::GetInstance();

  window=new MainWindow(settings,
                        dbThread);
  window->resize(480,800);
  window->setResizeMode(QQuickView::SizeRootObjectToView);

  dbThread->connect(&thread, SIGNAL(started()), SLOT(Initialize()));
  dbThread->connect(&thread, SIGNAL(finished()), SLOT(Finalize()));

  dbThread->moveToThread(&thread);
  thread.start();

  window->show();

  result=app.exec();

  delete window;

  thread.quit();
  thread.wait();

  DBThread::FreeInstance();

  return result;
}
void LedDeviceWrapper::stopDeviceThread()
{
	_ledDevice->switchOff();
	QThread* oldThread = _ledDevice->thread();
	delete _ledDevice; // fast desctruction
	oldThread->quit(); // non blocking
}
Exemple #6
0
bool CuteNews::quit() {
    if (m_connection) {
        m_connection->close();
    }
    
    QThread *dbThread = DBConnection::asynchronousThread();

    if ((dbThread) && (dbThread != QThread::currentThread())) {
        if (dbThread->isRunning()) {
            Logger::log("CuteNews::quit(). Shutting down the database thread", Logger::LowVerbosity);
            connect(dbThread, SIGNAL(finished()), this, SLOT(quit()), Qt::UniqueConnection);
            dbThread->quit();
            return false;
        }
    }
        
    const int expiryDays = Settings::readArticleExpiry();
    
    if (expiryDays > -1) {
        uint expiryDate = QDateTime::currentDateTime().toTime_t();

        if (expiryDays > 0) {
            expiryDate -= expiryDays * 86400;
        }
        
        Logger::log("CuteNews::quit(). Deleting read articles older than "
                    + QDateTime::fromTime_t(expiryDate).toString(Qt::ISODate));
        DBConnection(false).deleteExpiredArticles(expiryDate);
    }
    
    Transfers::instance()->save();
    Logger::log("CuteNews::quit(). Quitting the application", Logger::LowVerbosity);
    QCoreApplication::quit();
    return true;
}
Exemple #7
0
int ServerApp::exec()
{
    QThread appThread;

    m_impl->application.moveToThread(&appThread);
    appThread.start();

    m_impl->window.show();

    // ... and run
    // Qt event loop must be in the main thread
    boost::thread orbThread(
        boost::bind(&CORBA::ORB::run, m_impl->orb.in()));

    int res = m_impl->app.exec();

    appThread.quit();
    appThread.wait();

    m_impl->orb->shutdown(1);

    orbThread.join();

    delete m_impl;
    m_impl = NULL;

    return res;
}
int main(int argc, char* argv[])
{
#ifdef Q_WS_X11
    QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

    QGuiApplication app(argc,argv);
    SettingsRef     settings;
    MainWindow      *window;
    int             result;

    app.setOrganizationName("libosmscout");
    app.setOrganizationDomain("libosmscout.sf.net");
    app.setApplicationName("OSMScout");

    settings=std::make_shared<Settings>();

    qRegisterMetaType<RenderMapRequest>();
    qRegisterMetaType<DatabaseLoadedResponse>();
    qRegisterMetaType<osmscout::TileRef>();

    qmlRegisterType<MapWidget>("net.sf.libosmscout.map", 1, 0, "Map");
    qmlRegisterType<Location>("net.sf.libosmscout.map", 1, 0, "Location");
    qmlRegisterType<LocationListModel>("net.sf.libosmscout.map", 1, 0, "LocationListModel");
    qmlRegisterType<FileIO, 1>("FileIO", 1, 0, "FileIO");

    QThread thread;

    if (!DBThread::InitializeInstance(/*settings*/)) {
        std::cerr << "Cannot initialize DBThread" << std::endl;
    }

    DBThread* dbThread=DBThread::GetInstance();

    window=new MainWindow(settings,
                          dbThread);

    dbThread->connect(&thread, SIGNAL(started()), SLOT(Initialize()));
    dbThread->connect(&thread, SIGNAL(finished()), SLOT(Finalize()));

    dbThread->moveToThread(&thread);
    thread.start();

    result=app.exec();

    delete window;

    QString tmpStylesheet(dbThread->GetStylesheetFilename()+TMP_SUFFIX);
    if(QFile::exists(tmpStylesheet)) {
        QFile::remove(tmpStylesheet);
    }

    thread.quit();
    thread.wait();

    DBThread::FreeInstance();

    return result;
}
Exemple #9
0
void TSController::calibrateVolume(){
    QSettings settings("settings.ini",QSettings::IniFormat);
    QDialog d(this);
    Ui::TSProgressDialog dui;
    //d.setWindowFlags(Qt::SubWindow);
    dui.setupUi(&d);

    //controller->setWindowFlags(Qt::WindowTitleHint | Qt::WindowMinimizeButtonHint|Qt::SubWindow);
    d.setWindowTitle(tr("Предупреждение"));
    dui.information->setText(tr("Идет подготовка..."));
    dui.acceptButton->setVisible(false);

    TSUsbDataReader *reader = new TSUsbDataReader();
    QThread *thread = new QThread();
    connect(thread,SIGNAL(started()),reader,SLOT(doWork()));
    connect(reader,SIGNAL(done()),&d,SLOT(accept()));
    connect(reader,SIGNAL(changeProgress(int)),dui.progressBar,SLOT(setValue(int)));
    reader->setBuffer(curveBuffer);
    reader->setReadingType(ReadForVolZer);
    reader->moveToThread(thread);
    thread->start();


    /*connect(readerThread,SIGNAL(done()),&d,SLOT(accept()));
    connect(readerThread,SIGNAL(changeProgress(int)),dui.progressBar,SLOT(setValue(int)));
    readerThread->setReadingType(ReadForVolZer);
    readerThread->startRead();*/
    if(d.exec()==1){
        settings.setValue("volZero",curveBuffer->volumeColibration());
        dui.information->setText(tr("Подготовка завершена.\nНажмите ОК и качайте шприцем."));
        dui.progressBar->setVisible(false);
        dui.acceptButton->setVisible(true);
    }
    reader->stopRead();
    Sleep(200);
    thread->quit();
    Sleep(200);
    thread->disconnect(reader);
    disconnect(&d,SLOT(accept()));
    delete thread;
    thread = NULL;
    delete reader;
    reader=NULL;

    d.exec();
    connect(&cPlotingTimer,SIGNAL(timeout()),this,SLOT(plotCalibration()));


    _reader = new TSUsbDataReader();
    _thread = new QThread();
    connect(_thread,SIGNAL(started()),_reader,SLOT(doWork()));
    connect(_reader,SIGNAL(done()),&d,SLOT(accept()));
    connect(_reader,SIGNAL(changeProgress(int)),dui.progressBar,SLOT(setValue(int)));
    _reader->setBuffer(curveBuffer);
    _reader->setReadingType(ReadForVolVal);
    _reader->moveToThread(_thread);
    _thread->start();
    cPlotingTimer.start(100);
}
int main(int argc, char* argv[])
{
#ifdef Q_WS_X11
  QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
#endif

  QGuiApplication app(argc,argv);
  SettingsRef     settings;
  int             result;

  app.setOrganizationName("libosmscout");
  app.setOrganizationDomain("libosmscout.sf.net");
  app.setApplicationName("OSMScout");

  qRegisterMetaType<RenderMapRequest>();
  qRegisterMetaType<DatabaseLoadedResponse>();
  qRegisterMetaType<osmscout::TileRef>();

  qmlRegisterType<MapWidget>("net.sf.libosmscout.map", 1, 0, "Map");
  qmlRegisterType<Location>("net.sf.libosmscout.map", 1, 0, "Location");
  qmlRegisterType<LocationListModel>("net.sf.libosmscout.map", 1, 0, "LocationListModel");
  qmlRegisterType<RouteStep>("net.sf.libosmscout.map", 1, 0, "RouteStep");
  qmlRegisterType<RoutingListModel>("net.sf.libosmscout.map", 1, 0, "RoutingListModel");

  qmlRegisterSingletonType<Theme>("net.sf.libosmscout.map", 1, 0, "Theme", ThemeProvider);

  osmscout::log.Debug(true);

  settings=std::make_shared<Settings>();

  QThread thread;

  if (!DBThread::InitializeInstance()) {
    std::cerr << "Cannot initialize DBThread" << std::endl;
    return 1;
  }

  DBThread* dbThread=DBThread::GetInstance();

  dbThread->connect(&thread, SIGNAL(started()), SLOT(Initialize()));
  dbThread->connect(&thread, SIGNAL(finished()), SLOT(Finalize()));

  dbThread->moveToThread(&thread);

  QQmlApplicationEngine window(QUrl("qrc:/qml/main.qml"));

  thread.start();

  result=app.exec();

  thread.quit();
  thread.wait();

  DBThread::FreeInstance();

  return result;
}
AssignmentClient::~AssignmentClient() {
    QThread* nodeThread = DependencyManager::get<NodeList>()->thread();
    
    // remove the NodeList from the DependencyManager
    DependencyManager::destroy<NodeList>();

    // ask the node thread to quit and wait until it is done
    nodeThread->quit();
    nodeThread->wait();
}
Exemple #12
0
int main(int argc, char ** argv) {
   QCoreApplication app{argc, argv};
   QObject context;
   QThread thread;
   context.moveToThread(&thread);
   thread.start();
   onTimeout(1000, []{ qDebug() << "T+1s"; });
   onTimeout(2000, &context, [&]{ qDebug() << "T+2s"; thread.quit(); });
   QObject::connect(&thread, &QThread::finished, &app, &QCoreApplication::quit);
   return app.exec();
}
void QWinRTAbstractVideoRendererControl::syncAndRender()
{
    qCDebug(lcMMVideoRender) << __FUNCTION__;
    Q_D(QWinRTAbstractVideoRendererControl);

    QThread *currentThread = QThread::currentThread();
    const QMetaMethod present = staticMetaObject.method(staticMetaObject.indexOfMethod("present()"));
    forever {
        if (currentThread->isInterruptionRequested())
            break;
        {
            CriticalSectionLocker lock(&d->mutex);
            HRESULT hr;
            if (d->dirtyState == TextureDirty) {
                CD3D11_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, d->format.frameWidth(), d->format.frameHeight(), 1, 1);
                desc.BindFlags |= D3D11_BIND_RENDER_TARGET;
                desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED;
                hr = g->device->CreateTexture2D(&desc, NULL, d->texture.ReleaseAndGetAddressOf());
                BREAK_IF_FAILED("Failed to get create video texture");
                ComPtr<IDXGIResource> resource;
                hr = d->texture.As(&resource);
                BREAK_IF_FAILED("Failed to cast texture to resource");
                hr = resource->GetSharedHandle(&d->shareHandle);
                BREAK_IF_FAILED("Failed to get texture share handle");
                d->dirtyState = SurfaceDirty;
            }

            hr = g->output->WaitForVBlank();
            CONTINUE_IF_FAILED("Failed to wait for vertical blank");

            bool success = false;
            switch (d->blitMode) {
            case DirectVideo:
                success = render(d->texture.Get());
                break;
            case MediaFoundation:
                success = dequeueFrame(&d->presentFrame);
                break;
            default:
                success = false;
            }

            if (!success)
                continue;

            // Queue to the control's thread for presentation
            present.invoke(this, Qt::QueuedConnection);
            currentThread->eventDispatcher()->processEvents(QEventLoop::AllEvents);
        }
    }

    // All done, exit render loop
    currentThread->quit();
}
void ThreadPoolWithSignals::cleanupIdleThreads()
{
   // QMutexLocker l(&threadMutex);
    while (idleThreads.count()>5)
    {
        QThread* t = *(idleThreads.begin());
        idleThreads.remove(t);
        allThreads.remove(t);
        t->quit();
    }
}
Exemple #15
0
 // cleans up the settings private instance. Should only be run once at closing down.
 void cleanupPrivateInstance() {
     // grab the thread before we nuke the instance
     QThread* settingsManagerThread = privateInstance->thread();
     
     // tell the private instance to clean itself up on its thread
     privateInstance->deleteLater();
     privateInstance = NULL;
     
     // quit the settings manager thread and wait on it to make sure it's gone
     settingsManagerThread->quit();
     settingsManagerThread->wait();
 }
void ThreadPoolWithSignals::cleanupThreads()
{
   // QMutexLocker l(&threadMutex);
    QThread * t;
    foreach(t,allThreads)
    {
        t->quit();
    }
    allThreads.clear();
    idleThreads.clear();
    activeThreads.clear();
}
Exemple #17
0
int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
	NetStatus::GiveFirewallAccess(QCoreApplication::applicationFilePath().replace('/','\\'));
	//qDebug() << QCoreApplication::applicationFilePath().replace('/','\\');
	QThread muxThread;
	Multiplexer *mux = new Multiplexer(AgentKind::ClientAgent, 0);
	mux->moveToThread(&muxThread);
	a.connect(&muxThread, &QThread::finished, mux, &QObject::deleteLater);
	a.connect(&a, &QCoreApplication::aboutToQuit, &muxThread, &QThread::quit);
	muxThread.start(QThread::TimeCriticalPriority);
	Sleep(1000);
	muxThread.quit();
	return a.exec();
}
Exemple #18
0
int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
	Network n;
	QThread inputHandleThread;
	InputHandle ih(&n);
	ih.moveToThread(&inputHandleThread);
	QObject::connect(&inputHandleThread, SIGNAL(started()), &ih, SLOT(start()));
	inputHandleThread.start();

	int ret = a.exec();
	inputHandleThread.quit();
	inputHandleThread.wait();
	return ret;
}
Exemple #19
0
void Connection::stopSendQueue() {
    if (auto sendQueue = _sendQueue.release()) {
        // grab the send queue thread so we can wait on it
        QThread* sendQueueThread = sendQueue->thread();
        
        // tell the send queue to stop and be deleted
        
        sendQueue->stop();

        _lastMessageNumber = sendQueue->getCurrentMessageNumber();

        sendQueue->deleteLater();
        
        // wait on the send queue thread so we know the send queue is gone
        sendQueueThread->quit();
        sendQueueThread->wait();
    }
}
Exemple #20
0
void tst_QPointer::threadSafety()
{

    QThread owner;
    owner.start();

    QThreadPool pool;
    for (int i = 0; i < 300; i++) {
        QPointer<TestRunnable> task = new TestRunnable;
        task->setAutoDelete(true);
        task->moveToThread(&owner);
        pool.start(task);
    }
    pool.waitForDone();

    owner.quit();
    owner.wait();
}
Exemple #21
0
void Connection::stopSendQueue() {
    if (auto sendQueue = _sendQueue.release()) {
        // grab the send queue thread so we can wait on it
        QThread* sendQueueThread = sendQueue->thread();
        
        // tell the send queue to stop and be deleted
        
        sendQueue->stop();
        sendQueue->deleteLater();
        
        // since we're stopping the send queue we should consider our handshake ACK not receieved
        _hasReceivedHandshakeACK = false;
        
        // wait on the send queue thread so we know the send queue is gone
        sendQueueThread->quit();
        sendQueueThread->wait();
    }
}
Exemple #22
0
void Agent::aboutToFinish() {
    setIsAvatar(false);// will stop timers for sending billboards and identity packets

    if (_scriptEngine) {
        _scriptEngine->stop();
    }

    // our entity tree is going to go away so tell that to the EntityScriptingInterface
    DependencyManager::get<EntityScriptingInterface>()->setEntityTree(nullptr);

    // cleanup the AssetClient thread
    QThread* assetThread = DependencyManager::get<AssetClient>()->thread();
    DependencyManager::destroy<AssetClient>();
    assetThread->quit();
    assetThread->wait();
    
    // cleanup the AudioInjectorManager (and any still running injectors)
    DependencyManager::destroy<AudioInjectorManager>();
}
AndroidCamera *AndroidCamera::open(int cameraId)
{
    AndroidCameraPrivate *d = new AndroidCameraPrivate();
    QThread *worker = new QThread;
    worker->start();
    d->moveToThread(worker);
    connect(worker, &QThread::finished, d, &AndroidCameraPrivate::deleteLater);
    bool ok = true;
    QMetaObject::invokeMethod(d, "init", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, ok), Q_ARG(int, cameraId));
    if (!ok) {
        worker->quit();
        worker->wait(5000);
        delete d;
        delete worker;
        return 0;
    }

    AndroidCamera *q = new AndroidCamera(d, worker);
    g_cameraMapMutex.lock();
    g_cameraMap->insert(cameraId, q);
    g_cameraMapMutex.unlock();
    return q;
}
Exemple #24
0
int main(int argc, char *argv[])
{
    QmlProfilerApplication app(argc, argv);

    app.parseArguments();

    if (app.isInteractive()) {
        QThread listenerThread;
        CommandListener listener;
        listener.moveToThread(&listenerThread);
        QObject::connect(&listener, SIGNAL(command(QString)), &app, SLOT(userCommand(QString)));
        QObject::connect(&app, SIGNAL(readyForCommand()), &listener, SLOT(readCommand()));
        listenerThread.start();
        int exitValue = app.exec();
        listenerThread.quit();
        // wait for listener to exit
        listenerThread.wait();
        return exitValue;
    } else {
        int exitValue = app.exec();
        app.outputData();
        return exitValue;
    }
}
	/**
	 * @brief This is a slot function. when a listening thread is terminated,
	 * the thread itself will be deleted here. Some cleanning works is also needed.
	 * @fn zp_net_Engine::on_ListenClosed
	 * @param id the terminated thread id.
	 */
	void zp_net_Engine::on_ListenClosed(QString  id)
	{
		//m_mutex_listen.lock();
		if (m_map_netListenThreads.find(id)!=m_map_netListenThreads.end())
		{
			//Clean objects;
			zp_netListenThread * pListenObj = m_map_netListenThreads[id];
			QThread * pThread = m_map_netInternalListenThreads[id];
			m_map_netListenThreads.remove(id);
			m_map_netInternalListenThreads.remove(id);
			//disconnect signals;
			disconnect(this,&zp_net_Engine::startListen,pListenObj,&zp_netListenThread::startListen);
			disconnect(this,&zp_net_Engine::stopListen,pListenObj,&zp_netListenThread::stopListen);
			disconnect(pListenObj,&zp_netListenThread::evt_Message,this,&zp_net_Engine::evt_Message);
			disconnect(pListenObj,&zp_netListenThread::evt_ListenClosed,this,&zp_net_Engine::on_ListenClosed);
			disconnect(pListenObj,&zp_netListenThread::evt_NewClientArrived,this,&zp_net_Engine::on_New_Arrived_Client);
			pListenObj->deleteLater();
			pThread->quit();
			pThread->wait();
			pThread->deleteLater();

		}
		//m_mutex_listen.unlock();
	}
void AssignmentClient::stopAssignmentClient() {
    qCDebug(assigmnentclient) << "Forced stop of assignment-client.";

    _requestTimer.stop();
    _statsTimerACM.stop();

    if (_currentAssignment) {
        // grab the thread for the current assignment
        QThread* currentAssignmentThread = _currentAssignment->thread();

        // ask the current assignment to stop
        QMetaObject::invokeMethod(_currentAssignment, "stop", Qt::BlockingQueuedConnection);

        // ask the current assignment to delete itself on its thread
        _currentAssignment->deleteLater();

        // when this thread is destroyed we don't need to run our assignment complete method
        disconnect(currentAssignmentThread, &QThread::destroyed, this, &AssignmentClient::assignmentCompleted);

        // wait on the thread from that assignment - it will be gone once the current assignment deletes
        currentAssignmentThread->quit();
        currentAssignmentThread->wait();
    }
}
Exemple #27
0
bool Commands::Run(const QString & filename, bool loopinput)
{
    QString cmd;

    int ret;
    int poll_cnt = 1;
    struct pollfd polls[2];
    memset(polls, 0, sizeof(polls));

    polls[0].fd      = 0;
    polls[0].events  = POLLIN | POLLPRI;
    polls[0].revents = 0;
    m_timeout = 10;

    m_fileName = filename;

    m_streamer = new Streamer(this, m_fileName, loopinput);
    QThread *streamThread = new QThread(this);

    m_streamer->moveToThread(streamThread);
    connect(streamThread, SIGNAL(finished(void)),
            m_streamer, SLOT(deleteLater(void)));

    connect(this, SIGNAL(SendBytes(void)),
            m_streamer, SLOT(SendBytes(void)));

    streamThread->start();

    QFile input;
    input.open(stdin, QIODevice::ReadOnly);
    QTextStream qtin(&input);

    LOG(VB_RECORD, LOG_INFO, LOC + "Listening for commands");

    while (m_run)
    {
        ret = poll(polls, poll_cnt, m_timeout);

        if (polls[0].revents & POLLHUP)
        {
            LOG(VB_RECORD, LOG_ERR, LOC + "poll eof (POLLHUP)");
            break;
        }
        else if (polls[0].revents & POLLNVAL)
        {
            LOG(VB_RECORD, LOG_ERR, LOC + "poll error");
            return false;
        }

        if (polls[0].revents & POLLIN)
        {
            if (ret > 0)
            {
                cmd = qtin.readLine();
                if (!process_command(cmd))
                {
                    streamThread->quit();
                    streamThread->wait();
                    delete streamThread;
                    streamThread = NULL;
                    m_streamer = NULL;
                    m_run = false;
                }
            }
            else if (ret < 0)
            {
                if ((EOVERFLOW == errno))
                {
                    LOG(VB_RECORD, LOG_ERR, LOC + "command overflow.");
                    break; // we have an error to handle
                }

                if ((EAGAIN == errno) || (EINTR  == errno))
                {
                    LOG(VB_RECORD, LOG_ERR, LOC + "retry command read.");
                    continue; // errors that tell you to try again
                }

                LOG(VB_RECORD, LOG_ERR, LOC + "unknown error reading command.");
            }
        }
    }

    return true;
}
void CallModelTest::testGetEventsTimeTypeFilter()
{
    QFETCH(bool, useThread);

    deleteAll();

    QThread modelThread;

    //initTestCase ==> 3 dialled calls, 2 Received calls, 3 Missed Calls already added
    CallModel model;
    watcher.setModel(&model);
    if (useThread) {
        modelThread.start();
        model.setBackgroundThread(&modelThread);
    }

    QDateTime when = QDateTime::currentDateTime();
    //3 dialled
    addTestEvent( model, Event::CallEvent, Event::Outbound, ACCOUNT1, -1, "", false, false, when );
    addTestEvent( model, Event::CallEvent, Event::Outbound, ACCOUNT1, -1, "", false, false, when.addSecs(5) );
    addTestEvent( model, Event::CallEvent, Event::Outbound, ACCOUNT1, -1, "", false, false, when.addSecs(10) );
    QVERIFY(watcher.waitForAdded(3));

    //2 received
    addTestEvent( model, Event::CallEvent, Event::Inbound, ACCOUNT1, -1, "", false, false, when );
    addTestEvent( model, Event::CallEvent, Event::Inbound, ACCOUNT1, -1, "", false, false, when.addSecs(5) );
    QVERIFY(watcher.waitForAdded(2));

    //3 missed
    addTestEvent( model, Event::CallEvent, Event::Inbound, ACCOUNT1, -1, "", false, true, when );
    addTestEvent( model, Event::CallEvent, Event::Inbound, ACCOUNT1, -1, "", false, true, when.addSecs(5) );
    addTestEvent( model, Event::CallEvent, Event::Inbound, ACCOUNT1, -1, "", false, true, when.addSecs(10) );
    QVERIFY(watcher.waitForAdded(3));

    QDateTime time = when;
    //model.setQueryMode(EventModel::SyncQuery);
    model.setTreeMode(false);
    QVERIFY(model.setFilter(CallModel::SortByTime,  CallEvent::DialedCallType, time));
    QVERIFY(model.getEvents());
    QVERIFY(watcher.waitForModelReady());

    int numEventsRet = model.rowCount();
    QCOMPARE(numEventsRet, 3);
    Event e1 = model.event(model.index(0,0));
    Event e2 = model.event(model.index(1,0));
    Event e3 = model.event(model.index(2,0));
    QVERIFY(e1.isValid());
    QVERIFY(e2.isValid());
    QVERIFY(e3.isValid());
    QVERIFY(e1.direction() == Event::Outbound);
    QVERIFY(e2.direction() == Event::Outbound);
    QVERIFY(e3.direction() == Event::Outbound);

    QVERIFY(model.setFilter(CallModel::SortByTime, CallEvent::MissedCallType, time));
    QVERIFY(watcher.waitForModelReady());
    QVERIFY(model.rowCount() == 3);
    QVERIFY(model.setFilter(CallModel::SortByTime, CallEvent::ReceivedCallType, time));
    qDebug() << time;
    QVERIFY(watcher.waitForModelReady());
    for (int i = 0; i < model.rowCount(); i++) {
        qDebug() << model.event(model.index(i, 0)).toString();
    }
    QVERIFY(model.rowCount() == 2);

    /**
      * testing to check for adding events with wrong filters
      */
    time = when.addSecs(-60*5);
    int numEventsGot = 0;
    //adding one more received but 5 minutes before the set time filter
    addTestEvent( model, Event::CallEvent, Event::Inbound, ACCOUNT1, -1, "", false, false, time );
    QVERIFY(watcher.waitForAdded());
    QVERIFY(model.rowCount() == 2); //event should not be added to model, so rowCount should remain same for received calls
    //filter is set for received call, try to add missed and dialled calls with correct time filter
    addTestEvent( model, Event::CallEvent, Event::Inbound, ACCOUNT1, -1, "", false, true, when );
    QVERIFY(watcher.waitForAdded());
    numEventsGot = model.rowCount();
    QVERIFY(numEventsGot == 2); //event should not be added to model, so rowCount should remain same which was for received calls
    addTestEvent( model, Event::CallEvent, Event::Outbound, ACCOUNT1, -1, "", false, false, when );
    QVERIFY(watcher.waitForAdded());
    numEventsGot = model.rowCount();
    QVERIFY(numEventsGot  == 2); //event should not be added to model, so rowCount should remain same which was for received calls

    /**
      ** testing to check for getting events after he time when all events addition was complete
      */
    //Trying to get events after 5 minutes after the  first event was added
    time = when.addSecs(60*5);
    QVERIFY(model.setFilter(CallModel::SortByTime, CallEvent::ReceivedCallType, time));
    QVERIFY(watcher.waitForModelReady());
    QVERIFY(model.rowCount() == 0);

    qDebug() << "wait thread";
    modelThread.quit();
    modelThread.wait(3000);
    qDebug() << "done";
}
Exemple #29
0
extern "C" int qtmn(int argc, char** argv)
{
#else
int main(int argc, char **argv)
{
#endif
    try {
        QApplication app(argc, argv);

        QSurfaceFormat fmt;
        fmt.setDepthBufferSize(24);
        if (QCoreApplication::arguments().contains(QStringLiteral("--multisample")))
            fmt.setSamples(4);
        if (QCoreApplication::arguments().contains(QStringLiteral("--coreprofile"))) {
            fmt.setVersion(3, 2);
            fmt.setProfile(QSurfaceFormat::CoreProfile);
        }
        QSurfaceFormat::setDefaultFormat(fmt);

        auto logger = gatherer::graphics::Logger::create("preview-qt");
        logger->info("Start");

        // Should be created in heap, ownership taken by parent widget
        GLWidget *glWidget = new GLWidget; // Note: moved creation output of Window for signal connection:

#if defined(__ANDROID__)
        const bool synth = true; // Camera not working on Android (yet)
#else
        const bool synth = false;
#endif
        VideoCapture capture(0, synth);

        MainWindow mainWindow(glWidget, capture);
        mainWindow.resize(mainWindow.sizeHint());
        int desktopArea = QApplication::desktop()->width() * QApplication::desktop()->height();
        int widgetArea = mainWindow.width() * mainWindow.height();
        if (((float)widgetArea / (float)desktopArea) < 0.75f)
            mainWindow.show();
        else
            mainWindow.showMaximized();

        // ((((((((((((((((( bEGIN )))))))))))))))))

        QThread captureThread;
        captureThread.start();

        capture.moveToThread(&captureThread);

        qRegisterMetaType< cv::Mat >("cv::Mat");
        QObject::connect(&capture, &VideoCapture::started, [](){ qDebug() << "capture started"; });

        glWidget->connect(&capture, SIGNAL(matReady(cv::Mat)), SLOT(setImage(cv::Mat)));

        // ((((((((((((((((( eND )))))))))))))))))
        int rc = app.exec();

        captureThread.quit();
        captureThread.wait();

        return rc;
    }
    catch (const std::exception& exc) {
        std::cerr << "Exception catched: " << exc.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch (...) {
        std::cerr << "Unknown exception catched" << std::endl;
        return EXIT_FAILURE;
    }
}
 void cleanup()
 {
     thread->quit();
     worker->deleteLater();
     this->deleteLater();
 }