示例#1
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;
    }
}
示例#2
0
void RPCConsole::startExecutor()
{
    QThread* thread = new QThread;
    RPCExecutor *executor = new RPCExecutor();
    executor->moveToThread(thread);

    // Notify executor when thread started (in executor thread)
    connect(thread, SIGNAL(started()), executor, SLOT(start()));
    // Replies from executor object must go to this object
    connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
    // Requests from this object must go to executor
    connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
    // On stopExecutor signal
    // - queue executor for deletion (in execution thread)
    // - quit the Qt event loop in the execution thread
    connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
    connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
    // Queue the thread for deletion (in this thread) when it is finished
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

    // Default implementation of QThread::run() simply spins up an event loop in the thread,
    // which is what we want.
    thread->start();
}
示例#3
0
void HLSManager::startSegmentation()
{
    qDebug() << "Initializing HSL manager...";
    config_info config;
    memset(&config, 0, sizeof(config_info));

    config.segment_length = m_segmentLength;
    config.temp_directory = (char *)malloc(sizeof(qPrintable(m_tempDirectory)));
    strcpy((char *)config.temp_directory, qPrintable(m_tempDirectory));
    config.filename_prefix = (char *)malloc(sizeof(qPrintable(m_filenamePrefix)));
    strcpy((char *)config.filename_prefix, qPrintable(m_filenamePrefix));
    config.encoding_profile = (char *)malloc(sizeof(qPrintable(m_encodingProfile)));
    strcpy((char *)config.encoding_profile, qPrintable(m_encodingProfile));
    config.input_filename = (char *)malloc(sizeof(qPrintable(m_inputFilename)));
    strcpy((char *)config.input_filename, qPrintable(m_inputFilename));

    config.pmt_pid = pids.value(PMT_PID);
    config.video_pid = pids.value(VIDEO_PID);
    config.audio_pid = pids.value(AUDIO_PID);

    m_segmenter = new Segmenter();
    m_segmenter->configure(m_adapter_no, config);
#ifdef USING_DEVICE
    m_segmenter->setDtvDevice(m_dtv_device);
#endif
    connect(m_segmenter, SIGNAL(segmentIndexChanged(int,double)), this, SLOT(onSegmentIndexChanged(int,double)));

    QThread* thread = new QThread();
    m_segmenter->moveToThread(thread);
    connect(thread, SIGNAL(started()), m_segmenter, SLOT(process()));
    connect(m_segmenter, SIGNAL(reportExitCode(int)), this, SLOT(onSegmenterExitCode(int)));
    connect(m_segmenter, SIGNAL(finished()), thread, SLOT(quit()));
    connect(m_segmenter, SIGNAL(finished()), m_segmenter, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();
}
示例#4
0
void Overlay::setEnabled(int status){
    if (status==2){

        worker = new OverlayWorker();

        QThread* workThread = new QThread();
        worker->moveToThread(workThread);
        workThread->start();

        if (ui->radioArray->isChecked()){ //mask from array
            worker->setMethod(0);

        } else {
            worker->setMethod(1);
        }

        worker->start(buffer, ui->outputNumber->value(), ui->inputA->value(), ui->inputOver->value());

    } else {

        delete worker;

    }
}
示例#5
0
bool Servatrice::initServer()
{
    serverName = settings->value("server/name").toString();
    serverId = settings->value("server/id", 0).toInt();
    bool regServerOnly = settings->value("server/regonly", 0).toBool();
        
    const QString authenticationMethodStr = settings->value("authentication/method").toString();
    if (authenticationMethodStr == "sql") {
        authenticationMethod = AuthenticationSql;
    } else {
        if (regServerOnly) {
            qDebug() << "Registration only server enabled but no DB Connection : Error.";
            return false;   
        }
        authenticationMethod = AuthenticationNone;
    }
    
    QString dbTypeStr = settings->value("database/type").toString();
    if (dbTypeStr == "mysql")
        databaseType = DatabaseMySql;
    else
        databaseType = DatabaseNone;
    
    servatriceDatabaseInterface = new Servatrice_DatabaseInterface(-1, this);
    setDatabaseInterface(servatriceDatabaseInterface);
    
    if (databaseType != DatabaseNone) {
        settings->beginGroup("database");
        dbPrefix = settings->value("prefix").toString();
        servatriceDatabaseInterface->initDatabase("QMYSQL",
                              settings->value("hostname").toString(),
                              settings->value("database").toString(),
                              settings->value("user").toString(),
                              settings->value("password").toString());
        settings->endGroup();
        
        updateServerList();
        
        qDebug() << "Clearing previous sessions...";
        servatriceDatabaseInterface->clearSessionTables();
    }
    
    const QString roomMethod = settings->value("rooms/method").toString();
    if (roomMethod == "sql") {
        QSqlQuery query(servatriceDatabaseInterface->getDatabase());
        query.prepare("select id, name, descr, auto_join, join_message from " + dbPrefix + "_rooms order by id asc");
        servatriceDatabaseInterface->execSqlQuery(query);
        while (query.next()) {
            QSqlQuery query2(servatriceDatabaseInterface->getDatabase());
            query2.prepare("select name from " + dbPrefix + "_rooms_gametypes where id_room = :id_room");
            query2.bindValue(":id_room", query.value(0).toInt());
            servatriceDatabaseInterface->execSqlQuery(query2);
            QStringList gameTypes;
            while (query2.next())
                gameTypes.append(query2.value(0).toString());
            
            addRoom(new Server_Room(query.value(0).toInt(),
                                    query.value(1).toString(),
                                    query.value(2).toString(),
                                    query.value(3).toInt(),
                                    query.value(4).toString(),
                                    gameTypes,
                                    this
            ));
        }
    } else {
        int size = settings->beginReadArray("rooms/roomlist");
        for (int i = 0; i < size; ++i) {
            settings->setArrayIndex(i);
            
            QStringList gameTypes;
            int size2 = settings->beginReadArray("game_types");
                for (int j = 0; j < size2; ++j) {
                settings->setArrayIndex(j);
                gameTypes.append(settings->value("name").toString());
            }
            settings->endArray();
                
            Server_Room *newRoom = new Server_Room(
                i,
                settings->value("name").toString(),
                settings->value("description").toString(),
                settings->value("autojoin").toBool(),
                settings->value("joinmessage").toString(),
                gameTypes,
                this
            );
            addRoom(newRoom);
        }
        settings->endArray();
    }
    
    updateLoginMessage();
    
    maxGameInactivityTime = settings->value("game/max_game_inactivity_time").toInt();
    maxPlayerInactivityTime = settings->value("game/max_player_inactivity_time").toInt();
    
    maxUsersPerAddress = settings->value("security/max_users_per_address").toInt();
    messageCountingInterval = settings->value("security/message_counting_interval").toInt();
    maxMessageCountPerInterval = settings->value("security/max_message_count_per_interval").toInt();
    maxMessageSizePerInterval = settings->value("security/max_message_size_per_interval").toInt();
    maxGamesPerUser = settings->value("security/max_games_per_user").toInt();

	try { if (settings->value("servernetwork/active", 0).toInt()) {
		qDebug() << "Connecting to ISL network.";
		const QString certFileName = settings->value("servernetwork/ssl_cert").toString();
		const QString keyFileName = settings->value("servernetwork/ssl_key").toString();
		qDebug() << "Loading certificate...";
		QFile certFile(certFileName);
		if (!certFile.open(QIODevice::ReadOnly))
			throw QString("Error opening certificate file: %1").arg(certFileName);
		QSslCertificate cert(&certFile);
#if QT_VERSION < 0x050000
		if (!cert.isValid())
			throw(QString("Invalid certificate."));
#else
		const QDateTime currentTime = QDateTime::currentDateTime();
		if(currentTime < cert.effectiveDate() ||
			currentTime > cert.expiryDate() ||
			cert.isBlacklisted())
			throw(QString("Invalid certificate."));
#endif
		qDebug() << "Loading private key...";
		QFile keyFile(keyFileName);
		if (!keyFile.open(QIODevice::ReadOnly))
			throw QString("Error opening private key file: %1").arg(keyFileName);
		QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
		if (key.isNull())
			throw QString("Invalid private key.");
		
		QMutableListIterator<ServerProperties> serverIterator(serverList);
		while (serverIterator.hasNext()) {
			const ServerProperties &prop = serverIterator.next();
			if (prop.cert == cert) {
				serverIterator.remove();
				continue;
			}
			
			QThread *thread = new QThread;
			thread->setObjectName("isl_" + QString::number(prop.id));
			connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
			
			IslInterface *interface = new IslInterface(prop.id, prop.hostname, prop.address.toString(), prop.controlPort, prop.cert, cert, key, this);
			interface->moveToThread(thread);
			connect(interface, SIGNAL(destroyed()), thread, SLOT(quit()));
			
			thread->start();
			QMetaObject::invokeMethod(interface, "initClient", Qt::BlockingQueuedConnection);
		}
			
		const int networkPort = settings->value("servernetwork/port", 14747).toInt();
		qDebug() << "Starting ISL server on port" << networkPort;
		
		islServer = new Servatrice_IslServer(this, cert, key, this);
		if (islServer->listen(QHostAddress::Any, networkPort))
			qDebug() << "ISL server listening.";
		else
			throw QString("islServer->listen()");
	} } catch (QString error) {
		qDebug() << "ERROR --" << error;
		return false;
	}
	
	pingClock = new QTimer(this);
	connect(pingClock, SIGNAL(timeout()), this, SIGNAL(pingClockTimeout()));
	pingClock->start(1000);
	
	int statusUpdateTime = settings->value("server/statusupdate").toInt();
	statusUpdateClock = new QTimer(this);
	connect(statusUpdateClock, SIGNAL(timeout()), this, SLOT(statusUpdate()));
	if (statusUpdateTime != 0) {
		qDebug() << "Starting status update clock, interval " << statusUpdateTime << " ms";
		statusUpdateClock->start(statusUpdateTime);
	}
	
	const int numberPools = settings->value("server/number_pools", 1).toInt();
	gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this);
	gameServer->setMaxPendingConnections(1000);
	const int gamePort = settings->value("server/port", 4747).toInt();
	qDebug() << "Starting server on port" << gamePort;
	if (gameServer->listen(QHostAddress::Any, gamePort))
		qDebug() << "Server listening.";
	else {
		qDebug() << "gameServer->listen(): Error.";
		return false;
	}
	return true;
}
示例#6
0
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";
}
示例#7
0
void MainWindow::install()
{
    ui->statusLabel->setFont(getFont(ui->statusLabel, FONT_STATUSLABEL_RATIO));
    ui->statusProgressBar->setFont(getFont(ui->statusProgressBar, FONT_PROGRESSBAR_RATIO));

    qApp->processEvents();
    /* Find out what device we are running on */
    logger->addLine("Detecting device we are running on");
    device = targetList->getTarget(utils->getOSMCDev());
    if (device == NULL)
    {
        haltInstall("unsupported device"); /* No tr here as not got lang yet */
        return;
    }
    /* Mount the BOOT filesystem */
    logger->addLine("Mounting boot filesystem");
    bool hasMount = false;
    hasMount = utils->mountPartition(device, MNT_BOOT);
    if (! hasMount && utils->getOSMCDev() == "atv")
    {
        /* Super hacky for Apple TV 1st gen. Sometimes no internal disk */
        hasMount = utils->mountPartition(device, "/dev/sda1");
        device->setRoot("/dev/sda2");
    }
    if (! hasMount)
    {
        haltInstall("could not mount bootfs");
        return;
    }
    /* Sanity check: need filesystem.tar.xz */
    QFile fileSystem(QString(MNT_BOOT) + "/filesystem.tar.xz");
    if (! fileSystem.exists())
    {
        haltInstall("no filesystem found");
        return;
    }
    /* Load in preseeded values */
    preseed = new PreseedParser();
    if (preseed->isLoaded())
    {
        logger->addLine("Preseed file found, will attempt to parse");
        /* Locales */
        locale = preseed->getStringValue("globe/locale");
        if (! locale.isEmpty())
        {
            logger->addLine("Found a definition for globalisation: " + locale);
            QTranslator translator;
            if (translator.load(qApp->applicationDirPath() + "/osmc_" + locale + ".qm"))
            {
                logger->addLine("Translation loaded successfully!");
                qApp->installTranslator(&translator);
                ui->retranslateUi(this);
            }
            else
                logger->addLine("Could not load translation");
        }
        /* Install target */
        installTarget = preseed->getStringValue("target/storage");
        if (! installTarget.isEmpty())
        {
            logger->addLine("Found a definition for storage: " + installTarget);
            if (installTarget == "nfs")
            {
                QString nfsPath = preseed->getStringValue("target/storagePath");
                if (! nfsPath.isEmpty())
                {
                    device->setRoot(nfsPath);
                    useNFS = true;
                }
            }
            if (installTarget == "usb")
            {
                /* Behaviour for handling USB installs */
                if (utils->getOSMCDev() == "rbp1") { device->setRoot("/dev/sda1"); }
                if (utils->getOSMCDev() == "rbp2") { device->setRoot("/dev/sda1"); }
                if (utils->getOSMCDev() == "vero1") { device->setRoot("/dev/sda1"); }
                for (int i = 0; i <= 60; i++)
                {
                    ui->statusLabel->setText(tr("USB install:") + " " + QString::number(60 - i) + " " + ("seconds to remove device before data loss"));
                    qApp->processEvents();
                    system("/bin/sleep 1");
                }
            }
        }
        /* Bring up network if using NFS */
        if (useNFS)
        {
            logger->addLine("NFS installation chosen, must bring up network");
            nw = new Network();
            nw->setIP(preseed->getStringValue("network/ip"));
            nw->setMask(preseed->getStringValue("network/mask"));
            nw->setGW(preseed->getStringValue("network/gw"));
            nw->setDNS1(preseed->getStringValue("network/dns1"));
            nw->setDNS2(preseed->getStringValue("network/dns2"));
            if (! nw->isDefined())
            {
                logger->addLine("Either network preseed definition incomplete, or user wants DHCP");
                nw->setAuto();
            }
            logger->addLine("Attempting to bring up eth0");
            ui->statusLabel->setText(tr("Configuring Network"));
            nw->bringUp();
        }
    }
    else
    {
        logger->addLine("No preseed file was found");
    }
    /* If !nfs, create necessary partitions */
    if (! useNFS)
    {
        logger->addLine("Creating root partition");
        ui->statusLabel->setText(tr("Formatting device"));
        qApp->processEvents(); /* Force GUI update */
        QString rootBase = device->getRoot();
        if (rootBase.contains("mmcblk"))
            rootBase.chop(2);
        else
            rootBase.chop(1);
        logger->addLine("From a root partition of " + device->getRoot() + ", I have deduced a base device of " + rootBase);
        if (device->hasRootChanged() && utils->getOSMCDev() != "atv")
        {
            logger->addLine("Must mklabel as root fs is on another device");
            utils->mklabel(rootBase, false);
            utils->mkpart(rootBase, "ext4", "4096s", "100%");
            utils->fmtpart(device->getRoot(), "ext4");
        }
        else
        {
            int size = utils->getPartSize(rootBase, (device->getBootFS() == "vfat" ? "fat32" : "ext4"));
            if (size == -1)
            {
                logger->addLine("Issue getting size of device");
                haltInstall(tr("cannot work out partition size"));
                return;
            }
            logger->addLine("Determined " + QString::number(size) + " MB as end of first partition");
            utils->mkpart(rootBase, "ext4", QString::number(size + 2) + "M", "100%");
            utils->fmtpart(device->getRoot(), "ext4");
        }
    }
    /* Mount root filesystem */
    if (useNFS)
        bc = new BootloaderConfig(device, nw, utils, logger);
    else
        bc = new BootloaderConfig(device, NULL, utils, logger);
    logger->addLine("Mounting root");
    if ( ! utils->mountPartition(device, MNT_ROOT))
    {
        logger->addLine("Error occured trying to mount root of " + device->getRoot());
        haltInstall(tr("can't mount root"));
        return;
    }
    if (useNFS)
        system("rm -rf /mnt/root/*"); /* BusyBox tar does not like overwrites. Clear nfsroot first */
   /* Extract root filesystem */
   ui->statusLabel->setText(tr("Installing files"));
   logger->addLine("Extracting files to root filesystem");
   ui->statusProgressBar->setMinimum(0);
   ui->statusProgressBar->setMaximum(100);

   QThread* thread = new QThread(this);
   ExtractWorker *worker = new ExtractWorker(fileSystem.fileName(), MNT_ROOT, logger);
   worker->moveToThread(thread);
   connect(thread, SIGNAL(started()), worker, SLOT(extract()));
   connect(worker, SIGNAL(progressUpdate(unsigned)), this, SLOT(setProgress(unsigned)));
   connect(worker, SIGNAL(error(QString)), this, SLOT(haltInstall(QString)));
   connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
   connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
   connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
   connect(thread, SIGNAL(finished()), this, SLOT(finished()));
   thread->start();
}
示例#8
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;
    }
}
示例#9
0
void MainWindow::getScanFromFile()
    {

    //TO DO - Use native dialog once bug is resolved with multiple windows and the file browser not closing


    inDir = QFileDialog::getExistingDirectory(NULL, "Open Directory",QDir::homePath(),QFileDialog::DontUseNativeDialog | QFileDialog::DontResolveSymlinks);

    if (inDir != ""){

    ui->pushButtonSaveScan->setEnabled(false);

    //ProcessScan scanner(inDir);

    ProcessScan *scanner = new ProcessScan(inDir);

    //processscan::ProcessScan scanner;

    if (pointcloud != NULL)
        delete pointcloud;

    pointcloud = new pointCloud;

    // Make a connection to allow the ScanDraiD scanner object return data.
    connect(scanner, SIGNAL(percentageComplete(QString, int)), this, SLOT(updateStatusBar(QString,int)));
    connect(scanner, SIGNAL(percentageComplete(QString, int)), ui->GLScanWidgetui, SLOT(redraw()));

    connect(scanner, SIGNAL(addPointToCloud(float,float,float)), pointcloud, SLOT(addPoint(float,float,float)));

    scanner->setCameraHFov(getSetting("CAMERA_HFOV").toFloat(), true);
    scanner->setCameraVFov(getSetting("CAMERA_VFOV").toFloat());
    scanner->setCameraDistance(getSetting("CAMERA_DISTANCE").toFloat());
    scanner->setLaserOffset(getSetting("LASER_OFFSET").toFloat());
    scanner->setHorizontalAverage(getSetting("HORIZ_AVG").toInt());
    scanner->setVerticalAverage(getSetting("VERT_AVG").toInt());
    scanner->setFrameSkip(getSetting("FRAME_SKIP").toInt());
    scanner->setLineSkip(getSetting("LINE_SKIP").toInt());

    //QThread *process = new QThread;
    //scanner.moveToThread(process);

    //connect(process, SIGNAL(started()), &scanner, SLOT(start()));
    //process->start();


    QThread* thread = new QThread;
    //Worker* worker = new Worker();
    scanner->moveToThread(thread);
    //connect(scanner, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
    connect(thread, SIGNAL(started()), scanner, SLOT(start()));
    connect(scanner, SIGNAL(finished()), thread, SLOT(quit()));
    connect(scanner, SIGNAL(finished()), scanner, SLOT(deleteLater()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();

    //scanner->start();

    //Move this from here. it doesnt work because of the thread
    updateStatusBar("Scan Complete", 3000);
    ui->pushButtonSaveScan->setEnabled(true);

    //qDebug() << "Number of points: " << pointcloud->cloudSize();

    ui->GLScanWidgetui->setCloud(pointcloud);

    //pointcloud->refineCloud();


    }
示例#10
0
MainWindow::MainWindow(CWizDatabaseManager& dbMgr, QWidget *parent)
    : QMainWindow(parent)
    , m_core(new ICore(this))
    , m_dbMgr(dbMgr)
    , m_progress(new CWizProgressDialog(this))
    , m_settings(new CWizUserSettings(dbMgr.db()))
    , m_sync(new CWizKMSyncThread(dbMgr.db(), this))
    , m_syncTimer(new QTimer(this))
    , m_searchIndexer(new CWizSearchIndexer(m_dbMgr))
    , m_upgrade(new CWizUpgrade())
    //, m_certManager(new CWizCertManager(*this))
    , m_cipherForm(new CWizUserCipherForm(*this, this))
    , m_objectDownloaderHost(new CWizObjectDataDownloaderHost(dbMgr, this))
    //, m_avatarDownloaderHost(new CWizUserAvatarDownloaderHost(dbMgr.db().GetAvatarPath(), this))
    , m_transitionView(new CWizDocumentTransitionView(this))
    #ifndef Q_OS_MAC
    , m_labelNotice(NULL)
    , m_optionsAction(NULL)
    #endif
    #ifdef Q_OS_MAC
    , m_toolBar(new CWizMacToolBar(this))
    #else
    , m_toolBar(new QToolBar("Main", this))
    #endif
    , m_menuBar(new QMenuBar(this))
    , m_statusBar(new CWizStatusBar(*this, this))
    , m_actions(new CWizActions(*this, this))
    , m_category(new CWizCategoryView(*this, this))
    , m_documents(new CWizDocumentListView(*this, this))
    , m_noteList(NULL)
    , m_msgList(new MessageListView(this))
    , m_documentSelection(new CWizDocumentSelectionView(*this, this))
    , m_doc(new CWizDocumentView(*this, this))
    , m_history(new CWizDocumentViewHistory())
    , m_animateSync(new CWizAnimateAction(*this, this))
    , m_bRestart(false)
    , m_bLogoutRestart(false)
    , m_bUpdatingSelection(false)
{
    connect(qApp, SIGNAL(aboutToQuit()), SLOT(on_application_aboutToQuit()));
    connect(qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit())); // Qt bug: Qt5 bug
    qApp->installEventFilter(this);

    //CWizCloudPool::instance()->init(&m_dbMgr);

    // search and full text search
    QThread *threadFTS = new QThread();
    m_searchIndexer->moveToThread(threadFTS);
    threadFTS->start(QThread::IdlePriority);

    // upgrade check
    QThread *thread = new QThread();
    m_upgrade->moveToThread(thread);
    connect(m_upgrade, SIGNAL(checkFinished(bool)), SLOT(on_checkUpgrade_finished(bool)));
    thread->start(QThread::IdlePriority);

    // syncing thread
    connect(m_sync, SIGNAL(processLog(const QString&)), SLOT(on_syncProcessLog(const QString&)));
    connect(m_sync, SIGNAL(syncFinished(int, QString)), SLOT(on_syncDone(int, QString)));
    connect(m_syncTimer, SIGNAL(timeout()), SLOT(on_actionAutoSync_triggered()));
    int nInterval = m_settings->syncInterval();
    if (nInterval == 0) {
        m_syncTimer->setInterval(15 * 60 * 1000);   // default 15 minutes
    } else {
        m_syncTimer->setInterval(nInterval * 60 * 1000);
    }

    if (nInterval != -1) {
        QTimer::singleShot(3 * 1000, this, SLOT(on_actionAutoSync_triggered()));
    }

    // misc settings
    //m_avatarDownloaderHost->setDefault(::WizGetSkinResourcePath(userSettings().skin()) + "avatar_default.png");

    // GUI
    initActions();
    initMenuBar();
    initToolBar();
    initClient();

    setWindowTitle(tr("WizNote"));

    restoreStatus();

    client()->hide();

#ifdef Q_OS_MAC
    setupFullScreenMode(this);
#endif // Q_OS_MAC

    WizService::NoteComments::init();
}
示例#11
0
void AssignmentClient::readPendingDatagrams() {
    auto nodeList = DependencyManager::get<NodeList>();

    QByteArray receivedPacket;
    HifiSockAddr senderSockAddr;

    while (nodeList->getNodeSocket().hasPendingDatagrams()) {
        receivedPacket.resize(nodeList->getNodeSocket().pendingDatagramSize());
        nodeList->getNodeSocket().readDatagram(receivedPacket.data(), receivedPacket.size(),
                                               senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer());

        if (nodeList->packetVersionAndHashMatch(receivedPacket)) {
            if (packetTypeForPacket(receivedPacket) == PacketTypeCreateAssignment) {

                qDebug() << "Received a PacketTypeCreateAssignment - attempting to unpack.";

                // construct the deployed assignment from the packet data
                _currentAssignment = AssignmentFactory::unpackAssignment(receivedPacket);

                if (_currentAssignment) {
                    qDebug() << "Received an assignment -" << *_currentAssignment;

                    // switch our DomainHandler hostname and port to whoever sent us the assignment

                    nodeList->getDomainHandler().setSockAddr(senderSockAddr, _assignmentServerHostname);
                    nodeList->getDomainHandler().setAssignmentUUID(_currentAssignment->getUUID());

                    qDebug() << "Destination IP for assignment is" << nodeList->getDomainHandler().getIP().toString();

                    // start the deployed assignment
                    QThread* workerThread = new QThread;
                    workerThread->setObjectName("ThreadedAssignment Worker");

                    connect(workerThread, &QThread::started, _currentAssignment.data(), &ThreadedAssignment::run);

                    // Once the ThreadedAssignment says it is finished - we ask it to deleteLater
                    // This is a queued connection so that it is put into the event loop to be processed by the worker
                    // thread when it is ready.
                    connect(_currentAssignment.data(), &ThreadedAssignment::finished, _currentAssignment.data(),
                            &ThreadedAssignment::deleteLater, Qt::QueuedConnection);

                    // once it is deleted, we quit the worker thread
                    connect(_currentAssignment.data(), &ThreadedAssignment::destroyed, workerThread, &QThread::quit);

                    // have the worker thread remove itself once it is done
                    connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater);

                    // once the worker thread says it is done, we consider the assignment completed
                    connect(workerThread, &QThread::destroyed, this, &AssignmentClient::assignmentCompleted);

                    _currentAssignment->moveToThread(workerThread);

                    // move the NodeList to the thread used for the _current assignment
                    nodeList->moveToThread(workerThread);

                    // let the assignment handle the incoming datagrams for its duration
                    disconnect(&nodeList->getNodeSocket(), 0, this, 0);
                    connect(&nodeList->getNodeSocket(), &QUdpSocket::readyRead, _currentAssignment.data(),
                            &ThreadedAssignment::readPendingDatagrams);

                    // Starts an event loop, and emits workerThread->started()
                    workerThread->start();
                } else {
                    qDebug() << "Received an assignment that could not be unpacked. Re-requesting.";
                }
            } else if (packetTypeForPacket(receivedPacket) == PacketTypeStopNode) {
                if (senderSockAddr.getAddress() == QHostAddress::LocalHost ||
                    senderSockAddr.getAddress() == QHostAddress::LocalHostIPv6) {
                    qDebug() << "AssignmentClientMonitor at" << senderSockAddr << "requested stop via PacketTypeStopNode.";

                    QCoreApplication::quit();
                } else {
                    qDebug() << "Got a stop packet from other than localhost.";
                }
            } else {
                // have the NodeList attempt to handle it
                nodeList->processNodeData(senderSockAddr, receivedPacket);
            }
        }
    }
}
示例#12
0
MainWidget::MainWidget( QWidget *parent )
: QSplitter( Qt::Horizontal, parent )
, mpKryptonite( new Kryptonite() )
, mpAmazonDE( new KryptoniteJobCoverAmazonDE( mpKryptonite ) )
, mpDiscogs( new KryptoniteJobCoverDiscogs( mpKryptonite ) )
, mpLayout( new QGridLayout( this ) )
, mpFileSysTree( new QTreeView( this ) )
, mpFileSysModel( new QFileSystemModel( this ) )
, mpLineEdit( new QLineEdit( this ) )
, mpFollowPartyman( new QCheckBox( tr("Follow Partyman"), this ) )
, mpCopyBuffer( new QPushButton( tr("Copy debug buffer to clipboard"), this ) )
, mpImage( new DropImageWidget( this ) )
, mpInfo( new QListWidget( this ) )
, mpSignalMapper( new QSignalMapper( this ) )
, mDataMap()
, mCacheMap()
, mDebugData()
{
   mpKryptonite->setObjectName( "Downloader");
   mpAmazonDE->setObjectName( "Amazon" );
   mpDiscogs->setObjectName( "Discogs" );
   mpFileSysTree->setObjectName( "FileSysTree" );
   mpFileSysModel->setObjectName( "FileSysModel" );
   mpLineEdit->setObjectName( "LineInput" );
   mpFollowPartyman->setObjectName( "FollowPartyman" );
   mpFollowPartyman->setChecked( true );
   mpCopyBuffer->setObjectName( "CopyBuffer" );
   mpImage->setObjectName( "Image" );
   mpInfo->setObjectName( "Info" );
   QThread *t = new QThread();
   connect( qApp, SIGNAL(aboutToQuit()),
            t, SLOT(quit()) );
   ProxyWidget::setProxy( mpKryptonite->networkAccessManager() );
   mpKryptonite->moveToThread( t );
   mpAmazonDE->moveToThread( t );
   mpDiscogs->moveToThread( t );
   t->setObjectName( "DownloadThread" );
   t->start();
   QWidget *w = 0;
   mpFileSysTree->setModel( mpFileSysModel );
   mpFileSysModel->setRootPath( "/" );
   mpFileSysModel->setFilter( QDir::NoDotAndDotDot | QDir::AllDirs );
   const QString current( Settings::value( Settings::RubberbandmanRootDirectory ) );
   QModelIndex qmi( mpFileSysModel->index( current ) );
   if( qmi.isValid() )
   {
      mpFileSysTree->setRootIndex( qmi );
      mpFileSysTree->setCurrentIndex( mpFileSysModel->index( current ) );
   }
   mpFileSysTree->header()->hide();
   mpFileSysTree->setColumnHidden( 1, true );
   mpFileSysTree->setColumnHidden( 2, true );
   mpFileSysTree->setColumnHidden( 3, true );

   QSplitter *s = new QSplitter( Qt::Vertical, this );
   w = new QWidget( this );
   QVBoxLayout *v = new QVBoxLayout( w );
   v->addWidget( mpFileSysTree );
   v->addWidget( mpLineEdit );
   QHBoxLayout *h = new QHBoxLayout();
   v->addLayout( h );
   h->addWidget( mpFollowPartyman );
   h->addWidget( mpCopyBuffer );
   s->addWidget( w );
   w = new QWidget( this );
   w->setLayout( mpLayout );
   s->addWidget( w );
   addWidget( s );
   w = new QWidget( this );
   v = new QVBoxLayout( w );
   v->addWidget( mpImage );
   v->addWidget( mpInfo );
   addWidget( w );
   v->setStretch( 0, 1 );
   Satellite *satellite = Satellite::get();

   connect( mpImage, SIGNAL(droppedUrl(QUrl)),
            this, SLOT(saveImage(QUrl)) );
   connect( mpCopyBuffer, SIGNAL(clicked()),
            this, SLOT(debugBufferToClipboard()) );
   connect( mpLineEdit, SIGNAL(returnPressed()),
            this, SLOT(requestFromLine()) );
   connect( mpFileSysTree, SIGNAL(clicked(QModelIndex)),
            this, SLOT(entryClicked(QModelIndex)) );
   connect( mpSignalMapper, SIGNAL(mapped(QWidget*)),
            this, SLOT(saveImage(QWidget*)) );
   connect( this, SIGNAL(requestSearch(QString)),
            mpDiscogs, SLOT(requestList(QString)) );
   connect( mpDiscogs, SIGNAL(imageFound(QByteArray,QVariant)),
            this, SLOT(addThumbnail(QByteArray,QVariant)) );
   connect( mpDiscogs, SIGNAL(imageDownloaded(QByteArray,QVariant)),
            this, SLOT(showImage(QByteArray,QVariant)) );
   connect( mpDiscogs, SIGNAL(message(QString,QByteArray)),
            this, SLOT(message(QString,QByteArray)) );
   connect( this, SIGNAL(requestSearch(QString)),
            mpAmazonDE, SLOT(requestList(QString)) );
   connect( mpAmazonDE, SIGNAL(imageFound(QByteArray,QVariant)),
            this, SLOT(addThumbnail(QByteArray,QVariant)) );
   connect( mpAmazonDE, SIGNAL(imageDownloaded(QByteArray,QVariant)),
            this, SLOT(showImage(QByteArray,QVariant)) );
   connect( mpAmazonDE, SIGNAL(message(QString,QByteArray)),
            this, SLOT(message(QString,QByteArray)) );
   connect( satellite, SIGNAL(received(QByteArray)),
            this, SLOT(handleSatelliteMessage(QByteArray)) );

   QList<int> sizes;
   sizes << 30 << 300;
   s->setSizes( sizes );
}
示例#13
0
void AssignmentClient::readPendingDatagrams() {
    NodeList* nodeList = NodeList::getInstance();

    static unsigned char packetData[1500];
    static qint64 receivedBytes = 0;
    static HifiSockAddr senderSockAddr;

    while (nodeList->getNodeSocket().hasPendingDatagrams()) {

        if ((receivedBytes = nodeList->getNodeSocket().readDatagram((char*) packetData, MAX_PACKET_SIZE,
                             senderSockAddr.getAddressPointer(),
                             senderSockAddr.getPortPointer()))
                && packetVersionMatch(packetData)) {

            if (_currentAssignment) {
                // have the threaded current assignment handle this datagram
                QMetaObject::invokeMethod(_currentAssignment, "processDatagram", Qt::QueuedConnection,
                                          Q_ARG(QByteArray, QByteArray((char*) packetData, receivedBytes)),
                                          Q_ARG(HifiSockAddr, senderSockAddr));
            } else if (packetData[0] == PACKET_TYPE_DEPLOY_ASSIGNMENT || packetData[0] == PACKET_TYPE_CREATE_ASSIGNMENT) {

                if (_currentAssignment) {
                    qDebug() << "Dropping received assignment since we are currently running one.\n";
                } else {
                    // construct the deployed assignment from the packet data
                    _currentAssignment = AssignmentFactory::unpackAssignment(packetData, receivedBytes);

                    qDebug() << "Received an assignment -" << *_currentAssignment << "\n";

                    // switch our nodelist domain IP and port to whoever sent us the assignment
                    if (packetData[0] == PACKET_TYPE_CREATE_ASSIGNMENT) {
                        nodeList->setDomainSockAddr(senderSockAddr);
                        nodeList->setOwnerUUID(_currentAssignment->getUUID());

                        qDebug("Destination IP for assignment is %s\n",
                               nodeList->getDomainIP().toString().toStdString().c_str());

                        // start the deployed assignment
                        QThread* workerThread = new QThread(this);

                        connect(workerThread, SIGNAL(started()), _currentAssignment, SLOT(run()));

                        connect(_currentAssignment, SIGNAL(finished()), this, SLOT(assignmentCompleted()));
                        connect(_currentAssignment, SIGNAL(finished()), workerThread, SLOT(quit()));
                        connect(_currentAssignment, SIGNAL(finished()), _currentAssignment, SLOT(deleteLater()));
                        connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater()));

                        _currentAssignment->moveToThread(workerThread);

                        // Starts an event loop, and emits workerThread->started()
                        workerThread->start();
                    } else {
                        qDebug("Received a bad destination socket for assignment.\n");
                    }
                }
            } else {
                // have the NodeList attempt to handle it
                nodeList->processNodeData(senderSockAddr, packetData, receivedBytes);
            }
        }
    }
}
PointViewerMainWindow::PointViewerMainWindow(const QGLFormat& format)
    : m_progressBar(0),
    m_pointView(0),
    m_shaderEditor(0),
    m_helpDialog(0),
    m_logTextView(0),
    m_maxPointCount(200*1000*1000), // 200 million
    m_geometries(0),
    m_ipcServer(0),
    m_hookManager(0)
{
#ifndef _WIN32
    setWindowIcon(QIcon(":resource/icons/hicolor/256x256/apps/displaz.png"));
#else
    // On windows, application icon is set via windows resource file
#endif
    setWindowTitle("Displaz");
    setAcceptDrops(true);

    m_helpDialog = new HelpDialog(this);

    m_geometries = new GeometryCollection(this);
    connect(m_geometries, SIGNAL(layoutChanged()), this, SLOT(updateTitle()));
    connect(m_geometries, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(updateTitle()));
    connect(m_geometries, SIGNAL(rowsInserted(QModelIndex,int,int)),    this, SLOT(updateTitle()));
    connect(m_geometries, SIGNAL(rowsRemoved(QModelIndex,int,int)),     this, SLOT(updateTitle()));

    //--------------------------------------------------
    // Set up file loader in a separate thread
    //
    // Some subtleties regarding qt thread usage are discussed here:
    // http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation
    //
    // Main point: each QObject has a thread affinity which determines which
    // thread its slots will execute on, when called via a connected signal.
    QThread* loaderThread = new QThread();
    m_fileLoader = new FileLoader(m_maxPointCount);
    m_fileLoader->moveToThread(loaderThread);
    connect(loaderThread, SIGNAL(finished()), m_fileLoader, SLOT(deleteLater()));
    connect(loaderThread, SIGNAL(finished()), loaderThread, SLOT(deleteLater()));
    //connect(m_fileLoader, SIGNAL(finished()), this, SIGNAL(fileLoadFinished()));
    connect(m_fileLoader, SIGNAL(geometryLoaded(std::shared_ptr<Geometry>, bool, bool)),
            m_geometries, SLOT(addGeometry(std::shared_ptr<Geometry>, bool, bool)));
    connect(m_fileLoader, SIGNAL(geometryMutatorLoaded(std::shared_ptr<GeometryMutator>)),
            m_geometries, SLOT(mutateGeometry(std::shared_ptr<GeometryMutator>)));
    loaderThread->start();

    //--------------------------------------------------
    // Menus
    menuBar()->setNativeMenuBar(false); // OS X doesn't activate the native menu bar under Qt5

    // File menu
    QMenu* fileMenu = menuBar()->addMenu(tr("&File"));
    QAction* openAct = fileMenu->addAction(tr("&Open"));
    openAct->setToolTip(tr("Open a data set"));
    openAct->setShortcuts(QKeySequence::Open);
    connect(openAct, SIGNAL(triggered()), this, SLOT(openFiles()));
    QAction* addAct = fileMenu->addAction(tr("&Add"));
    addAct->setToolTip(tr("Add a data set"));
    connect(addAct, SIGNAL(triggered()), this, SLOT(addFiles()));
    QAction* reloadAct = fileMenu->addAction(tr("&Reload"));
    reloadAct->setStatusTip(tr("Reload point files from disk"));
    reloadAct->setShortcut(Qt::Key_F5);
    connect(reloadAct, SIGNAL(triggered()), this, SLOT(reloadFiles()));

    fileMenu->addSeparator();
    QAction* screenShotAct = fileMenu->addAction(tr("Scree&nshot"));
    screenShotAct->setStatusTip(tr("Save screen shot of 3D window"));
    screenShotAct->setShortcut(Qt::Key_F9);
    connect(screenShotAct, SIGNAL(triggered()), this, SLOT(screenShot()));

    fileMenu->addSeparator();
    QAction* quitAct = fileMenu->addAction(tr("&Quit"));
    quitAct->setStatusTip(tr("Exit the application"));
    quitAct->setShortcuts(QKeySequence::Quit);
    connect(quitAct, SIGNAL(triggered()), this, SLOT(close()));

    // View menu
    QMenu* viewMenu = menuBar()->addMenu(tr("&View"));
    QAction* trackballMode = viewMenu->addAction(tr("Use &Trackball camera"));
    trackballMode->setCheckable(true);
    trackballMode->setChecked(false);
    // Background sub-menu
    QMenu* backMenu = viewMenu->addMenu(tr("Set &Background"));
    QSignalMapper* mapper = new QSignalMapper(this);
    // Selectable backgrounds (svg_names from SVG standard - see QColor docs)
    const char* backgroundNames[] = {/* "Display Name", "svg_name", */
                                        "Default",      "#3C3232",
                                        "Black",        "black",
                                        "Dark Grey",    "dimgrey",
                                        "Slate Grey",   "#858C93",
                                        "Light Grey",   "lightgrey",
                                        "White",        "white" };
    for(size_t i = 0; i < sizeof(backgroundNames)/sizeof(const char*); i+=2)
    {
        QAction* backgroundAct = backMenu->addAction(tr(backgroundNames[i]));
        QPixmap pixmap(50,50);
        QString colName = backgroundNames[i+1];
        pixmap.fill(QColor(colName));
        QIcon icon(pixmap);
        backgroundAct->setIcon(icon);
        mapper->setMapping(backgroundAct, colName);
        connect(backgroundAct, SIGNAL(triggered()), mapper, SLOT(map()));
    }
    connect(mapper, SIGNAL(mapped(QString)),
            this, SLOT(setBackground(QString)));
    backMenu->addSeparator();
    QAction* backgroundCustom = backMenu->addAction(tr("&Custom"));
    connect(backgroundCustom, SIGNAL(triggered()),
            this, SLOT(chooseBackground()));
    // Check boxes for drawing various scene elements by category
    viewMenu->addSeparator();
    QAction* drawBoundingBoxes = viewMenu->addAction(tr("Draw Bounding bo&xes"));
    drawBoundingBoxes->setCheckable(true);
    drawBoundingBoxes->setChecked(false);
    QAction* drawCursor = viewMenu->addAction(tr("Draw 3D &Cursor"));
    drawCursor->setCheckable(true);
    drawCursor->setChecked(true);
    QAction* drawAxes = viewMenu->addAction(tr("Draw &Axes"));
    drawAxes->setCheckable(true);
    drawAxes->setChecked(true);
    QAction* drawGrid = viewMenu->addAction(tr("Draw &Grid"));
    drawGrid->setCheckable(true);
    drawGrid->setChecked(false);
    QAction* drawAnnotations = viewMenu->addAction(tr("Draw A&nnotations"));
    drawAnnotations->setCheckable(true);
    drawAnnotations->setChecked(true);

    // Shader menu
    QMenu* shaderMenu = menuBar()->addMenu(tr("&Shader"));
    QAction* openShaderAct = shaderMenu->addAction(tr("&Open"));
    openShaderAct->setToolTip(tr("Open a shader file"));
    connect(openShaderAct, SIGNAL(triggered()), this, SLOT(openShaderFile()));
    QAction* editShaderAct = shaderMenu->addAction(tr("&Edit"));
    editShaderAct->setToolTip(tr("Open shader editor window"));
    QAction* saveShaderAct = shaderMenu->addAction(tr("&Save"));
    saveShaderAct->setToolTip(tr("Save current shader file"));
    connect(saveShaderAct, SIGNAL(triggered()), this, SLOT(saveShaderFile()));
    shaderMenu->addSeparator();

    // Help menu
    QMenu* helpMenu = menuBar()->addMenu(tr("&Help"));
    QAction* helpAct = helpMenu->addAction(tr("User &Guide"));
    connect(helpAct, SIGNAL(triggered()), this, SLOT(helpDialog()));
    helpMenu->addSeparator();
    QAction* aboutAct = helpMenu->addAction(tr("&About"));
    connect(aboutAct, SIGNAL(triggered()), this, SLOT(aboutDialog()));


    //--------------------------------------------------
    // Point viewer
    m_pointView = new View3D(m_geometries, format, this);
    setCentralWidget(m_pointView);
    connect(drawBoundingBoxes, SIGNAL(triggered()),
            m_pointView, SLOT(toggleDrawBoundingBoxes()));
    connect(drawCursor, SIGNAL(triggered()),
            m_pointView, SLOT(toggleDrawCursor()));
    connect(drawAxes, SIGNAL(triggered()),
            m_pointView, SLOT(toggleDrawAxes()));
    connect(drawGrid, SIGNAL(triggered()),
            m_pointView, SLOT(toggleDrawGrid()));
    connect(drawAnnotations, SIGNAL(triggered()),
            m_pointView, SLOT(toggleDrawAnnotations()));
    connect(trackballMode, SIGNAL(triggered()),
            m_pointView, SLOT(toggleCameraMode()));
    connect(m_geometries, SIGNAL(rowsInserted(QModelIndex,int,int)),
            this, SLOT(geometryRowsInserted(QModelIndex,int,int)));

    //--------------------------------------------------
    // Docked widgets
    // Shader parameters UI
    QDockWidget* shaderParamsDock = new QDockWidget(tr("Shader Parameters"), this);
    shaderParamsDock->setFeatures(QDockWidget::DockWidgetMovable |
                                  QDockWidget::DockWidgetClosable);
    QWidget* shaderParamsUI = new QWidget(shaderParamsDock);
    shaderParamsDock->setWidget(shaderParamsUI);
    m_pointView->setShaderParamsUIWidget(shaderParamsUI);

    // Shader editor UI
    QDockWidget* shaderEditorDock = new QDockWidget(tr("Shader Editor"), this);
    shaderEditorDock->setFeatures(QDockWidget::DockWidgetMovable |
                                  QDockWidget::DockWidgetClosable |
                                  QDockWidget::DockWidgetFloatable);
    QWidget* shaderEditorUI = new QWidget(shaderEditorDock);
    m_shaderEditor = new ShaderEditor(shaderEditorUI);
    QGridLayout* shaderEditorLayout = new QGridLayout(shaderEditorUI);
    shaderEditorLayout->setContentsMargins(2,2,2,2);
    shaderEditorLayout->addWidget(m_shaderEditor, 0, 0, 1, 1);
    connect(editShaderAct, SIGNAL(triggered()), shaderEditorDock, SLOT(show()));
    shaderEditorDock->setWidget(shaderEditorUI);

    shaderMenu->addAction(m_shaderEditor->compileAction());
    connect(m_shaderEditor->compileAction(), SIGNAL(triggered()),
            this, SLOT(compileShaderFile()));

    // TODO: check if this is needed - test shader update functionality
    //connect(m_shaderEditor, SIGNAL(sendShader(QString)),
    //        &m_pointView->shaderProgram(), SLOT(setShader(QString)));

    // Log viewer UI
    QDockWidget* logDock = new QDockWidget(tr("Log"), this);
    logDock->setFeatures(QDockWidget::DockWidgetMovable |
                         QDockWidget::DockWidgetClosable);
    QWidget* logUI = new QWidget(logDock);
    m_logTextView = new LogViewer(logUI);
    m_logTextView->setReadOnly(true);
    m_logTextView->setTextInteractionFlags(Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse);
    m_logTextView->connectLogger(&g_logger); // connect to global logger
    m_progressBar = new QProgressBar(logUI);
    m_progressBar->setRange(0,100);
    m_progressBar->setValue(0);
    m_progressBar->hide();
    connect(m_fileLoader, SIGNAL(loadStepStarted(QString)),
            this, SLOT(setProgressBarText(QString)));
    connect(m_fileLoader, SIGNAL(loadProgress(int)),
            m_progressBar, SLOT(setValue(int)));
    connect(m_fileLoader, SIGNAL(resetProgress()),
            m_progressBar, SLOT(hide()));
    QVBoxLayout* logUILayout = new QVBoxLayout(logUI);
    //logUILayout->setContentsMargins(2,2,2,2);
    logUILayout->addWidget(m_logTextView);
    logUILayout->addWidget(m_progressBar);
    //m_logTextView->setLineWrapMode(QPlainTextEdit::NoWrap);
    logDock->setWidget(logUI);

    // Data set list UI
    QDockWidget* dataSetDock = new QDockWidget(tr("Data Sets"), this);
    dataSetDock->setFeatures(QDockWidget::DockWidgetMovable |
                              QDockWidget::DockWidgetClosable |
                              QDockWidget::DockWidgetFloatable);
    DataSetUI* dataSetUI = new DataSetUI(this);
    dataSetDock->setWidget(dataSetUI);
    QAbstractItemView* dataSetOverview = dataSetUI->view();
    dataSetOverview->setModel(m_geometries);
    connect(dataSetOverview, SIGNAL(doubleClicked(const QModelIndex&)),
            m_pointView, SLOT(centerOnGeometry(const QModelIndex&)));
    m_pointView->setSelectionModel(dataSetOverview->selectionModel());

    // Set up docked widgets
    addDockWidget(Qt::RightDockWidgetArea, shaderParamsDock);
    addDockWidget(Qt::LeftDockWidgetArea, shaderEditorDock);
    addDockWidget(Qt::RightDockWidgetArea, logDock);
    addDockWidget(Qt::RightDockWidgetArea, dataSetDock);
    tabifyDockWidget(logDock, dataSetDock);
    logDock->raise();
    shaderEditorDock->setVisible(false);

    // Add dock widget toggles to view menu
    viewMenu->addSeparator();
    viewMenu->addAction(shaderParamsDock->toggleViewAction());
    viewMenu->addAction(logDock->toggleViewAction());
    viewMenu->addAction(dataSetDock->toggleViewAction());

    // Create custom hook events from CLI at runtime
    m_hookManager = new HookManager(this);
}
示例#15
0
Q_DECL_EXPORT int main(int argc, char *argv[])
{
#ifdef Q_OS_LINUX
	QApplication::setAttribute(Qt::AA_X11InitThreads, true);
#endif
	QApplication a(argc, argv);
	QSize res = QApplication::desktop()->screenGeometry().size();
	if (res.width() < res.height())
		res.transpose();
	pixel_xres = res.width();
	pixel_yres = res.height();
	g_dpi_scale = CalculateDPIScale();
	dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale);
	net::Init();
