Exemplo n.º 1
0
void KPAOS4Checker::check()
{
    QString inPort(Settings::get().getMidiInPort());
    QString outPort(Settings::get().getMidiOutPort());

    if(inPort.isEmpty() || outPort.isEmpty())
    {
        SettingsDialog settingsDialog(nullptr);
        settingsDialog.exec();
        inPort = Settings::get().getMidiInPort();
        outPort = Settings::get().getMidiOutPort();
    }

    if(Midi::get().openPorts(inPort, outPort))
    {
        QEventLoop el;
        el.connect(this, &KPAOS4Checker::stopLoop, &el, &QEventLoop::quit);
        el.connect(&stompDelayObj, &Stomp::onOffReceived, this, &KPAOS4Checker::onOfReceived);
        el.connect(mTimer, &QTimer::timeout, this, &KPAOS4Checker::timerTimeout);
        mTimer->start(500);
        stompDelayObj.requestOnOff();
        el.exec();
        el.disconnect(this, &KPAOS4Checker::stopLoop, &el, &QEventLoop::quit);
        el.disconnect(&stompDelayObj, &Stomp::onOffReceived, this, &KPAOS4Checker::onOfReceived);
        el.disconnect(mTimer, &QTimer::timeout, this, &KPAOS4Checker::timerTimeout);
    }
}
Exemplo n.º 2
0
int main(int argc, char** argv) try
{
    if (argc < 2) {
        std::cerr << "usage: " << argv[0] << " path" << std::endl;
        return 1;
    }
 
    QCoreApplication app(argc, argv);
    QEventLoop loop;
    
    QString const path = QFile::decodeName(argv[1]);
    
    lastfm::Track t = lastfm::taglib(path); //see contrib //TODO mbid
    lastfm::Fingerprint fp(t);
    if (fp.id().isNull()) {
        lastfm::FingerprintableSource* src = factory(typeOf(path));
        fp.generate(src);
        QNetworkReply* reply = fp.submit();
        loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
        fp.decode(reply);
    }
    
    QNetworkReply* reply = fp.id().getSuggestions();
    loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
    
    std::cout << reply->readAll().data() << std::endl; //returns XML
    return 0;
}
catch (std::exception& e)
{
    std::cerr << e.what() << std::endl;
}
Exemplo n.º 3
0
void CatalogTest::testList()
{
    QNetworkReply* reply = Echonest::Catalog::list();

    qDebug() << reply->url().toString();
    QCOMPARE( reply->url().toString(), QLatin1String( "http://developer.echonest.com/api/v4/catalog/list?api_key=JGJCRKWLXLBZIFAZB&format=xml" ) );

    QEventLoop loop;
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();

    Echonest::Catalogs catalogs = Echonest::Catalog::parseList( reply );
    qDebug() << catalogs.size();
    qDebug() << catalogs;
    QVERIFY( !catalogs.isEmpty() );

    // Now limit it to just 1, but the second one.
    reply = Echonest::Catalog::list( 1, 1 );

    qDebug() << reply->url().toString();
    QCOMPARE( reply->url().toString(), QLatin1String( "http://developer.echonest.com/api/v4/catalog/list?api_key=JGJCRKWLXLBZIFAZB&format=xml&results=1&start=1" ) );

    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();

    catalogs = Echonest::Catalog::parseList( reply );
    qDebug() << catalogs.size();
    QCOMPARE( catalogs.size(), 1 );
}
Exemplo n.º 4
0
http::Response * Server::wait(QFuture<http::Response *> future) {
	
	QEventLoop loop;
	
	// Interrrupt the event loop when the result is available
	QFutureWatcher<http::Response *> watcher;
	watcher.setFuture(future);
	loop.connect(&watcher, SIGNAL(finished()), SLOT(quit()));
	
	// Prevent infinite loop if the future completes before we start the loop
	QTimer timer;
	loop.connect(&timer, SIGNAL(timeout()), SLOT(quit()));
	timer.setSingleShot(false);
	timer.start(1000);
	
	// Process events while waiting so that the UI stays responsive
	while(!future.isFinished()) {
		loop.exec();
	}
	
	http::Response * response = future.result();
	
	if(response->ok()) {
		m_lastErrorString.clear();
	} else if(!response->error().empty()) {
		m_lastErrorString = toQString(response->error());
	} else if(!response->data().empty()) {
		m_lastErrorString = toQString(response->data());
	} else {
		m_lastErrorString = "HTTP Error " + QString::number(response->status());
	}
	
	return response;
}
Exemplo n.º 5
0
void CatalogTest::testCreateUpdateDeleteArtist()
{
    try {
        QNetworkReply* reply = Echonest::Catalog::create( QLatin1String( "unittest_catalog_artist_X" ), Echonest::CatalogTypes::Artist );
    //
        QEventLoop loop;
        loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
        loop.exec();

        m_artistC = Echonest::Catalog::parseCreate( reply );
        qDebug() << "CREATED NEW ARTIST CATALOG:" << m_artistC;
        QVERIFY( !m_artistC.id().isEmpty() );
        QVERIFY( !m_artistC.name().isEmpty() );

    //         c = Echonest::Catalog( "CAPRWVK12BFA1A6F17" );

        Echonest::CatalogUpdateEntry entry;
        entry.setArtistName( QLatin1String( "Balmorhea" ) );
        entry.setGenre( QLatin1String( "Post Rock" ) );
        entry.setAction( Echonest::CatalogTypes::Update );
        Echonest::CatalogUpdateEntry entry2;
        entry2.setArtistName( QLatin1String( "Mono" ) );
        entry2.setGenre( QLatin1String( "Post Rock" ) );
        entry2.setAction( Echonest::CatalogTypes::Update );
        Echonest::CatalogUpdateEntries entries;
        entries << entry << entry2;

        reply = m_artistC.update( entries );
        loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
        loop.exec();

        QByteArray ticket = Echonest::Catalog::parseTicket( reply );
        qDebug() << ticket;

        QVERIFY( !ticket.isEmpty() );
        // now check the ticket status after 5s
        QTest::qWait( 10000 );
        reply = Echonest::Catalog::status( ticket );
        loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
        loop.exec();
        Echonest::CatalogStatus cs = Echonest::Catalog::parseStatus( reply );
        qDebug() << "Catalog status:" << cs.status << cs.items_updated << cs.items;

        // now read the catalog
        reply = m_artistC.readSongCatalog();
        loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
        loop.exec();
        m_artistC.parseRead( reply );
        qDebug() << m_artistC;
        QCOMPARE( m_artistC.artists().size(), 2 );
    } catch( const Echonest::ParseError& e ) {
        qWarning() << "Got exception, failing:" << e.what();
        QVERIFY( false );
    }
}
Exemplo n.º 6
0
// http://stackoverflow.com/questions/2629055/qtestlib-qnetworkrequest-not-executed
bool waitForSignal(QObject *sender, const char *signal, int timeout = 1000) {
	QEventLoop loop;
	QTimer timer;
	timer.setInterval(timeout);
	timer.setSingleShot(true);

	loop.connect(sender, signal, SLOT(quit()));
	loop.connect(&timer, SIGNAL(timeout()), SLOT(quit()));
	timer.start();
	loop.exec();

	return timer.isActive();
}
Exemplo n.º 7
0
void CatalogTest::cleanupTestCase()
{
    // delete the two test catalogs we created
    qDebug() << "Deleting catalogs!";
    QNetworkReply* reply = m_songC.deleteCatalog();
    QEventLoop loop;
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();

    reply = m_artistC.deleteCatalog();
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();
    return;
}
Exemplo n.º 8
0
/*!
 * @brief       Add a user
 * @param[in]   username
 * @param[in]   password
 * @param[in]   access_level
 * @return      Returns a string, if successful "OK" otherwise an error
 */
