void CNetRender::ProcessData(QTcpSocket *socket, sMessage *inMsg) { // beware: payload points to char, first cast to target type pointer, then dereference // *(qint32*)msg->payload //------------------------- CLIENT ------------------------ if(IsClient()) { switch ((netCommand)inMsg->command) { case netRender_VERSION: { sMessage outMsg; if(*(qint32*)inMsg->payload.data() == version) { WriteLog("NetRender - version matches (" + QString::number(version) + "), connection established"); if(systemData.noGui) { QTextStream out(stdout); out << "NetRender - version matches (" + QString::number(version) + "), connection established\n"; } // server version matches, send worker count outMsg.command = netRender_WORKER; QDataStream stream(&outMsg.payload, QIODevice::WriteOnly); stream << workerCount; QString machineName = QHostInfo::localHostName(); stream << (qint32)machineName.toUtf8().size(); stream.writeRawData(machineName.toUtf8().data(), machineName.toUtf8().size()); status = netRender_READY; emit NewStatusClient(); } else { qWarning() << "CNetRender - version mismatch! client version: " << version << ", server: " << *(qint32*)inMsg->payload.data(); outMsg.command = netRender_BAD; } SendData(clientSocket, outMsg); break; } case netRender_STOP: { status = netRender_READY; gMainInterface->stopRequest = true; emit NotifyStatus(); WriteLog("CNetRender - STOP"); break; } case netRender_STATUS: { emit NotifyStatus(); break; } case netRender_JOB: { if (inMsg->id == actualId) { WriteLog("NetRender - received new job"); QDataStream stream(&inMsg->payload, QIODevice::ReadOnly); QByteArray buffer; qint32 size; status = netRender_WORKING; emit NotifyStatus(); // read settings stream >> size; buffer.resize(size); stream.readRawData(buffer.data(), size); settingsText = QString::fromUtf8(buffer.data(), buffer.size()); // read textures for (int i = 0; i < textures.textureList.size(); i++) { stream >> size; if (size > 0) { buffer.resize(size); stream.readRawData(buffer.data(), size); textures.textureList[i]->FromQByteArray(buffer); } } cSettings parSettings(cSettings::formatCondensedText); parSettings.BeQuiet(true); parSettings.LoadFromString(settingsText); parSettings.Decode(gPar, gParFractal); if(!systemData.noGui) { gMainInterface->SynchronizeInterface(gPar, gParFractal, cInterface::write); gMainInterface->StartRender(true); } else { //in noGui mode it must be started as separate thread to be able to process event loop gMainInterface->headless = new cHeadless; QThread *thread = new QThread; //deleted by deleteLater() gMainInterface->headless->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), gMainInterface->headless, SLOT(slotNetRender())); thread->setObjectName("RenderJob"); thread->start(); QObject::connect(gMainInterface->headless, SIGNAL(finished()), gMainInterface->headless, SLOT(deleteLater())); QObject::connect(gMainInterface->headless, SIGNAL(finished()), thread, SLOT(quit())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); } } else { WriteLog("NetRender - received JOB message with wrong id"); } break; } case netRender_RENDER: { if (inMsg->id == actualId) { QDataStream stream(&inMsg->payload, QIODevice::ReadOnly); qint32 doneSize; stream >> doneSize; QList<int> done; for (int i = 0; i < doneSize; i++) { qint32 line; stream >> line; done.append(line); } emit ToDoListArrived(done); } else {
bool Servatrice::initServer() { serverName = settingsCache->value("server/name", "My Cockatrice server").toString(); serverId = settingsCache->value("server/id", 0).toInt(); bool regServerOnly = settingsCache->value("authentication/regonly", 0).toBool(); const QString authenticationMethodStr = settingsCache->value("authentication/method").toString(); if (authenticationMethodStr == "sql") { qDebug() << "Authenticating method: sql"; authenticationMethod = AuthenticationSql; } else if(authenticationMethodStr == "password") { qDebug() << "Authenticating method: password"; authenticationMethod = AuthenticationPassword; } else { if (regServerOnly) { qDebug() << "Registration only server enabled but no authentication method defined: Error."; return false; } qDebug() << "Authenticating method: none"; authenticationMethod = AuthenticationNone; } bool maxUserLimitEnabled = settingsCache->value("security/enable_max_user_limit", false).toBool(); qDebug() << "Maximum user limit enabled: " << maxUserLimitEnabled; if (maxUserLimitEnabled){ int maxUserLimit = settingsCache->value("security/max_users_total", 500).toInt(); qDebug() << "Maximum user limit: " << maxUserLimit; } bool registrationEnabled = settingsCache->value("registration/enabled", false).toBool(); bool requireEmailForRegistration = settingsCache->value("registration/requireemail", true).toBool(); qDebug() << "Registration enabled: " << registrationEnabled; if (registrationEnabled) qDebug() << "Require email address to register: " << requireEmailForRegistration; QString dbTypeStr = settingsCache->value("database/type").toString(); if (dbTypeStr == "mysql") databaseType = DatabaseMySql; else databaseType = DatabaseNone; servatriceDatabaseInterface = new Servatrice_DatabaseInterface(-1, this); setDatabaseInterface(servatriceDatabaseInterface); if (databaseType != DatabaseNone) { settingsCache->beginGroup("database"); dbPrefix = settingsCache->value("prefix").toString(); bool dbOpened = servatriceDatabaseInterface->initDatabase("QMYSQL", settingsCache->value("hostname").toString(), settingsCache->value("database").toString(), settingsCache->value("user").toString(), settingsCache->value("password").toString()); settingsCache->endGroup(); if (!dbOpened) { qDebug() << "Failed to open database"; return false; } updateServerList(); qDebug() << "Clearing previous sessions..."; servatriceDatabaseInterface->clearSessionTables(); } const QString roomMethod = settingsCache->value("rooms/method").toString(); if (roomMethod == "sql") { QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select id, name, descr, auto_join, join_message from {prefix}_rooms order by id asc"); servatriceDatabaseInterface->execSqlQuery(query); while (query->next()) { QSqlQuery *query2 = servatriceDatabaseInterface->prepareQuery("select name from {prefix}_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 = settingsCache->beginReadArray("rooms/roomlist"); for (int i = 0; i < size; ++i) { settingsCache->setArrayIndex(i); QStringList gameTypes; int size2 = settingsCache->beginReadArray("game_types"); for (int j = 0; j < size2; ++j) { settingsCache->setArrayIndex(j); gameTypes.append(settingsCache->value("name").toString()); } settingsCache->endArray(); Server_Room *newRoom = new Server_Room( i, settingsCache->value("name").toString(), settingsCache->value("description").toString(), settingsCache->value("autojoin").toBool(), settingsCache->value("joinmessage").toString(), gameTypes, this ); addRoom(newRoom); } if(size==0) { // no room defined in config, add a dummy one Server_Room *newRoom = new Server_Room( 0, "General room", "Play anything here.", true, "", QStringList("Standard"), this ); addRoom(newRoom); } settingsCache->endArray(); } updateLoginMessage(); maxGameInactivityTime = settingsCache->value("game/max_game_inactivity_time", 120).toInt(); maxPlayerInactivityTime = settingsCache->value("game/max_player_inactivity_time", 15).toInt(); maxUsersPerAddress = settingsCache->value("security/max_users_per_address", 4).toInt(); messageCountingInterval = settingsCache->value("security/message_counting_interval", 10).toInt(); maxMessageCountPerInterval = settingsCache->value("security/max_message_count_per_interval", 15).toInt(); maxMessageSizePerInterval = settingsCache->value("security/max_message_size_per_interval", 1000).toInt(); maxGamesPerUser = settingsCache->value("security/max_games_per_user", 5).toInt(); commandCountingInterval = settingsCache->value("game/command_counting_interval", 10).toInt(); maxCommandCountPerInterval = settingsCache->value("game/max_command_count_per_interval", 20).toInt(); try { if (settingsCache->value("servernetwork/active", 0).toInt()) { qDebug() << "Connecting to ISL network."; const QString certFileName = settingsCache->value("servernetwork/ssl_cert").toString(); const QString keyFileName = settingsCache->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 = settingsCache->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 = settingsCache->value("server/statusupdate", 15000).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 = settingsCache->value("server/number_pools", 1).toInt(); gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this); gameServer->setMaxPendingConnections(1000); const int gamePort = settingsCache->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:" << gameServer->errorString(); return false; } return true; }
void start() { m_widget.blockGUI(true); worker->moveToThread(thread); thread->start(); }
QThread *QAdoptedThread::createThreadForAdoption() { QThread *t = new QAdoptedThread(0); t->moveToThread(t); return t; }
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; }
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()); } }
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()); } }
void dtkComposerEvaluatorSlave::run(void) { d->status = 0; if ( !d->communicator_i) { d->communicator_i = dtkDistributed::communicator::instance(); if (d->communicator_i->rank() == 0) { std::cout << QString("DTK_JOBID="+this->jobId()).toStdString() << std::endl << std::flush; } } if (!d->factory) { dtkFatal() << "No factory set ! abort slave execution"; d->status = 1; return; } int rank = d->communicator_i->rank(); int size = d->communicator_i->size(); dtkDebug() << "communicator size is" << size; dtkDebug() << "our rank is" << rank; bool new_composition; if ( rank == 0) { QScopedPointer<dtkDistributedMessage> msg; if (!this->isConnected()) { dtkDebug() << "connect to server" << d->server; this->connect(d->server); if (this->isConnected()) { if (!d->composition_socket) { dtkDebug() << "open second socket to server" << d->server; d->composition_socket = new QTcpSocket; d->composition_socket->connectToHost(d->server.host(), d->server.port()); if (d->composition_socket->waitForConnected()) { msg.reset(new dtkDistributedMessage(dtkDistributedMessage::SETRANK,this->jobId(), dtkDistributedMessage::SLAVE_RANK )); msg->send(d->composition_socket); } else { dtkError() << "Can't connect to server"; d->status = 1; return; } } dtkDebug() << "connected, send our jobid to server" << this->jobId(); msg.reset(new dtkDistributedMessage(dtkDistributedMessage::SETRANK,this->jobId(),0)); msg->send(this->socket()); this->socket()->flush(); this->socket()->setParent(0); } else { dtkFatal() << "Can't connect to server" << d->server; d->status = 1; return; } } QString composition; dtkDebug() << "Wait for composition from controller " ; if (d->composition_socket->bytesAvailable() > 10) { dtkInfo() << "data already available, try to parse composition " << d->composition_socket->bytesAvailable(); } else if (!d->composition_socket->waitForReadyRead(600000)) { dtkFatal() << "No data received from server after 10mn, abort " ; d->status = 1; return; } else { dtkDebug() << "Ok, data received on composition socket, parse" ; } msg.reset(new dtkDistributedMessage); msg->parse(d->composition_socket); if (msg->type() == "xml") { new_composition = true; composition = QString(msg->content()); d->last_controller_rank = msg->header("x-forwarded-for").toInt(); d->composition_cache.insert(d->last_controller_rank, composition); } else if (msg->type() == "not-modified") { // reuse the old composition if (msg->header("x-forwarded-for").toInt() == d->last_controller_rank) { new_composition = false; } else { d->last_controller_rank = msg->header("x-forwarded-for").toInt(); dtkDebug() << "not modified, but from another controller" << d->last_controller_rank; new_composition = true; composition = d->composition_cache.value(d->last_controller_rank); } } else { dtkFatal() << "Bad composition type, abort" << msg->type() << msg->content(); d->status = 1; return; } if (new_composition && composition.isEmpty()) { dtkFatal() << "Empty composition, abort" ; d->status = 1; return; } dtkDebug() << "got composition from controller:" << composition; if (new_composition) { dtkDebug() << "new composition"; if (size > 1) { dtkDebug() << "send composition to our slaves"; for (int i=1; i< size; i++) { d->communicator_i->send(composition,i,0); } } dtkDebug() << "parse composition" ; d->reader->readString(composition); } else { dtkInfo() << "composition hasn't changed"; for (int i=1; i< size; i++) d->communicator_i->send(QString("rerun"),i,0); } if (new_composition) { if (dtkComposerNodeRemote *remote = dynamic_cast<dtkComposerNodeRemote *>(d->scene->root()->nodes().first()->wrapee())) { //FIXME: can we remove this ? // this->communicator()->setProperty("jobid",this->jobId()); remote->setSlave(this); remote->setJob(this->jobId()); remote->setCommunicator(d->communicator_i); } else { dtkFatal() << "Can't find remote node in composition, abort"; d->status = 1; return; } } dtkDebug() << "run composition" ; if (QThread::currentThread() == qApp->thread()) { dtkTrace() << "running on main thread, create a thread for the evaluator" ; QThread *workerThread = new QThread(this); QObject::connect(workerThread, SIGNAL(started()), d->evaluator, SLOT(run()), Qt::DirectConnection); QObject::connect(d->evaluator, SIGNAL(evaluationStopped()), workerThread, SLOT(quit())); QEventLoop loop; loop.connect(d->evaluator, SIGNAL(evaluationStopped()), &loop, SLOT(quit())); loop.connect(qApp, SIGNAL(aboutToQuit()), &loop, SLOT(quit())); this->socket()->moveToThread(workerThread); workerThread->start(); loop.exec(); workerThread->wait(); workerThread->deleteLater(); } else { dtkTrace() << "running on dedicated thread,run the evaluator" ; d->evaluator->run_static(); } dtkDebug() << "finished" ; } else { QString composition; d->communicator_i->receive(composition,0,0); if (composition != "rerun") { dtkDebug() << "new/changed composition, read" ; dtkDebug() << " composition is " << composition ; d->reader->readString(composition); dtkDebug() << "read done" ; } else { dtkDebug() << "reuse composition" ; } if (dtkComposerNodeRemote *remote = dynamic_cast<dtkComposerNodeRemote *>(d->scene->root()->nodes().first()->wrapee())) { remote->setSlave(this); remote->setJob(this->jobId()); remote->setCommunicator(d->communicator_i); dtkDebug() << "run composition" ; QThread *workerThread = new QThread(this); QObject::connect(workerThread, SIGNAL(started()), d->evaluator, SLOT(run()), Qt::DirectConnection); QObject::connect(d->evaluator, SIGNAL(evaluationStopped()), workerThread, SLOT(quit())); QEventLoop loop; loop.connect(d->evaluator, SIGNAL(evaluationStopped()), &loop, SLOT(quit())); loop.connect(qApp, SIGNAL(aboutToQuit()), &loop, SLOT(quit())); workerThread->start(); loop.exec(); workerThread->wait(); workerThread->deleteLater(); // d->evaluator->run_static(); dtkDebug() << "finished" ; } else { dtkFatal() << "Can't find remote node in composition, abort"; d->status = 1; return; } } }
// calculate button is pressed int CcgView::calculate() { QString command; int retval = 0; statusLabel.setText("Calculating..."); ui->pushButtonCalculate->setEnabled(false); if (!globals.validData) { DialogData * data = new DialogData(this,&globals); data->exec(); delete data; ui->pushButtonCalculate->setEnabled(true); statusLabel.setText("Ready"); return -1; } result_filename = globals.dataDirectory + QString(PATH_SEPARATOR) + "result.png"; command = "ccg --dir " + globals.dataDirectory + " --sites " + globals.sitesFilename + " --filename " + result_filename + " --width " + QString::number(image_width) + " --height " + QString::number(image_height) + " --subvertical " + QString::number(subtitle_vertical_position) + " --start " + ui->spinBoxStartYear->text() + " --end " + ui->spinBoxEndYear->text() + " --gas \"" + ui->comboBoxGas->currentText().toLower() + "\""; if (globals.emissionsFilename.length()>0) { command += " --emissions \"" + globals.emissionsFilename + "\""; } if (globals.graphLabel.length()>0) { command += " --label \"" + globals.graphLabel + "\""; } if (ui->checkBoxMinMax->isChecked()) { command += " --minmax"; } if (ui->checkBoxVariance->isChecked()) { command += " --variance"; } if (ui->checkBoxRunningAverage->isChecked()) { command += " --runningaverage"; } if (ui->comboBoxRegion->currentText().contains("Europe")) { command += " --area \"60N,10W,37N,30E\""; } if (ui->comboBoxRegion->currentText().contains("North America")) { command += " --area \"75N,169W,10N,55W\""; } if (ui->comboBoxRegion->currentText().contains("South America")) { command += " --area \"10N,90W,55S,35W\""; } if (ui->comboBoxRegion->currentText().contains("Africa")) { command += " --area \"35N,20W,35S,52E\""; } if (ui->comboBoxRegion->currentText().contains("Asia")) { command += " --area \"80N,35E,5N,179E\""; } if ((ui->comboBoxPlotType->currentText().contains("Scatter")) || (ui->comboBoxPlotType->currentText().contains("Distribution"))) { command += " --distribution"; } if (ui->comboBoxPlotType->currentText().contains("Altitude")) { command += " --altitudes"; } if (ui->comboBoxPlotType->currentText().contains("Change")) { command += " --change"; } if ((ui->comboBoxPlotType->currentText().contains("monthly")) || (ui->comboBoxPlotType->currentText().contains("Monthly"))) { command += " --monthly"; } if (ui->comboBoxRegion->currentText().contains("Arctic Circle")) { command += " --latitudes \"90N,66N\""; } if (ui->comboBoxRegion->currentText().contains("Northern Hemisphere")) { command += " --latitudes \"90N,0N\""; } if (ui->comboBoxRegion->currentText().contains("Southern Hemisphere")) { command += " --latitudes \"0S,90S\""; } if (ui->comboBoxRegion->currentText().contains("Equatorial")) { command += " --latitudes \"10N,10S\""; } qDebug("%s", command.toStdString().c_str()); QThread* thread = new QThread; ThreadCalculate* calc = new ThreadCalculate(); calc->command = command; calc->image_filename = result_filename; calc->moveToThread(thread); connect(thread, SIGNAL(started()), calc, SLOT(process())); connect(calc, SIGNAL(finished()), thread, SLOT(quit())); connect(calc, SIGNAL(finished()), calc, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(calc, SIGNAL(finished()), this, SLOT(showGraph())); thread->start(); return retval; }
CWizDocumentView::CWizDocumentView(CWizExplorerApp& app, QWidget* parent) : INoteView(parent) , m_app(app) , m_userSettings(app.userSettings()) , m_dbMgr(app.databaseManager()) #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_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_splitter = new CWizSplitter(this); m_splitter->addWidget(m_web); m_splitter->addWidget(m_commentWidget); m_web->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); 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())); m_commentWidget->hide(); layoutDoc->addWidget(m_title); 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(); }
bool Commands::Run(const QString & filename, int data_rate, 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_fileName = filename; m_streamer = new Streamer(this, m_fileName, data_rate, 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; }
// this routine will be called now every 10 seconds to update the cartesianplot // however when many data it may take much longer, then suppress any new request void ArchiveCA_Plugin::Callback_UpdateInterface( QMap<QString, indexes> listOfIndexes) { int nbVal; precision = 5; // Index name stdString index_name = "/gfa/archiver-data/archive_PRO_ST/index"; //qDebug() << "====================== ArchiveCA_Plugin::Callback_UpdateInterface"; QMap<QString, indexes>::const_iterator i = listOfIndexes.constBegin(); while (i != listOfIndexes.constEnd()) { QThread *tmpThread = (QThread *) 0; indexes indexNew = i.value(); //qDebug() << i.key() << ": " << indexNew.indexX << indexNew.indexY << indexNew.pv << indexNew.w << endl; nbVal = 0; QMap<QString, QThread *>::iterator j = listOfThreads.find(indexNew.key); while (j !=listOfThreads.end() && j.key() == indexNew.key) { tmpThread = (QThread *) j.value(); ++j; } //qDebug() << "tmpThread" << tmpThread; if((tmpThread != (QThread *) 0) && tmpThread->isRunning()) { //qDebug() << "workerthread is running" << tmpThread->isRunning(); } else { // Get Index name if specified for this widget if(caCartesianPlot* w = qobject_cast<caCartesianPlot *>((QWidget*) indexNew.w)) { QVariant var = w->property("archiverIndex"); if(!var.isNull()) { QString indexName = var.toString(); index_name = qasc(indexName); } else if(indexNew.init){ QString mess("ArchiveCA plugin -- no archiverIndex defined as dynamic property in widget " + w->objectName() + ", defaulting to /gfa/archiver-data/archive_PRO_ST/index"); if(messagewindowP != (MessageWindow *) 0) messagewindowP->postMsgEvent(QtWarningMsg, (char*) qasc(mess)); } } WorkerCA *worker = new WorkerCA; QThread *tmpThread = new QThread; listOfThreads.insert(i.key(), tmpThread); worker->moveToThread(tmpThread); connect(tmpThread, SIGNAL(finished()), worker, SLOT(workerFinish())); connect(tmpThread, SIGNAL(finished()), tmpThread, SLOT(deleteLater()) ); connect(this, SIGNAL(operate( QWidget *, indexes, const stdString)), worker, SLOT(getFromArchive(QWidget *, indexes, stdString))); connect(worker, SIGNAL(resultReady(indexes, int, QVector<double>, QVector<double>, QString)), this, SLOT(handleResults(indexes, int, QVector<double>, QVector<double>, QString))); tmpThread->start(); //qDebug() << "CA emit operate"; emit operate((QWidget *) messagewindowP ,indexNew, index_name); } ++i; } }
void WidgetMain::slotClickUpload() { { //如果存在串口监视的则暂停 if(NULL != pSerialPortTool_) { pSerialPortTool_->closePort(); pSerialPortTool_->close(); } } //加入是否已经设置好串口的判断 if(pSerialSetting_->getBoardType() == tr("Plase Set Arduino Type") || pSerialSetting_->getSerialPort() == tr("Serial Port")) { //在此调出串口设置界面让其设置 createUploadSetting(); } else { UploadWaitForm *p = new UploadWaitForm(this->rect(), this); p->setAttribute(Qt::WA_DeleteOnClose); QSettings settingTmp("./resource/setting.ini", QSettings::IniFormat); QString value = settingTmp.value(tr("Normal/uploader")).toString(); QString filePath; if(value == "ArduinoUploader") { #ifdef Q_OS_MAC QDir dir("./resource/tools/ArduinoUploader/ArduinoUploader.app/Contents/MacOS"); if(!dir.exists("Temp")) { dir.mkdir("Temp"); } filePath = "./resource/tools/ArduinoUploader/ArduinoUploader.app/Contents/MacOS/Temp/code.cpp"; #else QDir dir("./resource/tools/ArduinoUploader"); if(!dir.exists("Temp")) { dir.mkdir("Temp"); } filePath = "./resource/tools/ArduinoUploader/Temp/code.cpp"; #endif } else if(value == "DFRobotUploader") { #ifdef Q_OS_MAC QDir dir("./resource/tools/ArduinoUploader/ArduinoUploader.app/Contents/MacOS"); if(!dir.exists("Temp")) { dir.mkdir("Temp"); } filePath = "./resource/tools/ArduinoUploader/ArduinoUploader.app/Contents/MacOS/Temp/code.cpp"; #else QDir dir("./resource/tools/ArduinoUploader"); if(!dir.exists("Temp")) { dir.mkdir("Temp"); } filePath = "./resource/tools/ArduinoUploader/Temp/code.cpp"; #endif } Uploader *pUpload = new Uploader(filePath, boardIndex_, pSerialSetting_->getSerialPort()); QThread *pThread = new QThread; pUpload->moveToThread(pThread); connect(pThread, SIGNAL(started()), pUpload, SLOT(slotStart())); connect(pUpload, SIGNAL(signalCurrentProgress(float, int)), p, SLOT(slotAdvanceProgress(float,int)), Qt::QueuedConnection); connect(pUpload, SIGNAL(signalBoardError(QString)), p, SLOT(SlotBoardError(QString)), Qt::QueuedConnection); connect(pUpload, SIGNAL(signalTypeConversionError(QString)), p, SLOT(SlotTypeConversionError(QString)), Qt::QueuedConnection); connect(pUpload, SIGNAL(signalPortError(QString)), p, SLOT(SlotPortError(QString)), Qt::QueuedConnection); connect(pUpload, SIGNAL(signalCompileEnd()), p, SLOT(SlotCompileEnd())); connect(p, SIGNAL(signalCancel()), pThread, SLOT(terminate())); p->show(); pThread->start(); } }
void AssignmentClient::readPendingDatagrams() { NodeList* nodeList = NodeList::getInstance(); 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 (packetVersionMatch(receivedPacket)) { if (_currentAssignment) { // have the threaded current assignment handle this datagram QMetaObject::invokeMethod(_currentAssignment, "processDatagram", Qt::QueuedConnection, Q_ARG(QByteArray, receivedPacket), Q_ARG(HifiSockAddr, senderSockAddr)); } else if (packetTypeForPacket(receivedPacket) == PacketTypeCreateAssignment) { if (_currentAssignment) { qDebug() << "Dropping received assignment since we are currently running one."; } else { // construct the deployed assignment from the packet data _currentAssignment = AssignmentFactory::unpackAssignment(receivedPacket); if (_currentAssignment) { qDebug() << "Received an assignment -" << *_currentAssignment; // switch our nodelist domain IP and port to whoever sent us the assignment nodeList->setDomainSockAddr(senderSockAddr); nodeList->setOwnerUUID(_currentAssignment->getUUID()); qDebug() << "Destination IP for assignment is" << nodeList->getDomainIP().toString(); // 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); // move the NodeList to the thread used for the _current assignment nodeList->moveToThread(workerThread); // Starts an event loop, and emits workerThread->started() workerThread->start(); } else { qDebug() << "Received an assignment that could not be unpacked. Re-requesting."; } } } else { // have the NodeList attempt to handle it nodeList->processNodeData(senderSockAddr, receivedPacket); } } } }
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 ); }
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()); 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(ui->fanSpinBox, SIGNAL(valueChanged(int)), printerObj, SLOT(setFan(int)), Qt::QueuedConnection); ui->fanSpinBox->blockSignals(true); //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)), this, SLOT(updateProgress(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); }
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); } } } }
SkpSocketTestWidget::SkpSocketTestWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SkpSocketTestWidget), m_writeSize(0), m_readSize(0), m_sec(0), m_readavgSize(0), m_writavgeSize(0), m_connectNumber(0), m_realConnect(0), m_closeNumber(0), m_errorConnect(0), m_max(0), m_isStart(false), m_autoConnectNumber(0), m_showPrintNumber(0) { ui->setupUi(this); //qDebug() << "main ID" << (qint64)QThread::currentThreadId(); m_autoConnectNumber = 100; m_showPrintNumber = 1000; g_ShowPrintNumber = m_showPrintNumber; ui->autoconnect_lineEdit->setText(QString::number(m_autoConnectNumber)); ui->showPrint_lineEdit->setText(QString::number(m_showPrintNumber)); connect(&m_timer, SIGNAL(timeout()), this, SLOT(skp_on_timer_socket())); connect(ui->startTimer, SIGNAL(clicked()), this, SLOT(skp_on_timeout_start())); connect(ui->stopTimer, SIGNAL(clicked()), this, SLOT(skp_on_timeout_stop())); connect(ui->timerOnce, SIGNAL(clicked()), this, SLOT(skp_on_timer_socket_once())); connect(ui->connectSocket, SIGNAL(clicked()), this, SLOT(skp_on_simple_socket())); connect(ui->socketSend, SIGNAL(clicked()), this, SLOT(skp_on_simple_send())); connect(ui->socketRecv, SIGNAL(clicked()), this, SLOT(skp_on_simple_recv())); connect(ui->socketClose, SIGNAL(clicked()), this, SLOT(skp_on_simple_close())); connect(ui->protocolConn, SIGNAL(clicked()), this, SLOT(skp_on_simple_protocol())); connect(ui->protocolConnClose, SIGNAL(clicked()), this, SLOT(skp_on_simple_protocol_close())); connect(&m_statisticsTimer, SIGNAL(timeout()), this, SLOT(skp_on_print())); ///yefy___ //m_statisticsTimer.start(5000); connect(&m_taskTimer, SIGNAL(timeout()), this, SLOT(skp_on_socket_task_start())); connect(ui->timerTaskStart, SIGNAL(clicked()), this, SLOT(skp_on_timer_task_start())); connect(ui->onceSocketTaskStart, SIGNAL(clicked()), this, SLOT(skp_on_socket_task_start())); connect(ui->ok_pushButton, SIGNAL(clicked()), this, SLOT(skp_on_socket_conf())); for(int i = 0; i < THREAD_NUMBER; i++) { QThread *thread = new QThread(); m_threadList.push_back(thread); thread->start(); while(!thread->isRunning()) { ; } SkpTcpSocketTask *tcpSocketTask = new SkpTcpSocketTask(); tcpSocketTask->moveToThread(thread); connect(this, SIGNAL(skp_sig_create_socket()), tcpSocketTask, SLOT(skpOnCreateSocket())); connect(tcpSocketTask, SIGNAL(skp_sig_connect()), this, SLOT(skp_on_connect())); connect(tcpSocketTask, SIGNAL(skp_sig_quit(qint64, qint64, qint64, qint64)), this, SLOT(skp_on_quit(qint64, qint64, qint64, qint64))); connect(tcpSocketTask, SIGNAL(skp_sig_socket_quit(qint64, qint64, qint64, qint64)), this, SLOT(skp_on_socket_quit(qint64, qint64, qint64, qint64))); } }
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()); } }
void QgsLocator::fetchResults( const QString &string, const QgsLocatorContext &context, QgsFeedback *feedback ) { // 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; if ( searchString.indexOf( ' ' ) > 0 ) { QString prefix = searchString.left( searchString.indexOf( ' ' ) ); if ( mPrefixedFilters.contains( prefix ) && mPrefixedFilters.value( prefix )->enabled() ) { activeFilters << mPrefixedFilters.value( prefix ); searchString = searchString.mid( prefix.length() + 1 ); } } if ( activeFilters.isEmpty() ) { for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) ) { if ( filter->useWithoutPrefix() && filter->enabled() ) activeFilters << filter; } } QList< QgsLocatorFilter *> threadedFilters; for ( QgsLocatorFilter *filter : qgis::as_const( activeFilters ) ) { 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(); }
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 */ device->setBoot("/dev/sda1"); hasMount = utils->mountPartition(device, MNT_BOOT); device->setRoot("/dev/sda2"); device->setBootNeedsFormat(false); } 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 */ if (utils->getOSMCDev() == "vero2" && ! device->hasBootChanged()) { /* Set up LVM */ system("dd if=/dev/zero of=/dev/data bs=1M count=1 conv=fsync"); system("dd if=/dev/zero of=/dev/misc bs=1M count=1 conv=fsync"); system("dd if=/dev/zero of=/dev/system bs=1M count=1 conv=fsync"); system("dd if=/dev/zero of=/dev/cache bs=1M count=1 conv=fsync"); /* Own logo eventually */ system("dd if=/dev/zero of=/dev/logo bs=1M count=1 conv=fsync"); system("pvcreate /dev/data dev/system /dev/cache /dev/misc"); system("vgcreate vero-nand /dev/data /dev/system /dev/cache /dev/misc"); system("lvcreate -n root -l100%FREE vero-nand"); utils->fmtpart(device->getRoot(), "ext4"); } 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") // && utils.getOSMCDev() != "pc" eventually.. -- cause we want boot there too. { 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 { if (! device->doesBootNeedsFormat() && utils->getOSMCDev() != "vero2") { int size = utils->getPartSize(rootBase, device->getBootFS()); 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, preseed); else bc = new BootloaderConfig(device, NULL, utils, logger, preseed); 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(); }
int main(int argc, char* argv[]) { #ifdef Q_WS_X11 QCoreApplication::setAttribute(Qt::AA_X11InitThreads); #endif QGuiApplication app(argc,argv); MainWindow *window; int result; app.setOrganizationName("libosmscout"); app.setOrganizationDomain("libosmscout.sf.net"); app.setApplicationName("StyleEditor"); qRegisterMetaType<RenderMapRequest>(); qRegisterMetaType<DatabaseLoadedResponse>(); qRegisterMetaType<osmscout::TileRef>(); qmlRegisterType<MapWidget>("net.sf.libosmscout.map", 1, 0, "Map"); qmlRegisterType<LocationEntry>("net.sf.libosmscout.map", 1, 0, "Location"); qmlRegisterType<LocationListModel>("net.sf.libosmscout.map", 1, 0, "LocationListModel"); qmlRegisterType<FileIO, 1>("FileIO", 1, 0, "FileIO"); qmlRegisterType<QmlSettings>("net.sf.libosmscout.map", 1, 0, "Settings"); QThread thread; // load online tile providers Settings::GetInstance()->loadOnlineTileProviders( ":/resources/online-tile-providers.json"); // setup paths QString documentsLocation = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); QString cacheLocation = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); QStringList cmdLineArgs = QApplication::arguments(); QStringList mapLookupDirectories; if (cmdLineArgs.size() > 1){ mapLookupDirectories << cmdLineArgs.at(1); }else{ mapLookupDirectories << QDir::currentPath(); mapLookupDirectories << documentsLocation + QDir::separator() + "Maps"; } QString stylesheetFilename; if (cmdLineArgs.size() > 2){ stylesheetFilename = cmdLineArgs.at(2); }else{ if (cmdLineArgs.size() > 1){ stylesheetFilename = cmdLineArgs.at(1) + "standard.oss"; }else{ stylesheetFilename = QString("stylesheets") + QDir::separator() + "standard.oss"; } } QString iconDirectory; if (cmdLineArgs.size() > 3){ iconDirectory = cmdLineArgs.at(3); }else{ if (cmdLineArgs.size() > 1){ iconDirectory = cmdLineArgs.at(1) + "icons"; }else{ iconDirectory = "icons"; } } if (!DBThread::InitializeTiledInstance( mapLookupDirectories, stylesheetFilename, iconDirectory, cacheLocation + QDir::separator() + "OSMScoutTileCache", /* onlineTileCacheSize */ 100, /* offlineTileCacheSize */ 200 )) { std::cerr << "Cannot initialize DBThread" << std::endl; } DBThread* dbThread=DBThread::GetInstance(); window=new MainWindow(dbThread); dbThread->connect(&thread, SIGNAL(started()), SLOT(Initialize())); dbThread->connect(&thread, SIGNAL(finished()), SLOT(Finalize())); dbThread->moveToThread(&thread); thread.start(); result=app.exec(); delete window; QString tmpStylesheet(dbThread->GetStylesheetFilename()+TMP_SUFFIX); if(QFile::exists(tmpStylesheet)){ QFile::remove(tmpStylesheet); } thread.quit(); thread.wait(); DBThread::FreeInstance(); Settings::FreeInstance(); return result; }
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"); }
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; }
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(); }
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); }
// This method is executed in a separate thread // via QtConcurrent::run TreeItem* ITunesFeature::importLibrary() { //Give thread a low priority QThread* thisThread = QThread::currentThread(); thisThread->setPriority(QThread::LowestPriority); //Delete all table entries of iTunes feature ScopedTransaction transaction(m_database); clearTable("itunes_playlist_tracks"); clearTable("itunes_library"); clearTable("itunes_playlists"); transaction.commit(); qDebug() << "ITunesFeature::importLibrary() "; transaction.transaction(); // By default set m_mixxxItunesRoot and m_dbItunesRoot to strip out // file://localhost/ from the URL. When we load the user's iTunes XML // configuration we may replace this with something based on the detected // location of the user's iTunes path but the defaults are necessary in case // their iTunes XML does not include the "Music Folder" key. m_mixxxItunesRoot = ""; m_dbItunesRoot = localhost_token(); //Parse iTunes XML file using SAX (for performance) QFile itunes_file(m_dbfile); if (!itunes_file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Cannot open iTunes music collection"; return NULL; } QXmlStreamReader xml(&itunes_file); TreeItem* playlist_root = NULL; while (!xml.atEnd() && !m_cancelImport) { xml.readNext(); if (xml.isStartElement()) { if (xml.name() == "key") { QString key = xml.readElementText(); if (key == "Music Folder") { if (readNextStartElement(xml)) { guessMusicLibraryMountpoint(xml); } } else if (key == "Tracks") { parseTracks(xml); playlist_root = parsePlaylists(xml); } } } } itunes_file.close(); // Even if an error occured, commit the transaction. The file may have been // half-parsed. transaction.commit(); if (xml.hasError()) { // do error handling qDebug() << "Cannot process iTunes music collection"; qDebug() << "XML ERROR: " << xml.errorString(); if (playlist_root) delete playlist_root; playlist_root = NULL; } return playlist_root; }
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); } } } }
void cleanup() { thread->quit(); worker->deleteLater(); this->deleteLater(); }
TreeItem* TraktorFeature::importLibrary(QString file) { //Give thread a low priority QThread* thisThread = QThread::currentThread(); thisThread->setPriority(QThread::LowPriority); //Invisible root item of Traktor's child model TreeItem* root = NULL; //Delete all table entries of Traktor feature ScopedTransaction transaction(m_database); clearTable("traktor_playlist_tracks"); clearTable("traktor_library"); clearTable("traktor_playlists"); transaction.commit(); transaction.transaction(); QSqlQuery query(m_database); query.prepare("INSERT INTO traktor_library (artist, title, album, year," "genre,comment,tracknumber,bpm, bitrate,duration, location," "rating,key) VALUES (:artist, :title, :album, :year,:genre," ":comment, :tracknumber,:bpm, :bitrate,:duration, :location," ":rating,:key)"); //Parse Trakor XML file using SAX (for performance) QFile traktor_file(file); if (!traktor_file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Cannot open Traktor music collection"; return NULL; } QXmlStreamReader xml(&traktor_file); bool inCollectionTag = false; bool inPlaylistsTag = false; bool isRootFolderParsed = false; int nAudioFiles = 0; while (!xml.atEnd() && !m_cancelImport) { xml.readNext(); if (xml.isStartElement()) { if (xml.name() == "COLLECTION") { inCollectionTag = true; } // Each "ENTRY" tag in <COLLECTION> represents a track if (inCollectionTag && xml.name() == "ENTRY" ) { //parse track parseTrack(xml, query); ++nAudioFiles; //increment number of files in the music collection } if (xml.name() == "PLAYLISTS") { inPlaylistsTag = true; } if (inPlaylistsTag && !isRootFolderParsed && xml.name() == "NODE") { QXmlStreamAttributes attr = xml.attributes(); QString nodetype = attr.value("TYPE").toString(); QString name = attr.value("NAME").toString(); if (nodetype == "FOLDER" && name == "$ROOT") { //process all playlists root = parsePlaylists(xml); isRootFolderParsed = true; } } } if (xml.isEndElement()) { if (xml.name() == "COLLECTION") { inCollectionTag = false; } if (xml.name() == "PLAYLISTS" && inPlaylistsTag) { inPlaylistsTag = false; } } } if (xml.hasError()) { // do error handling qDebug() << "Cannot process Traktor music collection"; if (root) delete root; return NULL; } qDebug() << "Found: " << nAudioFiles << " audio files in Traktor"; //initialize TraktorTableModel transaction.commit(); return root; }