#ifdef __SYMBIAN32__
	const char *savegame_dir = "E:/PPSSPP/";
	const char *assets_dir = "E:/PPSSPP/";
#elif defined(BLACKBERRY)
	const char *savegame_dir = "/accounts/1000/shared/misc/";
	const char *assets_dir = "app/native/assets/";
#elif defined(MEEGO_EDITION_HARMATTAN)
	const char *savegame_dir = "/home/user/MyDocs/PPSSPP/";
	QDir myDocs("/home/user/MyDocs/");
	if (!myDocs.exists("PPSSPP"))
		myDocs.mkdir("PPSSPP");
	const char *assets_dir = "/opt/PPSSPP/";
#else
	const char *savegame_dir = "./";
	const char *assets_dir = "./";
#endif
	NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE");

#if !defined(Q_OS_LINUX) || defined(ARM)
	MainUI w;
	w.resize(pixel_xres, pixel_yres);
#ifdef ARM
	w.showFullScreen();
#else
	w.show();
#endif
#endif
#ifdef __SYMBIAN32__
	// Set RunFast hardware mode for VFPv2.
	User::SetFloatingPointMode(EFpModeRunFast);
	// Disable screensaver
	QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w);
	ssObject->setScreenSaverInhibit();
	SymbianMediaKeys* mediakeys = new SymbianMediaKeys();