QString AdminRPC::addUser(const QString &username, const QString &password, int access_level)
{
    QString result;
    uint64_t fake_session_token = s_last_token++;
    int token = static_cast<int>(fake_session_token);

    // Create and insert a record of this request into m_completion_state
    m_completion_state.insert(token, "");

    qCDebug(logRPC) << "addUser call in progress";

    EventProcessor *tgt = HandlerLocator::getAuthDB_Handler();
    tgt->putq(new CreateAccountMessage({username, password, access_level}, fake_session_token, this));

    QTimer response_timer;
    QTimer timeout;
    timeout.setSingleShot(true);
    QEventLoop loop;
    loop.connect(&timeout, SIGNAL(timeout()), SLOT(quit()));
    loop.connect(this, SIGNAL(responseRecieved()), SLOT(quit()));
    loop.connect(&response_timer, &QTimer::timeout, [=] () {
        if (!m_completion_state[token].isEmpty())
        {
            emit responseRecieved(); // Response recieved we can break out of event loop
            return;
        }
        else
            return;
    });
    response_timer.start(500); // Checks completion status every 500ms
    timeout.start(5000); // Timeout of 5 seconds in case something goes wrong.
    loop.exec();

    if (!m_completion_state[token].isEmpty())
    {
        result = m_completion_state[token];
        response_timer.stop();
        m_completion_state.remove(token); // Tidy up
    }
    else
    {
        result = "Something went wrong";
        response_timer.stop();
        m_completion_state.remove(token);
    }

    return result;
}
Exemplo n.º 9
0
void PlaylistTest::testStatic2()
{
    DynamicPlaylist::PlaylistParams p;
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::Artist, QLatin1String( "tallest man on earth" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::Artist, QLatin1String( "bon iver" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::Artist, QLatin1String( "mumford and sons" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::Artist, QLatin1String( "Florence + The Machine" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::ArtistMaxFamiliarity, 0.4 ) );
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::MinDanceability, 0.7 ) );
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::Type, Echonest::DynamicPlaylist::ArtistType ) );
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::SongInformation, QVariant::fromValue( Echonest::SongInformation( Echonest::SongInformation::Hotttnesss | Echonest::SongInformation::ArtistHotttnesss | Echonest::SongInformation::ArtistFamiliarity ) ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( DynamicPlaylist::Results, 4 ) );

    QNetworkReply* reply = DynamicPlaylist::staticPlaylist( p );

    qDebug() << reply->url().toEncoded();
    QCOMPARE( QLatin1String( reply->url().toEncoded() ), QLatin1String( "http://developer.echonest.com/api/v4/playlist/static?api_key=JGJCRKWLXLBZIFAZB&format=xml&artist=tallest+man+on+earth&artist=bon+iver&artist=mumford+and+sons&artist=Florence+%2B+The+Machine&artist_max_familiarity=0.4&min_danceability=0.7&type=artist&bucket=song_hotttnesss&bucket=artist_hotttnesss&bucket=artist_familiarity&results=4" ) );

    QEventLoop loop;
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();
    SongList songs = DynamicPlaylist::parseStaticPlaylist( reply );