#endif

	QThread* thread = new QThread;
	MainAudio *audio = new MainAudio();
	audio->moveToThread(thread);
	QObject::connect(thread, SIGNAL(started()), audio, SLOT(run()));
	QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
	thread->start();

	int ret = a.exec();
	delete audio;
	thread->quit();
	NativeShutdown();
	net::Shutdown();
	return ret;
}
示例#16
0
void QgsLocator::fetchResults( const QString &string, const QgsLocatorContext &c, QgsFeedback *feedback )
{
  QgsLocatorContext context( c );
  // ideally this should not be required, as well behaved callers
  // will NOT fire up a new fetchResults call while an existing one is
  // operating/waiting to be canceled...
  cancelRunningQuery();

  // if no feedback object was passed, create one that is owned by this object
  // to ensure that filters ALWAYS receive a valid feedback
  if ( !feedback )
  {
    mOwnedFeedback.reset( new QgsFeedback() );
    feedback = mOwnedFeedback.get();
  }
  else
  {
    mOwnedFeedback.reset( nullptr );
  }
  mFeedback = feedback;

  QList< QgsLocatorFilter * > activeFilters;
  QString searchString = string;
  QString prefix = searchString.left( std::max( searchString.indexOf( ' ' ), 0 ) );
  if ( !prefix.isEmpty() )
  {
    for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) )
    {
      if ( filter->activePrefix() == prefix && filter->enabled() )
      {
        activeFilters << filter;
      }
    }
    context.usingPrefix = !activeFilters.empty();
  }
  if ( !activeFilters.isEmpty() )
  {
    searchString = searchString.mid( prefix.length() + 1 );
  }
  else
  {
    for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) )
    {
      if ( filter->useWithoutPrefix() && filter->enabled() )
      {
        activeFilters << filter;
      }
    }
  }

  QList< QgsLocatorFilter *> threadedFilters;
  for ( QgsLocatorFilter *filter : qgis::as_const( activeFilters ) )
  {
    filter->clearPreviousResults();
    std::unique_ptr< QgsLocatorFilter > clone( filter->clone() );
    connect( clone.get(), &QgsLocatorFilter::resultFetched, clone.get(), [this, filter]( QgsLocatorResult result )
    {
      result.filter = filter;
      emit filterSentResult( result );
    } );
    clone->prepare( searchString, context );

    if ( clone->flags() & QgsLocatorFilter::FlagFast )
    {
      // filter is fast enough to fetch results on the main thread
      clone->fetchResults( searchString, context, feedback );
    }
    else
    {
      // run filter in background
      threadedFilters.append( clone.release() );
    }
  }

  mActiveThreads.clear();
  for ( QgsLocatorFilter *filter : qgis::as_const( threadedFilters ) )
  {
    QThread *thread = new QThread();
    mActiveThreads.append( thread );
    filter->moveToThread( thread );
    connect( thread, &QThread::started, filter, [filter, searchString, context, feedback]
    {
      if ( !feedback->isCanceled() )
        filter->fetchResults( searchString, context, feedback );
      filter->emit finished();
    }, Qt::QueuedConnection );
    connect( filter, &QgsLocatorFilter::finished, thread, &QThread::quit );
    connect( filter, &QgsLocatorFilter::finished, filter, &QgsLocatorFilter::deleteLater );
    connect( thread, &QThread::finished, thread, [this, thread]
    {
      mActiveThreads.removeAll( thread );
      if ( mActiveThreads.empty() )
        emit finished();
    } );
    connect( thread, &QThread::finished, thread, &QThread::deleteLater );
    thread->start();
  }

  if ( mActiveThreads.empty() )
    emit finished();
}
示例#17
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //about window
    this->aboutWindow = new AboutWindow();
    this->aboutWindow->hide();
    this->aboutWindow->move(this->geometry().center()-this->aboutWindow->geometry().center());
    //calibrate Dialog
    this->calibrateDialog = new CalibrateDialog();
    this->calibrateDialog->hide();
    this->calibrateDialog->move(this->geometry().center()-this->calibrateDialog->geometry().center());
    //option Dialog
    this->optionDialog = new OptionDialog();
    this->optionDialog->hide();
    this->optionDialog->move(this->geometry().center()-this->optionDialog->geometry().center());
    //slice dialog
    this->sliceDialog = new SliceDialog(ui->glWidget, this);
    this->sliceDialog->hide();
    this->sliceDialog->move(this->geometry().center()-this->sliceDialog->geometry().center());
    //macros window
    this->macrosWindow = new MacrosWindow();
    this->macrosWindow->hide();
    this->macrosWindow->move(this->geometry().center()-this->macrosWindow->geometry().center());
    connect(this->macrosWindow, SIGNAL(buttonAdded(MacroButton*)), this, SLOT(addMacroBtn(MacroButton*)));
    connect(this->macrosWindow, SIGNAL(buttonRemoved(MacroButton*)), this, SLOT(removeMacroBtn(MacroButton*)));
    //sd card window
    this->sdCardWindow = new SDCardWindow();
    this->sdCardWindow->hide();
    this->sdCardWindow->move(this->geometry().center()-this->sdCardWindow->geometry().center());
    connect(this->sdCardWindow, SIGNAL(sdFile_selected(QString)), this, SLOT(sdFile_selected(QString)));
    connect(this->optionDialog, SIGNAL(slicerPathChanged(QString)), this->sliceDialog, SLOT(updateSlicerPath(QString)));
    connect(this->optionDialog, SIGNAL(outputPathChanged(QString)), this->sliceDialog, SLOT(updateOutputPath(QString)));
    connect(this->optionDialog, SIGNAL(newSize(QVector3D)), this, SLOT(updatadeSize(QVector3D)));
    connect(this->optionDialog, SIGNAL(newList(QList<Material*>*)), this->sliceDialog, SLOT(setMaterialList(QList<Material*>*)));
    connect(this->sliceDialog, SIGNAL(fileSliced(QString)), this, SLOT(loadFile(QString)));
    //set version number
    this->setWindowTitle("YARRH v"+QString::number(VERSION_MAJOR)+"."+QString::number(VERSION_MINOR)+"."+QString::number(VERSION_REVISION));
    this->aboutWindow->setVersion(VERSION_MAJOR,VERSION_MINOR,VERSION_REVISION);
    //setting up printer and its thread
    this->printerObj = new Printer();
    QThread *qthread = new QThread();

    //connecting ui to printer
    connect(printerObj, SIGNAL(write_to_console(QString)), ui->inConsole, SLOT(appendPlainText(QString)), Qt::QueuedConnection);
    connect(this->macrosWindow, SIGNAL(writeToPrinter(QString)), printerObj, SLOT(send_now(QString)),Qt::QueuedConnection);
    connect(ui->fanSpinBox, SIGNAL(valueChanged(int)), printerObj, SLOT(setFan(int)), Qt::QueuedConnection);
    ui->fanSpinBox->blockSignals(true);
    connect(this->printerObj, SIGNAL(SDFileList(QStringList)), this->sdCardWindow, SLOT(updateFileList(QStringList)));
    connect(this->printerObj, SIGNAL(uploadProgress(int,int)), this->sdCardWindow, SLOT(updateProgress(int,int)));
    this->sdCardWindow->setPrinter(this->printerObj);
    //connecting move btns
    connect(ui->homeX, SIGNAL(clicked()), printerObj, SLOT(homeX()), Qt::QueuedConnection);
    connect(ui->homeY, SIGNAL(clicked()), printerObj, SLOT(homeY()), Qt::QueuedConnection);
    connect(ui->homeAll, SIGNAL(clicked()), printerObj, SLOT(homeAll()), Qt::QueuedConnection);
    //connect monit temp checkbox
    connect(ui->graphGroupBox, SIGNAL(toggled(bool)), printerObj, SLOT(setMonitorTemperature(bool)),Qt::QueuedConnection);
    //connect printer to temp widget
    connect(printerObj, SIGNAL(currentTemp(double,double,double)), this, SLOT(drawTemp(double,double,double)));
    connect(printerObj, SIGNAL(progress(int,int)), this, SLOT(updateProgress(int,int)));
    connect(printerObj, SIGNAL(connected(bool)), this, SLOT(printerConnected(bool)));
    //setting ui temp from gcode
    connect(printerObj, SIGNAL(settingTemp1(double)), this, SLOT(setTemp1FromGcode(double)));
    connect(printerObj, SIGNAL(settingTemp3(double)), this, SLOT(setTemp3FromGcode(double)));
    //updating head position in ui
    connect(printerObj, SIGNAL(currentPosition(QVector3D)), this, SLOT(updateHeadPosition(QVector3D)));
    //print finished signal
    connect(printerObj, SIGNAL(printFinished(bool)), this, SLOT(printFinished(bool)));
    //connect calibration dialog to printer
    connect(calibrateDialog, SIGNAL(writeToPrinter(QString)), printerObj, SLOT(send_now(QString)),Qt::QueuedConnection);
    //connect z slider
    connect(ui->zSlider, SIGNAL(valueChanged(int)), this, SLOT(moveZ(int)));
    connect(ui->zSlider, SIGNAL(sliderMoved(int)), this, SLOT(updateZ(int)));
    //connect action load
    connect(ui->actionLoad, SIGNAL(triggered()), this, SLOT(loadFile()));

    printerObj->moveToThread(qthread);
    qthread->start(QThread::HighestPriority);


    this->portEnum = new QextSerialEnumerator(this);
    this->portEnum->setUpNotifications();
    QList<QextPortInfo> ports = this->portEnum->getPorts();
    //finding avalible ports
    foreach (QextPortInfo info, ports) {
        ui->portCombo->addItem(info.portName);
    }