//     qDebug() << "Got songs;" << songs;
    QVERIFY( songs.size() > 1 );
    Q_FOREACH( const Song& song, songs ) {
        QVERIFY( !song.id().isEmpty() );
    }
Exemplo n.º 10
0
bool ExportCommon::download(ExportContext *ctx, QString url, QString to) {
	QString filePath = QDir::cleanPath(ctx->outputDir.absoluteFilePath(to));
	QFileInfo fi = QFileInfo(filePath);
	ctx->outputDir.mkpath(fi.dir().absolutePath());
	QFile file(filePath);
	if (file.exists())
		return true;
	if (file.open(QIODevice::WriteOnly)) {
		exportInfo("Downloading %s\n", url.toStdString().c_str());

		QUrl imageUrl(url);
		FileDownloader *m_pImgCtrl = new FileDownloader(imageUrl);

		QEventLoop loop;
		loop.connect(m_pImgCtrl, SIGNAL(downloaded()), &loop, SLOT(quit()));
		loop.exec();

		QByteArray data = m_pImgCtrl->downloadedData();

		delete m_pImgCtrl;

		if (data.length() > 0) {
			file.write(data);
			return true;
		} else
			exportError("Failed to download %s\n", url.toStdString().c_str());
	} else
		exportError("Can't open file %s\n", to.toStdString().c_str());
	return false;
}
Exemplo n.º 11
0
void MainWindow::sendData(const QString &data)
{
    // Quick error checks before sending
    if (data.isEmpty())
    {
        showError(tr("Can't process audio ;("));
        return;
    }

    ui->label->setText(tr("Sending data..."));
    ui->recordButton->setIcon(*iconNetwork);
    repaint();

#ifdef USE_LIBECHONEST
    QNetworkReply * reply = Echonest::Song::identify(data);
    QEventLoop loop;
    loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
    loop.exec();

    QByteArray answer(reply->readAll());
#else
    EchoNestRequest request(this, nam, API_KEY, QString("4.11"));
    EchoNestSong * song = request.identifySong(data);
#endif

    emit(resultReady(song));
}
Exemplo n.º 12
0
void SongLoader::LoadRemote() {
  qLog(Debug) << "Loading remote file" << url_;

  // It's not a local file so we have to fetch it to see what it is.  We use
  // gstreamer to do this since it handles funky URLs for us (http://, ssh://,
  // etc) and also has typefinder plugins.
  // First we wait for typefinder to tell us what it is.  If it's not text/plain
  // or text/uri-list assume it's a song and return success.
  // Otherwise wait to get 512 bytes of data and do magic on it - if the magic
  // fails then we don't know what it is so return failure.
  // If the magic succeeds then we know for sure it's a playlist - so read the
  // rest of the file, parse the playlist and return success.

  timeout_timer_->start(timeout_);

  // Create the pipeline - it gets unreffed if it goes out of scope
  std::shared_ptr<GstElement> pipeline(gst_pipeline_new(nullptr),
                                       std::bind(&gst_object_unref, _1));

  // Create the source element automatically based on the URL
  GstElement* source = gst_element_make_from_uri(
      GST_URI_SRC, url_.toEncoded().constData(), nullptr, nullptr);
  if (!source) {
    qLog(Warning) << "Couldn't create gstreamer source element for"
                  << url_.toString();
    return;
  }

  // Create the other elements and link them up
  GstElement* typefind = gst_element_factory_make("typefind", nullptr);
  GstElement* fakesink = gst_element_factory_make("fakesink", nullptr);

  gst_bin_add_many(GST_BIN(pipeline.get()), source, typefind, fakesink,
                   nullptr);
  gst_element_link_many(source, typefind, fakesink, nullptr);

  // Connect callbacks
  GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline.get()));
  CHECKED_GCONNECT(typefind, "have-type", &TypeFound, this);
  gst_bus_set_sync_handler(bus, BusCallbackSync, this, NULL);
  gst_bus_add_watch(bus, BusCallback, this);

  // Add a probe to the sink so we can capture the data if it's a playlist
  GstPad* pad = gst_element_get_static_pad(fakesink, "sink");
  gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_BUFFER, &DataReady, this, NULL);
  gst_object_unref(pad);

  QEventLoop loop;
  loop.connect(this, SIGNAL(LoadRemoteFinished()), SLOT(quit()));

  // Start "playing"
  gst_element_set_state(pipeline.get(), GST_STATE_PLAYING);
  pipeline_ = pipeline;

  // Wait until loading is finished
  loop.exec();
}
Exemplo n.º 13
0
void EventQueue::run() {
	QEventLoop loop;
	loop.connect(this, SIGNAL(_stop()), SLOT(quit()));
	Task bgTask;
	this->_bgTask = &bgTask;
	this->_bgTask->setMouseArea(this->_view);
	emit this->_started();
	loop.exec();
	this->_bgTask = nullptr;
	emit this->_stopped();
}
Exemplo n.º 14
0
void LedDevicePhilipsHue::put(QString route, QString content) {
	QString url = QString("http://%1/api/%2/%3").arg(host).arg(username).arg(route);
	// Perfrom request
	QNetworkRequest request(url);
	QNetworkReply* reply = manager->put(request, content.toLatin1());
	// Connect finished signal to quit slot of the loop.
	QEventLoop loop;
	loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
	// Go into the loop until the request is finished.
	loop.exec();
}
Exemplo n.º 15
0
char *gui_debug_prompt()
{
    #ifdef MOBILE_UI
        return const_cast<char*>("c");
    #else
        QEventLoop ev;
        ev.connect(main_window, SIGNAL(debuggerCommand()), &ev, SLOT(quit()));
        ev.exec();
        return main_window->debug_command.data();
    #endif
}
Exemplo n.º 16
0
static int qt_serial_read(serial_t *device, void* data, unsigned int size)
{
#if defined(Q_OS_WIN)
	if (device == NULL)
		return DC_STATUS_INVALIDARGS;

	unsigned int nbytes = 0;
	int rc;

	while (nbytes < size) {
		rc = recv (device->socket, (char *) data + nbytes, size - nbytes, 0);

		if (rc < 0) {
			return -1; // Error during recv call.
		} else if (rc == 0) {
			break; // EOF reached.
		}

		nbytes += rc;
	}

	return nbytes;
#else
	if (device == NULL || device->socket == NULL)
		return DC_STATUS_INVALIDARGS;

	unsigned int nbytes = 0;
	int rc;

	while(nbytes < size)
	{
		device->socket->waitForReadyRead(device->timeout);

		rc = device->socket->read((char *) data + nbytes, size - nbytes);

		if (rc < 0) {
			if (errno == EINTR || errno == EAGAIN)
			    continue; // Retry.

			return -1; // Something really bad happened :-(
		} else if (rc == 0) {
			// Wait until the device is available for read operations
			QEventLoop loop;
			loop.connect(device->socket, SIGNAL(readyRead()), SLOT(quit()));
			loop.exec();
		}

		nbytes += rc;
	}

	return nbytes;
#endif
}
void LedDevicePhilipsHue::put(QString route, QString content) {
	QString url = getUrl(route);
	// Perfrom request
	QNetworkRequest request(url);
	QNetworkReply* reply = manager->put(request, content.toLatin1());
	// Connect finished signal to quit slot of the loop.
	QEventLoop loop;
	loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
	// Go into the loop until the request is finished.
	loop.exec();
	// Free space.
	reply->deleteLater();
}
Exemplo n.º 18
0
QByteArray LedDevicePhilipsHue::get(QString route) {
	QString url = QString("http://%1/api/%2/%3").arg(host).arg(username).arg(route);
	// Perfrom request
	QNetworkRequest request(url);
	QNetworkReply* reply = manager->get(request);
	// Connect requestFinished signal to quit slot of the loop.
	QEventLoop loop;
	loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
	// Go into the loop until the request is finished.
	loop.exec();
	// Read all data of the response.
	return reply->readAll();
}
Exemplo n.º 19
0
bool SessionServer::waitForNewConnection( int msec, bool * timedOut ) {
	QEventLoop wait;
	QTimer timer;
	timer.setSingleShot( true );
	timer.setInterval( msec );
	wait.connect( &timer, SIGNAL( timeout() ), SLOT( quit() ) );
	wait.connect( this, SIGNAL( newConnection() ), SLOT( quit() ) );
	wait.exec();
	if( !timer.isActive() ) {
		// timer timeout
		if( timedOut != nullptr ) {
			*timedOut = true;
		}
		return false;
	} else {
		// new connections
		if( timedOut != nullptr ) {
			*timedOut = false;
		}
		timer.stop();
		return true;
	}
}
Exemplo n.º 20
0
QNetworkReply *AccelTreeResourceLoader::load(const QUrl &uri,
                                             QNetworkAccessManager *const networkManager,
                                             const ReportContext::Ptr &context, ErrorHandling errorHandling)