示例#18
0
void NzmqtTest::testReqRep()
{
    try {
        QScopedPointer<ZMQContext> context(nzmqt::createDefaultContext());

        // Create replier.
        samples::reqrep::Replier* replier = new samples::reqrep::Replier(*context, "inproc://reqrep", "world");
        QSignalSpy spyReplierRequestReceived(replier, SIGNAL(requestReceived(const QList<QByteArray>&)));
        QSignalSpy spyReplierReplySent(replier, SIGNAL(replySent(const QList<QByteArray>&)));
        QSignalSpy spyReplierFailure(replier, SIGNAL(failure(const QString&)));
        QSignalSpy spyReplierFinished(replier, SIGNAL(finished()));
        // Create replier execution thread.
        QThread* replierThread = makeExecutionThread(*replier);
        QSignalSpy spyReplierThreadFinished(replierThread, SIGNAL(finished()));

        // Create requester.
        samples::reqrep::Requester* requester = new samples::reqrep::Requester(*context, "inproc://reqrep", "hello");
        QSignalSpy spyRequesterRequestSent(requester, SIGNAL(requestSent(const QList<QByteArray>&)));
        QSignalSpy spyRequesterReplyReceived(requester, SIGNAL(replyReceived(const QList<QByteArray>&)));
        QSignalSpy spyRequesterFailure(requester, SIGNAL(failure(const QString&)));
        QSignalSpy spyRequesterFinished(requester, SIGNAL(finished()));
        // Create requester execution thread.
        QThread* requesterThread = makeExecutionThread(*requester);
        QSignalSpy spyRequesterThreadFinished(requesterThread, SIGNAL(finished()));

        //
        // START TEST
        //

        context->start();

        replierThread->start();
        QTest::qWait(500);
        requesterThread->start();

        QTimer::singleShot(6000, replier, SLOT(stop()));
        QTimer::singleShot(6000, requester, SLOT(stop()));

        QTest::qWait(8000);

        //
        // CHECK POSTCONDITIONS
        //

        qDebug() << "Requester requests sent:" << spyRequesterRequestSent.size();
        qDebug() << "Replier requests received:" << spyReplierRequestReceived.size();

        QCOMPARE(spyReplierFailure.size(), 0);
        QCOMPARE(spyRequesterFailure.size(), 0);

        QVERIFY2(spyRequesterRequestSent.size() > 3, "Requester didn't send any/enough requests.");
        QCOMPARE(spyRequesterReplyReceived.size(), spyRequesterRequestSent.size());

        QCOMPARE(spyReplierRequestReceived.size(), spyRequesterRequestSent.size());
        QCOMPARE(spyReplierReplySent.size(), spyReplierRequestReceived.size());

        QCOMPARE(spyReplierFinished.size(), 1);
        QCOMPARE(spyRequesterFinished.size(), 1);

        QCOMPARE(spyReplierThreadFinished.size(), 1);
        QCOMPARE(spyRequesterThreadFinished.size(), 1);
    }
    catch (std::exception& ex)
    {
        QFAIL(ex.what());
    }
}
示例#19
0
 void start()
 {
     m_widget.blockGUI(true);
     worker->moveToThread(thread);
     thread->start();
 }