{
    Q_ASSERT(networkManager);
    Q_ASSERT(uri.isValid());

    const bool ftpSchemeUsed = (uri.scheme() == QStringLiteral("ftp"));
    // QNAM doesn't have support for SynchronousRequestAttribute in its ftp backend.
    QEventLoop ftpNetworkLoop;
    QNetworkRequest request(uri);
    if (!ftpSchemeUsed)
        request.setAttribute(QNetworkRequest::SynchronousRequestAttribute, true);
    QNetworkReply *const reply = networkManager->get(request);
    if (ftpSchemeUsed) {
        ftpNetworkLoop.connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(quit()));
        ftpNetworkLoop.connect(reply, SIGNAL(finished()), SLOT(quit()));
        ftpNetworkLoop.exec(QEventLoop::ExcludeUserInputEvents);
    }

    if (reply->error() != QNetworkReply::NoError) {
        const QString errorMessage(escape(reply->errorString()));

        /* Note, we delete reply before we exit this function with error(). */
        delete reply;

        const QSourceLocation location(uri);

        if(context && (errorHandling == FailOnError))
            context->error(errorMessage, ReportContext::FODC0002, location);

        return 0;
    } else
        return reply;
}
Exemplo n.º 21
0
void CatalogTest::testProfile()
{
    Echonest::Catalog c( "CAWRKLJ12BF92BC7C3" );
    QNetworkReply* reply = c.profile();

    qDebug() << reply->url().toString();
    QCOMPARE( reply->url().toString(), QLatin1String( "http://developer.echonest.com/api/v4/catalog/profile?api_key=JGJCRKWLXLBZIFAZB&format=xml&id=CAWRKLJ12BF92BC7C3" ) );

    QEventLoop loop;
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();

    c.parseProfile( reply );
    qDebug() << c;
    QCOMPARE( c.total(), 3 );
}
QByteArray LedDevicePhilipsHue::get(QString route) {
	QString url = getUrl(route);
	// Perfrom request
	QNetworkRequest request(url);
	QNetworkReply* reply = manager->get(request);
	// Connect requestFinished signal to quit slot of the loop.
	QEventLoop loop;
	loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
	// Go into the loop until the request is finished.
	loop.exec();
	// Read all data of the response.
	QByteArray response = reply->readAll();
	// Free space.
	reply->deleteLater();
	// Return response
	return response;
}
Exemplo n.º 23
0
void Vkeybord::slotEnter()
{
    m_lbWaitKeyIn->setText(ui->lineEdit->text());
    qDebug()<<"parent name : "<<m_lbWaitKeyIn->parent()->objectName()<<" ,lb objname : "<<m_lbWaitKeyIn->objectName()<<" lbText: "<<m_lbWaitKeyIn->text();

    ui->lineEdit->setText("");
    m_ani->setStartValue(QPoint(0,0));
    m_ani->setEndValue(QPoint(0,height()));

    QEventLoop loop;
    loop.connect(m_ani,SIGNAL(finished()),&loop,SLOT(quit()));
    m_ani->start();
    loop.exec();
    hide();

    loop.disconnect();
}
void CWizDocumentStatusCheckThread::downloadData(const QString& strUrl)
{
    QNetworkAccessManager net;
    QNetworkReply* reply = net.get(QNetworkRequest(strUrl));

    QEventLoop loop;
    loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
    loop.exec();

    if (reply->error()) {
        Q_EMIT checkFinished(QString(), QStringList());
        reply->deleteLater();
        return;
    }

    rapidjson::Document d;
    d.Parse<0>(reply->readAll().constData());
    if (d.IsArray())
    {
        QStringList strList;
        QTextCodec* codec = QTextCodec::codecForName("UTF-8");
        QTextDecoder* encoder = codec->makeDecoder();
        for (rapidjson::SizeType i = 0; i < d.Size(); i++)
        {
            const rapidjson::Value& u = d[i];
            strList.append(encoder->toUnicode(u.GetString(), u.GetStringLength()));
        }
        //
        {
            QMutexLocker lock(&m_mutexWait);
            if (strUrl.indexOf(m_strGUID) != -1)
            {
                emit checkFinished(m_strGUID, strList);
            }
            else
            {
                needRecheck();
            }
        }
        reply->deleteLater();
        return;
    }
    Q_EMIT checkFinished(QString(), QStringList());
    reply->deleteLater();
}
bool QConnectedReplicaPrivate::waitForFinished(const QRemoteObjectPendingCall& call, int timeout)
{
    if (!call.d->watcherHelper)
        call.d->watcherHelper.reset(new QRemoteObjectPendingCallWatcherHelper);

    call.d->mutex.unlock();

    QEventLoop loop;
    loop.connect(call.d->watcherHelper.data(), SIGNAL(finished()), SLOT(quit()));
    QTimer::singleShot(timeout, &loop, SLOT(quit()));

    // enter the event loop and wait for a reply
    loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);

    call.d->mutex.lock();

    return call.d->error != QRemoteObjectPendingCall::InvalidMessage;
}
Exemplo n.º 26
0
void QSpotifySession::initiateQuit()
{
    qDebug() << "QSpotifySession::initiateQuit";
    stop();
    m_audioThread->quit();
    m_audioThread->wait();
    if(!m_isLoggedIn) {
        this->deleteLater();
        return;
    }
    QEventLoop evLoop;
    evLoop.connect(this, SIGNAL(readyToQuit()), SLOT(quit()));
    m_aboutToQuit = true;
    QSpotifyCacheManager::instance().clearTables();
    logout(true);
    evLoop.exec();
    this->deleteLater();
}
Exemplo n.º 27
0
QNetworkReply *filterNetworkAccessModule::Get()
{
    QUrl url(this->requestURL);
    QNetworkRequest req(url);

    this->reply = netManager->get(req);

    connect(reply, SIGNAL(finished()), this, SLOT(networkReply()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError)));

    {
        QEventLoop loop;
        loop.connect(this, SIGNAL(dataProcessed()), SLOT(quit()));
//        std::cout << "...in event loop..." << std::endl;
        loop.exec();

//        std::cout << "EVENT LOOP HAS EXITED" << std::endl;
    }
    return this->reply;
}
Exemplo n.º 28
0
KisImportExportFilter::ConversionStatus KisAnimationExporter::exportAnimation()
{

    if (!m_d->batchMode) {
        emit m_d->document->statusBarMessage(i18n("Export frames"));
        emit m_d->document->sigProgress(0);
        connect(m_d->document, SIGNAL(sigProgressCanceled()), this, SLOT(cancel()));
    }
    m_d->status = KisImportExportFilter::OK;
    m_d->exporting = true;
    m_d->currentFrame = m_d->firstFrame;
    connect(m_d->image->animationInterface(), SIGNAL(sigFrameReady(int)), this, SLOT(frameReadyToCopy(int)), Qt::DirectConnection);
    m_d->image->animationInterface()->requestFrameRegeneration(m_d->currentFrame, m_d->image->bounds());

    QEventLoop loop;
    loop.connect(this, SIGNAL(sigFinished()), SLOT(quit()));
    loop.exec();

    return m_d->status;
}
Exemplo n.º 29
0
void PlaylistTest::testStatic1()
{
    DynamicPlaylist::PlaylistParams p;
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Artist, QLatin1String( "tallest man on earth" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Artist, QLatin1String( "bon iver" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Artist, QLatin1String( "mumford and sons" ) ) );
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Type, Echonest::DynamicPlaylist::ArtistRadioType ) );
    p.append( DynamicPlaylist::PlaylistParamData( Echonest::DynamicPlaylist::Results, 10 ) );

    QNetworkReply* reply = DynamicPlaylist::staticPlaylist( p );

    qDebug() << reply->url().toString();
    QVERIFY( reply->url().toString() == QLatin1String( "http://developer.echonest.com/api/v4/playlist/static?api_key=JGJCRKWLXLBZIFAZB&format=xml&artist=tallest+man+on+earth&artist=bon+iver&artist=mumford+and+sons&type=artist-radio&results=10" ) );

    QEventLoop loop;
    loop.connect( reply, SIGNAL(finished()), SLOT(quit()) );
    loop.exec();
    SongList songs = DynamicPlaylist::parseStaticPlaylist( reply );

    QVERIFY( songs.size() == 10 );
    Q_FOREACH( const Song& song, songs )
        QVERIFY( !song.id().isEmpty() );

}
Exemplo n.º 30
0
static int qt_serial_open(serial_t **out, dc_context_t *context, const char* devaddr)
{
	if (out == NULL)
		return DC_STATUS_INVALIDARGS;

	// Allocate memory.
	serial_t *serial_port = (serial_t *) malloc (sizeof (serial_t));
	if (serial_port == NULL) {
		return DC_STATUS_NOMEMORY;
	}

	// Library context.
	serial_port->context = context;

	// Default to blocking reads.
	serial_port->timeout = -1;

#if defined(Q_OS_WIN)
	// Create a RFCOMM socket
	serial_port->socket = ::socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);

	if (serial_port->socket == INVALID_SOCKET) {
		free(serial_port);
		return DC_STATUS_IO;
	}

	SOCKADDR_BTH socketBthAddress;
	int socketBthAddressBth = sizeof (socketBthAddress);
	char *address = strdup(devaddr);

	ZeroMemory(&socketBthAddress, socketBthAddressBth);
	qDebug() << "Trying to connect to address " << devaddr;

	if (WSAStringToAddressA(address,
				AF_BTH,
				NULL,
				(LPSOCKADDR) &socketBthAddress,
				&socketBthAddressBth
				) != 0) {
		qDebug() << "FAiled to convert the address " << address;
		free(address);

		return DC_STATUS_IO;
	}

	free(address);

	socketBthAddress.addressFamily = AF_BTH;
	socketBthAddress.port = BT_PORT_ANY;
	memset(&socketBthAddress.serviceClassId, 0, sizeof(socketBthAddress.serviceClassId));
	socketBthAddress.serviceClassId = SerialPortServiceClass_UUID;

	// Try to connect to the device
	if (::connect(serial_port->socket,
		      (struct sockaddr *) &socketBthAddress,
		      socketBthAddressBth
		      ) != 0) {
		qDebug() << "Failed to connect to device";

		return DC_STATUS_NODEVICE;
	}

	qDebug() << "Succesfully connected to device";