示例#20
0
void NzmqtTest::testPushPull()
{
    try {
        QScopedPointer<ZMQContext> context(nzmqt::createDefaultContext());

        // Create ventilator.
        samples::pushpull::Ventilator* ventilator = new samples::pushpull::Ventilator(*context, "tcp://127.0.0.1:5557", "tcp://127.0.0.1:5558", 200);
        QSignalSpy spyVentilatorBatchStarted(ventilator, SIGNAL(batchStarted(int)));
        QSignalSpy spyVentilatorWorkItemSent(ventilator, SIGNAL(workItemSent(quint32)));
        QSignalSpy spyVentilatorFailure(ventilator, SIGNAL(failure(const QString&)));
        QSignalSpy spyVentilatorFinished(ventilator, SIGNAL(finished()));
        // Create ventilator execution thread.
        QThread* ventilatorThread = makeExecutionThread(*ventilator);
        QSignalSpy spyVentilatorThreadFinished(ventilatorThread, SIGNAL(finished()));

        // Create worker.
        samples::pushpull::Worker* worker = new samples::pushpull::Worker(*context, "tcp://127.0.0.1:5557", "tcp://127.0.0.1:5558");
        QSignalSpy spyWorkerWorkItemReceived(worker, SIGNAL(workItemReceived(quint32)));
        QSignalSpy spyWorkerWorkItemResultSent(worker, SIGNAL(workItemResultSent()));
        QSignalSpy spyWorkerFailure(worker, SIGNAL(failure(const QString&)));
        QSignalSpy spyWorkerFinished(worker, SIGNAL(finished()));
        // Create worker execution thread.
        QThread* workerThread = makeExecutionThread(*worker);
        QSignalSpy spyWorkerThreadFinished(workerThread, SIGNAL(finished()));

        // Create sink.
        samples::pushpull::Sink* sink = new samples::pushpull::Sink(*context, "tcp://127.0.0.1:5558");
        QSignalSpy spySinkBatchStarted(sink, SIGNAL(batchStarted(int)));
        QSignalSpy spySinkWorkItemResultReceived(sink, SIGNAL(workItemResultReceived()));
        QSignalSpy spySinkBatchCompleted(sink, SIGNAL(batchCompleted()));
        QSignalSpy spySinkFailure(sink, SIGNAL(failure(const QString&)));
        QSignalSpy spySinkFinished(sink, SIGNAL(finished()));
        // Create sink execution thread.
        QThread* sinkThread = makeExecutionThread(*sink);
        QSignalSpy spySinkThreadFinished(sinkThread, SIGNAL(finished()));

        //
        // START TEST
        //

        const int numberOfWorkItems = ventilator->numberOfWorkItems();
        const int maxTotalExpectedCost = numberOfWorkItems*ventilator->maxWorkLoad();
        QTimer::singleShot(maxTotalExpectedCost + 2000, ventilator, SLOT(stop()));
        QTimer::singleShot(maxTotalExpectedCost + 2000, worker, SLOT(stop()));
        QTimer::singleShot(maxTotalExpectedCost + 2000, sink, SLOT(stop()));

        context->start();

        sinkThread->start();
        QTest::qWait(500);
        ventilatorThread->start();
        QTest::qWait(500);
        workerThread->start();

        QTest::qWait(maxTotalExpectedCost + 2500);

        //
        // CHECK POSTCONDITIONS
        //

        QCOMPARE(spyVentilatorFailure.size(), 0);
        QCOMPARE(spyWorkerFailure.size(), 0);
        QCOMPARE(spySinkFailure.size(), 0);

        QCOMPARE(spyVentilatorBatchStarted.size(), 1);
        QCOMPARE(spyVentilatorWorkItemSent.size(), numberOfWorkItems);
        QCOMPARE(spyVentilatorFinished.size(), 1);
        QCOMPARE(spyVentilatorThreadFinished.size(), 1);

        QCOMPARE(spyWorkerWorkItemReceived.size(), numberOfWorkItems);
        QCOMPARE(spyWorkerWorkItemResultSent.size(), numberOfWorkItems);
        QCOMPARE(spyWorkerFinished.size(), 1);
        QCOMPARE(spyWorkerThreadFinished.size(), 1);

        QCOMPARE(spySinkBatchStarted.size(), 1);
        QCOMPARE(spySinkWorkItemResultReceived.size(), numberOfWorkItems);
        QCOMPARE(spySinkBatchCompleted.size(), 1);
        QCOMPARE(spySinkFinished.size(), 1);
        QCOMPARE(spySinkThreadFinished.size(), 1);
    }
    catch (std::exception& ex)
    {
        QFAIL(ex.what());
    }
}
示例#21
0
文件: main.cpp 项目: ZackMattor/tis
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    app.setOrganizationName("arksaw");
    app.setApplicationName("tisserver");

    // Initialize settings stuff
    QSettings::setDefaultFormat(QSettings::IniFormat);
    QSettings settings;
    settings.setValue("port", 50000);
    settings.sync();

    Console console;
    Database database;
    SessionManager sessionManager(0, &database);
    GameThread game(0, &database, &sessionManager);
    UdpServer udpServer;

    qRegisterMetaType<Packet>("Packet");
    qRegisterMetaType<QHostAddress>("QHostAddress");
    // Console signals/slots
    QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)),
                     &sessionManager, SLOT(runCommand(CommandType,QStringList)));
    QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)),
                     &game, SLOT(runCommand(CommandType,QStringList)),
                     Qt::DirectConnection); // Need direct connection from cross-thread signals to blocked thread
    QObject::connect(&console, SIGNAL(commandEntered(CommandType,QStringList)),
                     &udpServer, SLOT(runCommand(CommandType,QStringList)));

    // Database signals/slots
    QObject::connect(&database, SIGNAL(writeToConsole(QString)),
                     &console, SLOT(writeLine(QString)),
                     Qt::QueuedConnection);

    // SessionManager signals/slots
    QObject::connect(&sessionManager, SIGNAL(writeToConsole(QString)),
                     &console, SLOT(writeLine(QString)));
    QObject::connect(&sessionManager, SIGNAL(responseReady(Packet,QHostAddress,quint16)),
                     &udpServer, SLOT(sendResponse(Packet,QHostAddress,quint16)), Qt::QueuedConnection);

    // GameThread signals/slots
    QObject::connect(&game, SIGNAL(writeToConsole(QString)),
                     &console, SLOT(writeLine(QString)));
    QObject::connect(&game, SIGNAL(updatePacketReady(Packet)),
                     &sessionManager, SLOT(sendUpdatePacket(Packet)),
                     Qt::QueuedConnection);

    // UdpServer signals/slots
    QObject::connect(&udpServer, SIGNAL(writeToConsole(QString)),
                     &console, SLOT(writeLine(QString)));
    QObject::connect(&udpServer, SIGNAL(packetReceived(Packet,QHostAddress,quint16)),
                     &sessionManager, SLOT(processPacket(Packet,QHostAddress,quint16)),
                     Qt::DirectConnection);

    // Set up threading.
    QThread thread;
    game.moveToThread(&thread);
    thread.start();
    thread.connect(&thread, SIGNAL(finished()), &app, SLOT(quit()));

    // Invoke with Qt::QueuedConnection since the Qt event loop isn't up yet
    QMetaObject::invokeMethod(&database, "init", Qt::QueuedConnection);
    QMetaObject::invokeMethod(&sessionManager, "start", Qt::QueuedConnection);
    QMetaObject::invokeMethod(&game, "start", Qt::QueuedConnection);
    QMetaObject::invokeMethod(&udpServer, "start", Qt::QueuedConnection);

    // Run the primary thread's main event loop.
    // exec() will return when we stop the main event loop via a signal
    return app.exec();
}
示例#22
0
void NzmqtTest::testPubSub()
{
    try {
        QScopedPointer<ZMQContext> context(nzmqt::createDefaultContext());

        // Create publisher.
        samples::pubsub::Publisher* publisher = new samples::pubsub::Publisher(*context, "inproc://pubsub", "ping");
        QSignalSpy spyPublisherPingSent(publisher, SIGNAL(pingSent(const QList<QByteArray>&)));
        QSignalSpy spyPublisherFailure(publisher, SIGNAL(failure(const QString&)));
        QSignalSpy spyPublisherFinished(publisher, SIGNAL(finished()));
        // Create publisher execution thread.
        QThread* publisherThread = makeExecutionThread(*publisher);
        QSignalSpy spyPublisherThreadFinished(publisherThread, SIGNAL(finished()));

        // Create subscriber.
        samples::pubsub::Subscriber* subscriber = new samples::pubsub::Subscriber(*context, "inproc://pubsub", "ping");
        QSignalSpy spySubscriberPingReceived(subscriber, SIGNAL(pingReceived(const QList<QByteArray>&)));
        QSignalSpy spySubscriberFailure(subscriber, SIGNAL(failure(const QString&)));
        QSignalSpy spySubscriberFinished(subscriber, SIGNAL(finished()));
        // Create subscriber execution thread.
        QThread* subscriberThread = makeExecutionThread(*subscriber);
        QSignalSpy spySubscriberThreadFinished(subscriberThread, SIGNAL(finished()));

        //
        // START TEST
        //

        context->start();

        publisherThread->start();
        QTest::qWait(500);
        subscriberThread->start();

        QTimer::singleShot(6000, publisher, SLOT(stop()));
        QTimer::singleShot(6000, subscriber, SLOT(stop()));

        QTest::qWait(8000);

        //
        // CHECK POSTCONDITIONS
        //

        qDebug() << "Publisher pings sent:" << spyPublisherPingSent.size();
        qDebug() << "Subscriber pings received:" << spySubscriberPingReceived.size();

        QCOMPARE(spyPublisherFailure.size(), 0);
        QCOMPARE(spySubscriberFailure.size(), 0);

        QVERIFY2(spyPublisherPingSent.size() > 3, "Server didn't send any/enough pings.");
        QVERIFY2(spySubscriberPingReceived.size() > 3, "Client didn't receive any/enough pings.");

        QVERIFY2(qAbs(spyPublisherPingSent.size() - spySubscriberPingReceived.size()) < 3, "Publisher and subscriber communication flawed.");

        QCOMPARE(spyPublisherFinished.size(), 1);
        QCOMPARE(spySubscriberFinished.size(), 1);

        QCOMPARE(spyPublisherThreadFinished.size(), 1);
        QCOMPARE(spySubscriberThreadFinished.size(), 1);
    }
    catch (std::exception& ex)
    {
        QFAIL(ex.what());
    }
}
示例#23
0
int main(int argc, char *argv[]){

    QApplication application(argc, argv);

    /*
     * XML configuration parser
     */
    ParseNetworkConfigurationXML parser;
    Sink* sink = new Sink();
    vector<Camera*>* cameras = Camera::getCameras();
    vector<Link*> links;
    vector<NetworkItem*> items;

    parser.parse(XML_NETWORK_PATH, items, links, cameras, sink);
    std::cout << "main: XML sink: " << *sink << endl;
    Camera::printCameras();

    /*
     * PKLot configuration parser
     */
    for (uint camIdx = 0;camIdx < cameras->size(); camIdx++){
        Camera* cam = cameras->at(camIdx);
        std::vector<PKLot> pklots;
        cv::Size imgSize(FRAME_W,FRAME_H);
        stringstream ss;
        ss << PKLOT_XML_PATH << cam->getId() << ".xml";
        PKLot::parse(ss.str(),pklots);
        cam->setPKLots(pklots,imgSize);
    }

    /*
     * GUI
     */
    QDesktopWidget desktop;
    QRect mainScreenSize = desktop.availableGeometry(desktop.primaryScreen());

    std::vector<CameraView*> cam_views(cameras->size());



    /* Create the server */
    IoThread* ioThread = IoThread::getInstance(GUI_LISTENING_TCP_PORT);

    //cam_views.reserve(cameras.size());
    for (uint camIdx = 0; camIdx < cameras->size(); camIdx++){

        Camera* curCam = cameras->at(camIdx);
        curCam->setGuiIdx(camIdx);

        std::stringstream ss;
        ss << "Camera " << camIdx+1;
        QString wTitle(ss.str().c_str());

        CameraView* curCamView = new CameraView(curCam, 0, camIdx);

        curCamView->setWindowTitle(wTitle);
        int cwTLx = (10 + curCamView->width())*camIdx;
        int cwTLy = 10;

        curCamView->setGeometry(cwTLx, cwTLy, curCamView->width(), curCamView->height());
        curCamView->show();

        cam_views[camIdx] = curCamView;
    }

    ObjectTracking * task_track = ObjectTracking::getObjectTracking(DB_PATH);

    task_track->setCameras(cameras);
    task_track->setCamViews(cam_views);

    for (vector<Camera*>::iterator camIt = cameras->begin(); camIt != cameras->end(); camIt++){
        task_track->connectTasks(*camIt);
    }

    GuiProcessingSystem* guiProcessingSistem = GuiProcessingSystem::getInstance();

    inverse_BRISK * invBRISK = inverse_BRISK::getinverse_BRISK(guiProcessingSistem->getBriskExtractor(),FRAME_W, FRAME_H);
    invBRISK->build_database(DB_IMAGE_PATH);
    invBRISK->setNCameras(cameras->size());
    invBRISK->setCameras(cameras);

    invBRISK->connectTasks(cameras->size());

    PerformanceManager * perf = PerformanceManager::getPerformanceManager(cameras, 40*1000/1000, 1000,5);

    CameraSettings camSet;

    NetworkTopology net(&camSet, &items, &links, 0);
    camSet.setNetworkTopology(&net);

    int netTLx = 10;
    int netTLy = mainScreenSize.height() - net.geometry().height();

    net.setGeometry(netTLx, netTLy, net.geometry().width(), net.geometry().height());
    /*net.show();*/

    int csTLy = 10;
    int csTLx = mainScreenSize.width() - camSet.geometry().width() - 10;

    camSet.setGeometry(csTLx, csTLy, camSet.geometry().width(), camSet.geometry().height());

    camSet.show();

    std::vector<Plot*> cam_plots(cameras->size());

    for (uint8_t cam = 0; cam < cameras->size(); cam++){

        Plot * p = new Plot(*perf, cam, *(cameras->at(cam)));
        p->setWindowTitle("Camera " + QString::number(cam + 1));
        int plotTLx = mainScreenSize.width() - (10 + p->width())*(cameras->size() - cam);
        int plotTLy = mainScreenSize.height() - p->height();

        p->setGeometry(plotTLx, plotTLy, p->width(), p->height());
        p->show();

        cam_plots.push_back(p);
    }

    MainWindow mainWindow(&camSet, cam_views, &net, cam_plots);

    int wTLx = 20 + net.geometry().width();
    int wTLy = mainScreenSize.height() - net.geometry().height();

    mainWindow.setGeometry(wTLx, wTLy, mainWindow.geometry().width(), mainWindow.geometry().height());
    mainWindow.show();

    // inverse BRISK thread
    QThread* inverseBriskThread = new QThread;
    invBRISK->moveToThread(inverseBriskThread);
    inverseBriskThread->start();

    // object tracking+recognition thread
    QThread* recognitionTrackingThread = new QThread;
    task_track->moveToThread(recognitionTrackingThread);
    recognitionTrackingThread->start();

    perf->connectTasks();

    /* Gentle shutdown */
    signal(SIGINT, GuiNetworkSystem::shutdown);
    signal(SIGQUIT, GuiNetworkSystem::shutdown);

    /* Start the network system */
    ioThread->start();

    return application.exec();
}
示例#24
0
AssignmentClient::AssignmentClient(Assignment::Type requestAssignmentType, QString assignmentPool,
                                   quint16 listenPort, QUuid walletUUID, QString assignmentServerHostname,
                                   quint16 assignmentServerPort, quint16 assignmentMonitorPort) :
    _assignmentServerHostname(DEFAULT_ASSIGNMENT_SERVER_HOSTNAME)
{
    LogUtils::init();

    QSettings::setDefaultFormat(QSettings::IniFormat);

    DependencyManager::set<AccountManager>();
 
    auto scriptableAvatar = DependencyManager::set<ScriptableAvatar>();
    auto addressManager = DependencyManager::set<AddressManager>();
    auto scriptEngines = DependencyManager::set<ScriptEngines>();

    // create a NodeList as an unassigned client, must be after addressManager
    auto nodeList = DependencyManager::set<NodeList>(NodeType::Unassigned, listenPort);

    auto animationCache = DependencyManager::set<AnimationCache>();
    auto entityScriptingInterface = DependencyManager::set<EntityScriptingInterface>(false);

    DependencyManager::registerInheritance<EntityActionFactoryInterface, AssignmentActionFactory>();
    auto actionFactory = DependencyManager::set<AssignmentActionFactory>();
    DependencyManager::set<ResourceScriptingInterface>();

    // setup a thread for the NodeList and its PacketReceiver
    QThread* nodeThread = new QThread(this);
    nodeThread->setObjectName("NodeList Thread");
    nodeThread->start();

    // make sure the node thread is given highest priority
    nodeThread->setPriority(QThread::TimeCriticalPriority);

    // put the NodeList on the node thread
    nodeList->moveToThread(nodeThread);

    // set the logging target to the the CHILD_TARGET_NAME
    LogHandler::getInstance().setTargetName(ASSIGNMENT_CLIENT_TARGET_NAME);

    // make sure we output process IDs for a child AC otherwise it's insane to parse
    LogHandler::getInstance().setShouldOutputProcessID(true);

    // setup our _requestAssignment member variable from the passed arguments
    _requestAssignment = Assignment(Assignment::RequestCommand, requestAssignmentType, assignmentPool);

    // check for a wallet UUID on the command line or in the config
    // this would represent where the user running AC wants funds sent to
    if (!walletUUID.isNull()) {
        qCDebug(assigmnentclient) << "The destination wallet UUID for credits is" << uuidStringWithoutCurlyBraces(walletUUID);
        _requestAssignment.setWalletUUID(walletUUID);
    }

    // check for an overriden assignment server hostname
    if (assignmentServerHostname != "") {
        // change the hostname for our assignment server
        _assignmentServerHostname = assignmentServerHostname;
    }

    _assignmentServerSocket = HifiSockAddr(_assignmentServerHostname, assignmentServerPort, true);
    _assignmentServerSocket.setObjectName("AssigmentServer");
    nodeList->setAssignmentServerSocket(_assignmentServerSocket);

    qCDebug(assigmnentclient) << "Assignment server socket is" << _assignmentServerSocket;

    // call a timer function every ASSIGNMENT_REQUEST_INTERVAL_MSECS to ask for assignment, if required
    qCDebug(assigmnentclient) << "Waiting for assignment -" << _requestAssignment;

    if (_assignmentServerHostname != "localhost") {
        qCDebug(assigmnentclient) << "- will attempt to connect to domain-server on" << _assignmentServerSocket.getPort();
    }

    connect(&_requestTimer, SIGNAL(timeout()), SLOT(sendAssignmentRequest()));
    _requestTimer.start(ASSIGNMENT_REQUEST_INTERVAL_MSECS);

    // connections to AccountManager for authentication
    connect(DependencyManager::get<AccountManager>().data(), &AccountManager::authRequired,
            this, &AssignmentClient::handleAuthenticationRequest);

    // Create Singleton objects on main thread
    NetworkAccessManager::getInstance();

    // did we get an assignment-client monitor port?
    if (assignmentMonitorPort > 0) {
        _assignmentClientMonitorSocket = HifiSockAddr(DEFAULT_ASSIGNMENT_CLIENT_MONITOR_HOSTNAME, assignmentMonitorPort);
        _assignmentClientMonitorSocket.setObjectName("AssignmentClientMonitor");

        qCDebug(assigmnentclient) << "Assignment-client monitor socket is" << _assignmentClientMonitorSocket;

        // Hook up a timer to send this child's status to the Monitor once per second
        setUpStatusToMonitor();
    }
    auto& packetReceiver = DependencyManager::get<NodeList>()->getPacketReceiver();
    packetReceiver.registerListener(PacketType::CreateAssignment, this, "handleCreateAssignmentPacket");
    packetReceiver.registerListener(PacketType::StopNode, this, "handleStopNodePacket");
}
示例#25
0
CWizDocumentListView::CWizDocumentListView(CWizExplorerApp& app, QWidget *parent /*= 0*/)
    : QListWidget(parent)
    , m_app(app)
    , m_dbMgr(app.databaseManager())
    , m_tagList(NULL)
{
    setFrameStyle(QFrame::NoFrame);
    setAttribute(Qt::WA_MacShowFocusRect, false);

    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);

#ifndef Q_OS_MAC
    // smoothly scroll
    m_vscrollOldPos = 0;
    connect(verticalScrollBar(), SIGNAL(valueChanged(int)), SLOT(on_vscroll_valueChanged(int)));
    connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), SLOT(on_vscroll_actionTriggered(int)));
    connect(&m_vscrollTimer, SIGNAL(timeout()), SLOT(on_vscroll_update()));
#endif //Q_OS_MAC

    setItemDelegate(new CWizDocumentListViewDelegate(this));

    QPalette pal = palette();
    pal.setColor(QPalette::Base, WizGetDocumentsBackroundColor(m_app.userSettings().skin()));
    setPalette(pal);

    setStyle(::WizGetStyle(m_app.userSettings().skin()));

    qRegisterMetaType<WIZTAGDATA>("WIZTAGDATA");
    qRegisterMetaType<WIZDOCUMENTDATA>("WIZDOCUMENTDATA");

    connect(&m_dbMgr, SIGNAL(tagCreated(const WIZTAGDATA&)), \
            SLOT(on_tag_created(const WIZTAGDATA&)));

    connect(&m_dbMgr, SIGNAL(tagModified(const WIZTAGDATA&, const WIZTAGDATA&)), \
            SLOT(on_tag_modified(const WIZTAGDATA&, const WIZTAGDATA&)));

    connect(&m_dbMgr, SIGNAL(documentCreated(const WIZDOCUMENTDATA&)), \
            SLOT(on_document_created(const WIZDOCUMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(documentModified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)), \
            SLOT(on_document_modified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(documentDeleted(const WIZDOCUMENTDATA&)), \
            SLOT(on_document_deleted(const WIZDOCUMENTDATA&)));


    m_thumbCache = new CWizThumbIndexCache(app);
    qRegisterMetaType<WIZABSTRACT>("WIZABSTRACT");
    connect(m_thumbCache, SIGNAL(loaded(const WIZABSTRACT&)),
            SLOT(on_document_abstractLoaded(const WIZABSTRACT&)));

    QThread *thread = new QThread();
    m_thumbCache->moveToThread(thread);
    thread->start();

    setDragDropMode(QAbstractItemView::DragDrop);
    setDragEnabled(true);
    viewport()->setAcceptDrops(true);

    setSelectionMode(QAbstractItemView::ExtendedSelection);

    // setup popup menu
    m_menu = new QMenu(this);
    m_menu->addAction(WIZACTION_LIST_TAGS, this, SLOT(on_action_selectTags()));
    m_menu->addSeparator();
    m_menu->addAction(WIZACTION_LIST_DELETE, this, SLOT(on_action_deleteDocument()));
    //m_actionEncryptDocument = new QAction(tr("Encrypt Document"), m_menu);
    //connect(m_actionEncryptDocument, SIGNAL(triggered()), SLOT(on_action_encryptDocument()));
    //m_menu->addAction(m_actionEncryptDocument);
}
示例#26
0
文件: main.cpp 项目: mathieu/dtEntity
int main(int argc, char *argv[])
{

   // enable multithreaded opengl on linux
#ifdef __GNUC__
   XInitThreads();
#endif

   using namespace dtEntityEditor;

   // start up Qt
   MyQApplication qtapp(argc, argv);


   // for QSettings
   QCoreApplication::setOrganizationName("dtEntity");
   QCoreApplication::setOrganizationDomain("dtEntity");
   QCoreApplication::setApplicationName("dtEntity Editor");

   // let OpenSceneGraph window be a Qt widget
   dtEntityQtWidgets::QtGuiWindowSystemWrapper::EnableQtGUIWrapper();

   // register some used classes as Qt meta types so that they can be
   // used in signal slot connections
   qRegisterMetaType<dtEntity::EntityId>("dtEntity::EntityId");
   qRegisterMetaType<dtEntity::ComponentType>("dtEntity::ComponentType");
   qRegisterMetaType<dtEntity::StringId>("dtEntity::StringId");
   qRegisterMetaType<osg::Vec2>("osg::Vec2");
   qRegisterMetaType<osg::Vec3>("osg::Vec3");
   qRegisterMetaType<osg::Vec4>("osg::Vec4");
   qRegisterMetaType<osg::Timer_t>("osg::Timer_t");
   qRegisterMetaType<dtEntity::GroupProperty>("dtEntity::GroupProperty");
   qRegisterMetaType<dtEntityQtWidgets::OSGGraphicsWindowQt*>("dtEntityQtWidgets::OSGGraphicsWindowQt*");

   bool singleThread = false;

   QString pluginPath = "plugins";
   QString scene = "";
   for(int curArg = 1; curArg < argc; ++curArg)
   {
      std::string curArgv = argv[curArg];
      if (curArgv.empty())
      {
         continue;
      }
      else if(curArgv == "--singleThread")
      {
         singleThread = true;
      }
      else if(curArgv == "--scene")
      {
         ++curArg;
         if (curArg < argc)
         {
            scene = argv[curArg];
         }
      }
      else if(curArgv == "--pluginPath")
      {
         ++curArg;
         if (curArg < argc)
         {
            pluginPath = argv[curArg];
         }
      }
   }

   osg::ref_ptr<EditorApplication> application = new EditorApplication(argc, argv);

   application->SetAdditionalPluginPath(pluginPath);

   QThread* viewerThread;

   if(!singleThread)
   {
      // start dtEntity in a background thread. All communications between
      // Qt and dtEntity go over signal slot connections.
      viewerThread = new QThread();
      application->moveToThread(viewerThread);
   }
   
    // create Qt main window
   EditorMainWindow main(application.get());      
   application->SetMainWindow(&main);

   if(!singleThread)
   {
      // Start the Qt event loop in the d3d thread
      viewerThread->start(QThread::NormalPriority);
   }
  
   // show main window
   main.show();

   // send qt event to game to start processing. This gets delivered thread-safe
   // if qt was started in extra thread
   QMetaObject::invokeMethod(application, "StartGame", Qt::QueuedConnection,
                              Q_ARG(QString, scene));

   qtapp.exec();

   if(!singleThread)
   {
      viewerThread->wait();
      delete viewerThread;
   }
   
   application->moveToThread(QThread::currentThread());
   application = NULL;
   
   return 0;
}
示例#27
0
void tpMainWindow::executeExternalPlayer(QString player, QString url, QString channel, int streamWidth, int streamHeight, int xOffset, int yOffset, bool mute, QString quality)
{
    QString qresBin = "";
    QString playerBin = "";
    QString playerarg = "";
    QStringList args;
    QStringList qresargs;
    QThread* processLaunchThread = new QThread;

    qresargs << "-f" << "^http://.+" << channel << ".+";
    qresargs << "-x" << QString::number(xOffset);
    qresargs << "-y" << QString::number(yOffset);
    qresargs << "-w" << QString::number(streamWidth);
    qresargs << "-t" << QString::number(streamHeight);
    qresargs << "-i" << "30";
    qresargs << "-d" << "20";
    args = genericHelper::getVlcArgs();

    if (mute == true) {
        args << "--volume=0";
    }

    args << url;
    qresBin = QCoreApplication::applicationFilePath().replace(genericHelper::getAppName()+".exe","qres.exe");

    if (player == "vlc2") {
        playerBin = genericHelper::getVlcPath();
    }

    qresargs << "-e" << "\""+playerBin+"\"";
    qresargs << "-u" << args.join(" ");
    QFile playerBinFile( playerBin );
    QFile qresBinFile( qresBin );

    if(! playerBinFile.exists()) {
        QMessageBox::critical(this, genericHelper::getAppName(),
                                       tr("Can't find VLC, please check options."),
                                       QMessageBox::Ok);
        return ;
    }

    if(! qresBinFile.exists() && genericHelper::getStreamPositioning() ) {
        QMessageBox::critical(this, genericHelper::getAppName(),
                                       tr("Can't find qres, please check options."),
                                       QMessageBox::Ok);
        return ;
    }

    if (genericHelper::getStreamPositioning() == true) {
        if( (qresBinFile.exists()) && (playerBinFile.exists()) ) {
            processLauncher *processL = new processLauncher();
            processL->setProgramStr("\""+qresBin+"\"");
            processL->setArgs(qresargs);
            genericHelper::log("starting player: "+qresBin+" "+qresargs.join(" "));
            processL->moveToThread(processLaunchThread);
            // connect the thread start started signal to the process slot of the riftLogWatcher class
            QObject::connect(processLaunchThread, SIGNAL(started()), processL, SLOT(launch()));
            processLaunchThread->start();
        }
    } else {
        if( playerBinFile.exists() ) {
            processLauncher *processL = new processLauncher();

            processL->setProgramStr("\""+playerBin+"\"");
            processL->setArgs(args);

            genericHelper::log("starting player: "+playerBin+" "+args.join(" "));

            processL->moveToThread(processLaunchThread);

            // connect the thread start started signal to the process slot of the riftLogWatcher class
            QObject::connect(processLaunchThread, SIGNAL(started()), processL, SLOT(launch()));
            processLaunchThread->start();
        }
    }

    //genericHelper::log("player or qres binary not found, not starting: "+qresBin+" "+qresargs.join(" "));
    this->playerThreads.append(processLaunchThread);
}
void UpdateMediaVolumeInfo::run()
{
    QThread backend;
    backend.start();

    QNetworkAccessManager manager;
    manager.moveToThread(&backend);

    MediaLibrary library(m_log);

    QSqlQuery query;
    query.prepare("SELECT media.id, media.filename, mime_type.name from media LEFT OUTER JOIN mime_type ON media.mime_type=mime_type.id WHERE media.is_reachable=1");

    if (query.exec())
    {
        while (query.next())
        {
            int idMedia = query.record().value("id").toInt();
            QString filename = query.record().value("filename").toString();
            QString mime_type = query.record().value("name").toString();
            QHash<QString, double> volumeInfo = library.volumeInfo(idMedia);

            if (volumeInfo.isEmpty())
            {
                if (mime_type.startsWith("audio/"))
                {
                    qWarning() << "Analyze audio" << filename;

                    DlnaMusicTrackFile track(m_log, filename, "HOST", 80);
                    if (!library.setVolumeInfo(idMedia, track.volumeInfo()))
                        qWarning() << "Unable to set volume information for" << filename;
                }
                else if (mime_type.startsWith("video/")  && !filename.startsWith("http"))
                {
                    qWarning() << "Analyze local video" << filename;

                    DlnaVideoFile movie(m_log, filename, "HOST", 80);
                    if (!library.setVolumeInfo(idMedia, movie.volumeInfo(-1)))
                        qWarning() << "Unable to set volume information for" << filename;
                }
                else if (mime_type.startsWith("video/") && filename.startsWith("http"))
                {
                    qWarning() << "Analyze internet video" << filename;

                    DlnaYouTubeVideo video(m_log, "HOST", 80);
                    video.moveToThread(&backend);
                    video.setNetworkAccessManager(&manager);
                    video.setUrl(filename);
                    bool res = video.waitUrl(30000);

                    if (res && video.isValid())
                    {
                        if (!library.setVolumeInfo(idMedia, video.volumeInfo(-1)))
                            qWarning() << "Unable to set volume information for" << filename;
                    }
                    else
                    {
                        qWarning() << "NO VOLUME INFO (TIMEOUT)" << filename;
                    }

                }
                else
                {
                    qWarning() << "NO VOLUME INFO" << filename;
                }
            }
        }
    }
    else
    {
        qWarning() << "ERROR in request" << query.lastError().text();
    }

    backend.quit();
}
示例#29
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;
}
CWizDocumentView::CWizDocumentView(CWizExplorerApp& app, QWidget* parent)
    : INoteView(parent)
    , m_app(app)
    , m_dbMgr(app.databaseManager())
    , m_userSettings(app.userSettings())
    #ifdef USEWEBENGINE
    , m_web(new CWizDocumentWebEngine(app, this))
    , m_comments(new QWebEngineView(this))
    #else
    , m_web(new CWizDocumentWebView(app, this))
    , m_commentWidget(new CWizLocalProgressWebView(app.mainWindow()))
    #endif
    , m_title(new TitleBar(app, this))
    , m_passwordView(new CWizUserCipherForm(app, this))
    , m_viewMode(app.userSettings().noteViewMode())
    , m_transitionView(new CWizDocumentTransitionView(this))
    , m_bLocked(false)
    , m_bEditingMode(false)
    , m_noteLoaded(false)
    , m_editStatusSyncThread(new CWizDocumentEditStatusSyncThread(this))
    //, m_editStatusCheckThread(new CWizDocumentStatusCheckThread(this))
    , m_editStatus(0)
    , m_sizeHint(QSize(200, 1))
{
    m_title->setEditor(m_web);

    QVBoxLayout* layoutDoc = new QVBoxLayout();
    layoutDoc->setContentsMargins(0, 0, 0, 0);
    layoutDoc->setSpacing(0);

    m_docView = new QWidget(this);
    m_docView->setLayout(layoutDoc);

    m_tab = new QStackedWidget(this);
    //
    m_passwordView->setGeometry(this->geometry());
    connect(m_passwordView, SIGNAL(cipherCheckRequest()), SLOT(onCipherCheckRequest()));
    //
    m_msgWidget = new QWidget(this);
    QVBoxLayout* layoutMsg = new QVBoxLayout();
    m_msgWidget->setLayout(layoutMsg);
    m_msgLabel = new QLabel(m_msgWidget);
    m_msgLabel->setAlignment(Qt::AlignCenter);
    m_msgLabel->setWordWrap(true);
    layoutMsg->addWidget(m_msgLabel);
    //
    m_tab->addWidget(m_docView);
    m_tab->addWidget(m_passwordView);
    m_tab->addWidget(m_msgWidget);
    m_tab->setCurrentWidget(m_docView);    

    m_web->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_comments = m_commentWidget->web();
    QWebPage *commentPage = new QWebPage(m_comments);
    commentPage->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    m_comments->setPage(commentPage);
    m_comments->history()->setMaximumItemCount(0);
    m_comments->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    m_comments->settings()->globalSettings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
    m_comments->settings()->globalSettings()->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, true);
    m_comments->page()->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
    m_comments->setAcceptDrops(false);
    connect(m_comments, SIGNAL(loadFinished(bool)), m_title, SLOT(onCommentPageLoaded(bool)));
    connect(m_comments, SIGNAL(linkClicked(QUrl)), m_web, SLOT(onEditorLinkClicked(QUrl)));
    connect(m_comments->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            SLOT(on_comment_populateJavaScriptWindowObject()));
    connect(m_commentWidget, SIGNAL(widgetStatusChanged()), SLOT(on_commentWidget_statusChanged()));

    m_commentWidget->hide();

    QWidget* wgtEditor = new QWidget(m_docView);
    QVBoxLayout* layoutEditor = new QVBoxLayout(wgtEditor);
    layoutEditor->setSpacing(0);
    layoutEditor->setContentsMargins(0, 5, 0, 0);
    layoutEditor->addWidget(m_title);
    layoutEditor->addWidget(m_web);
    layoutEditor->setStretchFactor(m_title, 0);
    layoutEditor->setStretchFactor(m_web, 1);

    m_splitter = new CWizSplitter(this);
    m_splitter->addWidget(wgtEditor);
    m_splitter->addWidget(m_commentWidget);
    m_splitter->setOrientation(Qt::Horizontal);

    layoutDoc->addWidget(m_splitter);