#else
	// Create a RFCOMM socket
	serial_port->socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);

	// Wait until the connection succeeds or until an error occurs
	QEventLoop loop;
	loop.connect(serial_port->socket, SIGNAL(connected()), SLOT(quit()));
	loop.connect(serial_port->socket, SIGNAL(error(QBluetoothSocket::SocketError)), SLOT(quit()));

	// Create a timer. If the connection doesn't succeed after five seconds or no error occurs then stop the opening step
	QTimer timer;
	int msec = 5000;
	timer.setSingleShot(true);
	loop.connect(&timer, SIGNAL(timeout()), SLOT(quit()));

#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
	// First try to connect on RFCOMM channel 1. This is the default channel for most devices
	QBluetoothAddress remoteDeviceAddress(devaddr);
	serial_port->socket->connectToService(remoteDeviceAddress, 1);
	timer.start(msec);
	loop.exec();

	if (serial_port->socket->state() == QBluetoothSocket::ConnectingState) {
		// It seems that the connection on channel 1 took more than expected. Wait another 15 seconds
		qDebug() << "The connection on RFCOMM channel number 1 took more than expected. Wait another 15 seconds.";
		timer.start(3 * msec);
		loop.exec();
	} else if (serial_port->socket->state() == QBluetoothSocket::UnconnectedState) {
		// Try to connect on channel number 5. Maybe this is a Shearwater Petrel2 device.
		qDebug() << "Connection on channel 1 failed. Trying on channel number 5.";
		serial_port->socket->connectToService(remoteDeviceAddress, 5);
		timer.start(msec);
		loop.exec();

		if (serial_port->socket->state() == QBluetoothSocket::ConnectingState) {
			// It seems that the connection on channel 5 took more than expected. Wait another 15 seconds
			qDebug() << "The connection on RFCOMM channel number 5 took more than expected. Wait another 15 seconds.";
			timer.start(3 * msec);
			loop.exec();
		}
	}