//    layoutDoc->setStretchFactor(m_title, 0);
//    layoutDoc->setStretchFactor(m_splitter, 1);

#ifdef USEWEBENGINE
    QLineEdit *commandLine = new QLineEdit(this);
    layoutDoc->addWidget(commandLine);
    connect(commandLine, SIGNAL(returnPressed()), SLOT(on_command_request()));
#endif

    QVBoxLayout* layoutMain = new QVBoxLayout(this);
    layoutMain->setContentsMargins(0, 0, 0, 0);
    setLayout(layoutMain);
    layoutMain->addWidget(m_tab);

    //
    layoutMain->addWidget(m_transitionView);
    m_transitionView->hide();

    MainWindow* mainWindow = qobject_cast<MainWindow *>(m_app.mainWindow());
    m_downloaderHost = mainWindow->downloaderHost();
    connect(m_downloaderHost, SIGNAL(downloadDone(const WIZOBJECTDATA&, bool)),
            SLOT(on_download_finished(const WIZOBJECTDATA&, bool)));

    connect(&m_dbMgr, SIGNAL(documentModified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)), \
            SLOT(on_document_modified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(documentDataModified(const WIZDOCUMENTDATA&)),
            SLOT(on_document_data_modified(const WIZDOCUMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(attachmentCreated(const WIZDOCUMENTATTACHMENTDATA&)), \
            SLOT(on_attachment_created(const WIZDOCUMENTATTACHMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(attachmentDeleted(const WIZDOCUMENTATTACHMENTDATA&)), \
            SLOT(on_attachment_deleted(const WIZDOCUMENTATTACHMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(documentUploaded(QString,QString)), \
            m_editStatusSyncThread, SLOT(documentUploaded(QString,QString)));

    connect(Core::ICore::instance(), SIGNAL(viewNoteRequested(Core::INoteView*,const WIZDOCUMENTDATA&)),
            SLOT(onViewNoteRequested(Core::INoteView*,const WIZDOCUMENTDATA&)));

    connect(Core::ICore::instance(), SIGNAL(viewNoteLoaded(Core::INoteView*,WIZDOCUMENTDATA,bool)),
            SLOT(onViewNoteLoaded(Core::INoteView*,const WIZDOCUMENTDATA&,bool)));

    connect(Core::ICore::instance(), SIGNAL(closeNoteRequested(Core::INoteView*)),
            SLOT(onCloseNoteRequested(Core::INoteView*)));

    connect(m_web, SIGNAL(focusIn()), SLOT(on_webView_focus_changed()));

    connect(m_title, SIGNAL(notifyBar_link_clicked(QString)), SLOT(on_notifyBar_link_clicked(QString)));
    connect(m_title, SIGNAL(loadComment_request(QString)), SLOT(on_loadComment_request(QString)), Qt::QueuedConnection);

//    connect(m_editStatusCheckThread, SIGNAL(checkFinished(QString,QStringList)),
//            SLOT(on_checkEditStatus_finished(QString,QStringList)));
//    connect(m_editStatusCheckThread, SIGNAL(checkDocumentChangedFinished(QString,bool)),
//            SLOT(on_checkDocumentChanged_finished(QString,bool)));
//    connect(m_editStatusCheckThread, SIGNAL(checkTimeOut(QString)),
//            SLOT(on_checkEditStatus_timeout(QString)));

    //
    m_editStatusSyncThread->start(QThread::IdlePriority);
//    m_editStatusCheckThread->start(QThread::IdlePriority);

    m_editStatusChecker = new CWizDocumentStatusChecker();
    connect(this, SIGNAL(checkDocumentEditStatusRequest(QString,QString)), m_editStatusChecker,
            SLOT(checkEditStatus(QString,QString)));
    connect(this, SIGNAL(stopCheckDocumentEditStatusRequest(QString,QString)),
            m_editStatusChecker, SLOT(stopCheckStatus(QString,QString)));
    connect(m_editStatusChecker, SIGNAL(checkEditStatusFinished(QString,bool)), \
            SLOT(on_checkEditStatus_finished(QString,bool)));
    connect(m_editStatusChecker, SIGNAL(checkTimeOut(QString)), \
            SLOT(on_checkEditStatus_timeout(QString)));
    connect(m_editStatusChecker, SIGNAL(documentEditingByOthers(QString,QStringList)), \
            SLOT(on_documentEditingByOthers(QString,QStringList)));
    connect(m_editStatusChecker, SIGNAL(checkDocumentChangedFinished(QString,bool)), \
            SLOT(on_checkDocumentChanged_finished(QString,bool)));

    QThread* checkThread = new QThread(this);
    connect(checkThread, SIGNAL(started()), m_editStatusChecker, SLOT(initialise()));
    connect(checkThread, SIGNAL(finished()), m_editStatusChecker, SLOT(clearTimers()));
    m_editStatusChecker->moveToThread(checkThread);
    checkThread->start();
}