#elif defined(Q_OS_ANDROID) || (QT_VERSION >= 0x050500 && defined(Q_OS_MAC))
	// Try to connect to the device using the uuid of the Serial Port Profile service
	QBluetoothAddress remoteDeviceAddress(devaddr);
	serial_port->socket->connectToService(remoteDeviceAddress, QBluetoothUuid(QBluetoothUuid::SerialPort));
	timer.start(msec);
	loop.exec();

	if (serial_port->socket->state() == QBluetoothSocket::ConnectingState ||
	    serial_port->socket->state() == QBluetoothSocket::ServiceLookupState) {
		// It seems that the connection step took more than expected. Wait another 20 seconds.
		qDebug() << "The connection step took more than expected. Wait another 20 seconds";
		timer.start(4 * msec);
		loop.exec();
	}
#endif
	if (serial_port->socket->state() != QBluetoothSocket::ConnectedState) {

		// Get the latest error and try to match it with one from libdivecomputer
		QBluetoothSocket::SocketError err = serial_port->socket->error();
		qDebug() << "Failed to connect to device " << devaddr << ". Device state " << serial_port->socket->state() << ". Error: " << err;

		free (serial_port);
		switch(err) {
		case QBluetoothSocket::HostNotFoundError:
		case QBluetoothSocket::ServiceNotFoundError:
			return DC_STATUS_NODEVICE;
		case QBluetoothSocket::UnsupportedProtocolError:
			return DC_STATUS_PROTOCOL;
#if QT_VERSION >= 0x050400
		case QBluetoothSocket::OperationError:
			return DC_STATUS_UNSUPPORTED;
#endif
		case QBluetoothSocket::NetworkError:
			return DC_STATUS_IO;
		default:
			return QBluetoothSocket::UnknownSocketError;
		}
	}
#endif
	*out = serial_port;

	return DC_STATUS_SUCCESS;
}