Ejemplo n.º 1
3
QVariant SearchTrackModel::data(const QModelIndex &index, int role) const
{
    QSharedPointer<SongView> s = mMatchingSongs.at(index.row());
    return QVariant::fromValue(s.data());
}
Ejemplo n.º 2
1
void RPolyline::appendShape(const RShape& shape, bool prepend) {
//    const RDirected* directed = dynamic_cast<const RDirected*>(&shape);
//    if (directed==NULL) {
//        qWarning() << "RPolyline::appendShape: shape is not a line, arc or polyline: " << shape;
//        return;
//    }

    const RPolyline* pl = dynamic_cast<const RPolyline*>(&shape);
    if (pl!=NULL) {
        if (prepend) {
            for (int i=pl->countSegments()-1; i>=0; --i) {
                QSharedPointer<RShape> s = pl->getSegmentAt(i);
                if (s.isNull()) {
                    continue;
                }
                prependShape(*s);
            }
        }
        else {
            for (int i=0; i<pl->countSegments(); ++i) {
                QSharedPointer<RShape> s = pl->getSegmentAt(i);
                if (s.isNull()) {
                    continue;
                }
                appendShape(*s);
            }
        }
        return;
    }

    const RDirected* directed = NULL;
    double bulge = 0.0;

    const RLine* line = dynamic_cast<const RLine*>(&shape);
    if (line!=NULL) {
        directed = line;
    }
    else {
        const RArc* arc = dynamic_cast<const RArc*>(&shape);
        if (arc!=NULL) {
            bulge = arc->getBulge();
            directed = arc;
        }
    }

    if (directed==NULL) {
        qWarning() << "RPolyline::appendShape: shape is not a line, arc or polyline: " << shape;
        return;
    }

    RVector connectionPoint;
    RVector nextPoint;
    double gap;
    if (prepend) {
        connectionPoint = directed->getEndPoint();
        nextPoint = directed->getStartPoint();
        if (vertices.size()==0) {
            appendVertex(connectionPoint);
        }
        gap = vertices.first().getDistanceTo(connectionPoint);
    }
    else {
        connectionPoint = directed->getStartPoint();
        nextPoint = directed->getEndPoint();
        if (vertices.size()==0) {
            appendVertex(connectionPoint);
        }
        gap = vertices.last().getDistanceTo(connectionPoint);
    }

    if (!RMath::fuzzyCompare(gap, 0.0, 1.0e-4)) {
        qWarning() << "RPolyline::appendShape: arc or line not connected to polyline, gap: " << gap;
    }

    if (prepend) {
        prependVertex(nextPoint);
        setBulgeAt(0, bulge);
    }
    else {
        appendVertex(nextPoint);
        setBulgeAt(bulges.size()-2, bulge);
    }
}
void UserTaskDeadlineEmailGenerator::run()
{
    qDebug() << "EmailGenerator: Generating UserClaimedTaskDeadlinePassed email";

    UserClaimedTaskDeadlinePassed email_message;
    email_message.ParseFromString(this->protoBody.toStdString());

    ConfigParser settings;
    QString error = "";
    QSharedPointer<Email> email = QSharedPointer<Email>(new Email);
    QSharedPointer<User> user = QSharedPointer<User>();
    QSharedPointer<Task> task = QSharedPointer<Task>();
    QSharedPointer<MySQLHandler> db = MySQLHandler::getInstance();


    user = UserDao::getUser(db, email_message.translator_id());
    task = TaskDao::getTask(db, email_message.task_id());

    if(!user || !task) {
        error = "Failed to generate UserClaimedTaskDeadlinePassed email: Unable to find relevant ";
        error += "data in the Database. Searched for User ID ";
        error += QString::number(email_message.translator_id()) + " and Task ID ";
        error += QString::number(email_message.task_id()) + ".";
    }

    if(error.compare("") == 0) {
        ctemplate::TemplateDictionary dict("user_claimed_task_deadline_exceeded");
        if(user->display_name() != "") {
            dict.ShowSection("USER_HAS_NAME");
            dict.SetValue("USERNAME", user->display_name());
        } else {
            dict.ShowSection("NO_USER_NAME");
        }
        dict.SetValue("TASK_TITLE", task->title());
        dict.SetValue("SITE_NAME", settings.get("site.name").toStdString());

        QString task_type = "Translation";
        switch(task->tasktype())
        {
            case 1:
                task_type = "Segmentation";
                break;
            case 2:
                task_type = "Translation";
                break;
            case 3:
                task_type = "Proofreading";
                break;
            case 4:
                task_type = "Desegmentation";
                break;
        }

        dict.SetValue("TASK_TYPE", task_type.toStdString());

        Locale taskSourceLocale =  task->sourcelocale();
        Locale taskTargetLocale = task->targetlocale();
        dict.SetValue("SOURCE_LANGUAGE",taskSourceLocale.languagename());
        dict.SetValue("TARGET_LANGUAGE",taskTargetLocale.languagename());

        bool footer_enabled=(QString::compare("y", settings.get("email-footer.enabled")) == 0);
        if (footer_enabled)
        {
            QString donate_link = settings.get("email-footer.donate_link");
            ctemplate::TemplateDictionary* footer_dict = dict.AddIncludeDictionary("FOOTER");
            QString footer_location = QString(TEMPLATE_DIRECTORY) + "emails/footer.tpl";
            footer_dict -> SetValue("DONATE_LINK",donate_link.toStdString());
            footer_dict -> SetFilename(footer_location.toStdString());
        }

        std::string email_body;
        QString template_location = QString(TEMPLATE_DIRECTORY) + "emails/user-claimed-task-deadline-passed.tpl";
        ctemplate::ExpandTemplate(template_location.toStdString(), ctemplate::DO_NOT_STRIP, &dict, &email_body);

        email->setSender(settings.get("site.system_email_address"));;
        email->addRecipient(QString::fromStdString(user->email()));
        email->setSubject(settings.get("site.name") + ": Task Deadline Passed");
        email->setBody(QString::fromUtf8(email_body.c_str()));
    } else {
        email = this->generateErrorEmail(error);
    }

    this->emailQueue->insert(email, currentMessage);
}
Ejemplo n.º 4
0
void tst_QSharedPointer::customDeleter()
{
    {
        QSharedPointer<Data> ptr(new Data, &Data::doDelete);
        QSharedPointer<Data> ptr2(new Data, &Data::alsoDelete);
        QSharedPointer<Data> ptr3(new Data, &Data::virtualDelete);
    }
    {
        QSharedPointer<DerivedData> ptr(new DerivedData, &Data::doDelete);
        QSharedPointer<DerivedData> ptr2(new DerivedData, &Data::alsoDelete);
        QSharedPointer<DerivedData> ptr3(new DerivedData, &Data::virtualDelete);
    }

    customDeleterFnCallCount = 0;
    {
        QSharedPointer<Data> ptr = QSharedPointer<Data>(new Data, customDeleterFn);
        ptr.data();
        QCOMPARE(customDeleterFnCallCount, 0);
    }
    QCOMPARE(customDeleterFnCallCount, 1);

    customDeleterFnCallCount = 0;
    {
        QSharedPointer<Data> ptr = QSharedPointer<Data>(new Data, customDeleterFn);
        QCOMPARE(customDeleterFnCallCount, 0);
        ptr.clear();
        QCOMPARE(customDeleterFnCallCount, 1);
    }
    QCOMPARE(customDeleterFnCallCount, 1);

    customDeleterFnCallCount = 0;
    {
        QSharedPointer<Data> ptr = QSharedPointer<Data>(new Data, customDeleterFn);
        QCOMPARE(customDeleterFnCallCount, 0);
        ptr = QSharedPointer<Data>(new Data);
        QCOMPARE(customDeleterFnCallCount, 1);
    }
    QCOMPARE(customDeleterFnCallCount, 1);

    customDeleterFnCallCount = 0;
    {
        QSharedPointer<Data> ptr = QSharedPointer<Data>(new DerivedData, customDeleterFn);
        ptr.data();
        QCOMPARE(customDeleterFnCallCount, 0);
    }
    QCOMPARE(customDeleterFnCallCount, 1);

    customDeleterFnCallCount = 0;
    {
        QSharedPointer<DerivedData> ptr = QSharedPointer<DerivedData>(new DerivedData, customDeleterFn);
        ptr.data();
        QCOMPARE(customDeleterFnCallCount, 0);
    }
    QCOMPARE(customDeleterFnCallCount, 1);

    customDeleterFnCallCount = 0;
    {
        QSharedPointer<Data> other;
        {
            QSharedPointer<Data> ptr = QSharedPointer<Data>(new Data, customDeleterFn);
            other = ptr;
            QCOMPARE(customDeleterFnCallCount, 0);
        }
        QCOMPARE(customDeleterFnCallCount, 0);
    }
    QCOMPARE(customDeleterFnCallCount, 1);

    customDeleterFnCallCount = 0;
    {
        QSharedPointer<Data> other;
        {
            QSharedPointer<DerivedData> ptr = QSharedPointer<DerivedData>(new DerivedData, customDeleterFn);
            other = ptr;
            QCOMPARE(customDeleterFnCallCount, 0);
        }
        QCOMPARE(customDeleterFnCallCount, 0);
    }
    QCOMPARE(customDeleterFnCallCount, 1);

    CustomDeleter<Data> dataDeleter;
    dataDeleter.callCount = 0;
    {
        QSharedPointer<Data> ptr = QSharedPointer<Data>(new Data, dataDeleter);
        ptr.data();
        QCOMPARE(dataDeleter.callCount, 0);
    }
    QCOMPARE(dataDeleter.callCount, 1);

    dataDeleter.callCount = 0;
    {
        QSharedPointer<Data> ptr = QSharedPointer<Data>(new Data, dataDeleter);
        QSharedPointer<Data> other = ptr;
        other.clear();
        QCOMPARE(dataDeleter.callCount, 0);
    }
    QCOMPARE(dataDeleter.callCount, 1);

    dataDeleter.callCount = 0;
    {
        QSharedPointer<Data> other;
        {
            QSharedPointer<Data> ptr = QSharedPointer<Data>(new Data, dataDeleter);
            other = ptr;
            QCOMPARE(dataDeleter.callCount, 0);
        }
        QCOMPARE(dataDeleter.callCount, 0);
    }
    QCOMPARE(dataDeleter.callCount, 1);

    dataDeleter.callCount = 0;
    {
        QSharedPointer<DerivedData> ptr = QSharedPointer<DerivedData>(new DerivedData, dataDeleter);
        ptr.data();
        QCOMPARE(dataDeleter.callCount, 0);
    }
    QCOMPARE(dataDeleter.callCount, 1);

    CustomDeleter<DerivedData> derivedDataDeleter;
    derivedDataDeleter.callCount = 0;
    dataDeleter.callCount = 0;
    {
        QSharedPointer<DerivedData> ptr = QSharedPointer<DerivedData>(new DerivedData, derivedDataDeleter);
        ptr.data();
        QCOMPARE(dataDeleter.callCount, 0);
        QCOMPARE(derivedDataDeleter.callCount, 0);
    }
    QCOMPARE(dataDeleter.callCount, 0);
    QCOMPARE(derivedDataDeleter.callCount, 1);

    derivedDataDeleter.callCount = 0;
    dataDeleter.callCount = 0;
    {
        QSharedPointer<Data> other;
        {
            QSharedPointer<DerivedData> ptr = QSharedPointer<DerivedData>(new DerivedData, dataDeleter);
            other = ptr;
            QCOMPARE(dataDeleter.callCount, 0);
            QCOMPARE(derivedDataDeleter.callCount, 0);
        }
        QCOMPARE(dataDeleter.callCount, 0);
        QCOMPARE(derivedDataDeleter.callCount, 0);
    }
    QCOMPARE(dataDeleter.callCount, 1);
    QCOMPARE(derivedDataDeleter.callCount, 0);

    derivedDataDeleter.callCount = 0;
    dataDeleter.callCount = 0;
    {
        QSharedPointer<Data> other;
        {
            QSharedPointer<DerivedData> ptr = QSharedPointer<DerivedData>(new DerivedData, derivedDataDeleter);
            other = ptr;
            QCOMPARE(dataDeleter.callCount, 0);
            QCOMPARE(derivedDataDeleter.callCount, 0);
        }
        QCOMPARE(dataDeleter.callCount, 0);
        QCOMPARE(derivedDataDeleter.callCount, 0);
    }
    QCOMPARE(dataDeleter.callCount, 0);
    QCOMPARE(derivedDataDeleter.callCount, 1);
}
Ejemplo n.º 5
0
//----------------------------------------------------------------------------
void ctkPluginPrivate::update0(const QUrl& updateLocation, bool wasActive)
{
  const bool wasResolved = state == ctkPlugin::RESOLVED;
  const int oldStartLevel = getStartLevel();
  QSharedPointer<ctkPluginArchive> newArchive;

  operation.fetchAndStoreOrdered(UPDATING);
  try
  {
    // New plugin as stream supplied?
    QUrl updateUrl(updateLocation);
    if (updateUrl.isEmpty())
    {
      // Try Plugin-UpdateLocation
      QString update = archive != 0 ? archive->getAttribute(ctkPluginConstants::PLUGIN_UPDATELOCATION) : QString();
      if (update.isEmpty())
      {
        // Take original location
        updateUrl = location;
      }
    }

    if(updateUrl.scheme() != "file")
    {
      QString msg = "Unsupported update URL:";
      msg += updateUrl.toString();
      throw ctkPluginException(msg);
    }

    newArchive = fwCtx->storage->updatePluginArchive(archive, updateUrl, updateUrl.toLocalFile());
    //checkCertificates(newArchive);
    checkManifestHeaders();
    newArchive->setStartLevel(oldStartLevel);
    fwCtx->storage->replacePluginArchive(archive, newArchive);
  }
  catch (const std::exception& e)
  {
    if (!newArchive.isNull())
    {
      newArchive->purge();
    }
    operation.fetchAndStoreOrdered(IDLE);
    if (wasActive)
    {
      try
      {
        this->q_func().data()->start();
      }
      catch (const ctkPluginException& pe)
      {
        fwCtx->listeners.frameworkError(this->q_func(), pe);
      }
    }
    try
    {
      const ctkPluginException& pe = dynamic_cast<const ctkPluginException&>(e);
      throw pe;
    }
    catch (std::bad_cast)
    {
      throw ctkPluginException(QString("Failed to get update plugin: ") + e.what(),
                               ctkPluginException::UNSPECIFIED);
    }
  }

  bool purgeOld = false;
  // TODO: check if dependent plug-ins are started. If not, set purgeOld to true.

  // Activate new plug-in
  QSharedPointer<ctkPluginArchive> oldArchive = archive;
  archive = newArchive;
  cachedRawHeaders.clear();
  state = ctkPlugin::INSTALLED;

  // Purge old archive
  if (purgeOld)
  {
    //secure.purge(this, oldProtectionDomain);
    if (oldArchive != 0)
    {
      oldArchive->purge();
    }
  }

  // Broadcast events
  if (wasResolved)
  {
    // TODO: use plugin threading
    //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UNRESOLVED, this));
    fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UNRESOLVED, this->q_func()));
  }
  //bundleThread().bundleChanged(new BundleEvent(BundleEvent.UPDATED, this));
  fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::UPDATED, this->q_func()));
  operation.fetchAndStoreOrdered(IDLE);

   // Restart plugin previously stopped in the operation
   if (wasActive)
   {
     try
     {
       this->q_func().data()->start();
     }
     catch (const ctkPluginException& pe)
     {
       fwCtx->listeners.frameworkError(this->q_func(), pe);
     }
   }
 }
Ejemplo n.º 6
0
void tst_QSharedPointer::memoryManagement()
{
    int generation = Data::generationCounter + 1;
    int destructorCounter = Data::destructorCounter;

    QSharedPointer<Data> ptr = QSharedPointer<Data>(new Data);
    QCOMPARE(ptr->generation, generation);
    QCOMPARE(Data::destructorCounter, destructorCounter);
    QCOMPARE(Data::generationCounter, generation);

    ptr = ptr;
    QCOMPARE(ptr->generation, generation);
    QCOMPARE(Data::destructorCounter, destructorCounter);
    QCOMPARE(Data::generationCounter, generation);

    {
        QSharedPointer<Data> copy = ptr;
        QCOMPARE(ptr->generation, generation);
        QCOMPARE(copy->generation, generation);

        // copy goes out of scope, ptr continues
    }
    QCOMPARE(ptr->generation, generation);
    QCOMPARE(Data::destructorCounter, destructorCounter);
    QCOMPARE(Data::generationCounter, generation);

    {
        QWeakPointer<Data> weak = ptr;
        weak = ptr;
        QCOMPARE(ptr->generation, generation);
        QCOMPARE(Data::destructorCounter, destructorCounter);
        QCOMPARE(Data::generationCounter, generation);

        weak = weak;
        QCOMPARE(ptr->generation, generation);
        QCOMPARE(Data::destructorCounter, destructorCounter);
        QCOMPARE(Data::generationCounter, generation);

        QSharedPointer<Data> strong = weak;
        QCOMPARE(ptr->generation, generation);
        QCOMPARE(strong->generation, generation);
        QCOMPARE(Data::destructorCounter, destructorCounter);
        QCOMPARE(Data::generationCounter, generation);

        // both weak and strong go out of scope
    }
    QCOMPARE(ptr->generation, generation);
    QCOMPARE(Data::destructorCounter, destructorCounter);
    QCOMPARE(Data::generationCounter, generation);

    QWeakPointer<Data> weak = ptr;
    ptr = QSharedPointer<Data>();

    // destructor must have been called
    QCOMPARE(Data::destructorCounter, destructorCounter + 1);
    QVERIFY(ptr.isNull());
    QVERIFY(weak.isNull());

    // if we create a strong pointer from the weak, it must still be null
    ptr = weak;
    QVERIFY(ptr.isNull());
    QVERIFY(ptr == 0);
    QCOMPARE(ptr.data(), (Data*)0);
}
Ejemplo n.º 7
0
void tst_QSharedPointer::dynamicCastDifferentPointers()
{
    // DiffPtrDerivedData derives from both Data and Stuffing
    DiffPtrDerivedData *aData = new DiffPtrDerivedData;
    QSharedPointer<Data> baseptr = QSharedPointer<Data>(aData);

    {
        QSharedPointer<DiffPtrDerivedData> derivedptr = qSharedPointerDynamicCast<DiffPtrDerivedData>(baseptr);
        QVERIFY(baseptr == derivedptr);
        QCOMPARE(derivedptr.data(), aData);
        QCOMPARE(static_cast<Data *>(derivedptr.data()), baseptr.data());
    }
    QCOMPARE(int(baseptr.d->weakref), 1);
    QCOMPARE(int(baseptr.d->strongref), 1);

    {
        QWeakPointer<Data> weakptr = baseptr;
        QSharedPointer<DiffPtrDerivedData> derivedptr = qSharedPointerDynamicCast<DiffPtrDerivedData>(weakptr);
        QVERIFY(baseptr == derivedptr);
        QCOMPARE(derivedptr.data(), aData);
        QCOMPARE(static_cast<Data *>(derivedptr.data()), baseptr.data());
    }
    QCOMPARE(int(baseptr.d->weakref), 1);
    QCOMPARE(int(baseptr.d->strongref), 1);

    {
        QSharedPointer<DiffPtrDerivedData> derivedptr = baseptr.dynamicCast<DiffPtrDerivedData>();
        QVERIFY(baseptr == derivedptr);
        QCOMPARE(derivedptr.data(), aData);
        QCOMPARE(static_cast<Data *>(derivedptr.data()), baseptr.data());
    }
    QCOMPARE(int(baseptr.d->weakref), 1);
    QCOMPARE(int(baseptr.d->strongref), 1);

    {
        Stuffing *nakedptr = dynamic_cast<Stuffing *>(baseptr.data());
        QVERIFY(nakedptr);

        QSharedPointer<Stuffing> otherbaseptr = qSharedPointerDynamicCast<Stuffing>(baseptr);
        QVERIFY(!otherbaseptr.isNull());
        QVERIFY(otherbaseptr == nakedptr);
        QCOMPARE(otherbaseptr.data(), nakedptr);
        QCOMPARE(static_cast<DiffPtrDerivedData*>(otherbaseptr.data()), aData);
    }
}
Ejemplo n.º 8
0
QSharedPointer<DataMark> QueryExecutor::insertNewTag(const QSharedPointer<DataMark>& tag)
{
  bool result;
  QSqlQuery newTagQuery(m_database);
  qlonglong newId = nextTagKey();
  newTagQuery.prepare("insert into tag (latitude, longitude, label, description, url, user_id, time, id) "
    "         values(:latitude,:longitude,:label,:description,:url,:user_id,:time,:id);");
  newTagQuery.bindValue(":latitude", tag->getLatitude());
  newTagQuery.bindValue(":longitude", tag->getLongitude());
  newTagQuery.bindValue(":label", tag->getLabel().isEmpty()? "New Mark" : tag->getLabel());
  newTagQuery.bindValue(":description", tag->getDescription());
  newTagQuery.bindValue(":url", tag->getUrl());
  newTagQuery.bindValue(":user_id", tag->getUser()->getId());
  newTagQuery.bindValue(":time", tag->getTime().toUTC());
  newTagQuery.bindValue(":id", newId);

  QSqlQuery putTagToChannelQuery(m_database);
  putTagToChannelQuery.prepare("insert into tags (tag_id,channel_id) values(:tag_id,:channel_id);");
  putTagToChannelQuery.bindValue(":tag_id",newId);
  putTagToChannelQuery.bindValue(":channel_id",tag->getChannel()->getId());

  m_database.transaction();

  result = newTagQuery.exec();
  if(!result)
  {
    m_database.rollback();
    return QSharedPointer<DataMark>(NULL);
  }
  result = putTagToChannelQuery.exec();
  if(!result)
  {
    m_database.rollback();
    return QSharedPointer<DataMark>(NULL);
  }

  m_database.commit();

  QSharedPointer<DataMark> t(
    new DbDataMark(newId,tag->getLatitude(),tag->getLongitude(),tag->getLabel(),
    tag->getDescription(),tag->getUrl(),tag->getTime(),tag->getUser()->getId()));
  t->setUser(tag->getUser());
  t->setChannel(tag->getChannel());
  return t;
}
Ejemplo n.º 9
0
QT_BEGIN_NAMESPACE

/*!
    \class QLowEnergyService
    \inmodule QtBluetooth
    \brief The QLowEnergyService class represents an individual service
    on a Bluetooth Low Energy Device.

    \since 5.4

    QLowEnergyService provides access to the details of Bluetooth Low Energy
    services. The class facilitates the discovery and publification of
    service details, permits reading and writing of the contained data
    and notifies about data changes.

    \section1 Service Structure

    A Bluetooth Low Energy peripheral device can contain multiple services.
    In turn each service may include further services. This class represents a
    single service of the peripheral device and is created via
    \l QLowEnergyController::createServiceObject(). The \l type() indicates
    whether this service is a primary (top-level) service or whether the
    service is part of another service. Each service may contain one or more
    characteristics and each characteristic may contain descriptors. The
    resulting structure may look like the following diagram:

    \image peripheral-structure.png Structure of a generic peripheral

    A characteristic is the principle information carrier. It has a
    \l {QLowEnergyCharacteristic::value()}{value()} and
    \l {QLowEnergyCharacteristic::value()}{properties()}
    describing the access permissions for the value. The general purpose
    of the contained descriptor is to further define the nature of the
    characteristic. For example, it might specify how the value is meant to be
    interpreted or whether it can notify the value consumer about value
    changes.

    \section1 Service Interaction

    Once a service object was created for the first time, its details are yet to
    be discovered. This is indicated by its current \l state() being \l DiscoveryRequired.
    It is only possible to retrieve the \l serviceUuid() and \l serviceName().

    The discovery of its included services, characteristics and descriptors
    is triggered when calling \l discoverDetails(). During the discovery the
    \l state() transitions from \l DiscoveryRequired via \l DiscoveringServices
    to its final \l ServiceDiscovered state. This transition is advertised via
    the \l stateChanged() signal. Once the details are known, all of the contained
    characteristics, descriptors and included services are known and can be read
    or written.

    The values of characteristics and descriptors can be retrieved via
    \l QLowEnergyCharacteristic and \l QLowEnergyDescriptor, respectively.
    However writing those attributes requires the service object. The
    \l writeCharacteristic() function attempts to write a new value to the given
    characteristic. If the write attempt is successful, the \l characteristicWritten()
    signal is emitted. A failure to write triggers the \l CharacteristicWriteError.
    Writing a descriptor follows the same pattern.

    \note Currently, it is not possible to send signed write or reliable write requests.

    \target notifications

    In some cases the peripheral generates value updates which
    the central is interested in receiving. In order for a characteristic to support
    such notifications it must have the \l QLowEnergyCharacteristic::Notify or
    \l QLowEnergyCharacteristic::Indicate property and a descriptor of type
    \l QBluetoothUuid::ClientCharacteristicConfiguration. Provided those conditions
    are fulfilled notifications can be enabled as shown in the following code segment:

    \snippet doc_src_qtbluetooth.cpp enable_btle_notifications

    The example shows a battery level characteristic which updates the central
    on every value change. The notifications are provided via
    the \l characteristicChanged() signal. More details about this mechanism
    are provided by the
    \l {https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml}{Bluetooth Specification}.

    \section1 Service Data Sharing

    Each QLowEnergyService instance shares its internal states and information
    with other QLowEnergyService instance of the same service. If one instance
    initiates the discovery of the service details, all remaining instances
    automatically follow. Therefore the following snippet always works:

    \snippet doc_src_qtbluetooth.cpp data_share_qlowenergyservice

    Other operations such as calls to \l writeCharacteristic(),
    writeDescriptor() or the invalidation of the service due to the
    related \l QLowEnergyController disconnecting from the device are shared
    the same way.

    \note This class is provided by Qt 5.4 as part of a Bluetooth Low Energy Tech Preview.
    Some API elements may change until the final release of the feature.

    \sa QLowEnergyController, QLowEnergyCharacteristic, QLowEnergyDescriptor
 */

/*!
    \enum QLowEnergyService::ServiceType

    This enum describes the type of the service.

    \value PrimaryService       The service is a top-level/primary service.
                                If this type flag is not set, the service is considered
                                to be a secondary service. Each service may be included
                                by another service which is indicated by IncludedService.
    \value IncludedService      The service is included by another service.
                                On some platforms, this flag cannot be determined until
                                the service that includes the current service was
                                discovered.
*/

/*!
    \enum QLowEnergyService::ServiceError

    This enum describes all possible error conditions during the service's
    existence. The \l error() function returns the last occurred error.

    \value NoError                  No error has occurred.
    \value OperationError           An operation was attempted while the service was not ready.
                                    An example might be the attempt to write to
                                    the service while it was not yet in the
                                    \l ServiceDiscovered \l state() or the service is invalid
                                    due to a loss of connection to the peripheral device.
    \value CharacteristicWriteError An attempt to write a new value to a characteristic
                                    failed. For example, it might be triggered when attempting
                                    to write to a read-only characteristic.
    \value DescriptorWriteError     An attempt to write a new value to a descriptor
                                    failed. For example, it might be triggered when attempting
                                    to write to a read-only descriptor.
 */

/*!
    \enum QLowEnergyService::ServiceState

    This enum describes the \l state() of the service object.

    \value InvalidService       A service can become invalid when it looses
                                the connection to the underlying device. Even though
                                the connection may be lost it retains its last information.
                                An invalid service cannot become valid anymore even if
                                the connection to the device is re-established.
    \value DiscoveryRequired    The service details are yet to be discovered by calling \l discoverDetails().
                                The only reliable pieces of information are its
                                \l serviceUuid() and \l serviceName().
    \value DiscoveringServices  The service details are being discovered.
    \value ServiceDiscovered    The service details have been discovered.
 */

/*!
  \enum QLowEnergyService::WriteMode

  This enum describes the mode to be used when writing a characteristic value.
  The characteristic advertises its supported write modes via its
  \l {QLowEnergyCharacteristic::properties()}{properties}.

  \value WriteWithResponse      If a characteristic is written using this mode, the peripheral
                                shall send a write confirmation. If the operation is
                                successful, the confirmation is emitted via the
                                \l characteristicWritten() signal. Otherwise the
                                \l CharacteristicWriteError is emitted.
                                A characteristic must have set the
                                \l QLowEnergyCharacteristic::Write property to support this
                                write mode.

  \value WriteWithoutResponse   If a characteristic is written using this mode, the remote peripheral
                                shall not send a write confirmation. The operation's success
                                cannot be determined and the payload must not be longer than 20 bytes.
                                A characteristic must have set the
                                \l QLowEnergyCharacteristic::WriteNoResponse property to support this
                                write mode. Its adavantage is a quicker
                                write operation as it may happen in between other
                                device interactions.
 */

/*!
    \fn void QLowEnergyService::stateChanged(QLowEnergyService::ServiceState newState)

    This signal is emitted when the service's state changes. The \a newState can also be
    retrieved via \l state().

    \sa state()
 */

/*!
    \fn void QLowEnergyService::error(QLowEnergyService::ServiceError newError)

    This signal is emitted when an error occurrs. The \a newError parameter
    describes the error that occurred.
 */

/*!
    \fn void QLowEnergyService::characteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue);

    This signal is emitted when the value of \a characteristic
    is successfully changed to \a newValue. The change must have been triggered
    by calling \l writeCharacteristic(). If the write operation is not successful,
    the \l error() signal is emitted using the \l CharacteristicWriteError flag.

    \note If \l writeCharacteristic() is called using the \l WriteWithoutResponse mode,
    this signal and the \l error() are never emitted.

    \sa writeCharacteristic()
 */

/*!
    \fn void QLowEnergyService::characteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue);

    This signal is emitted when the value of \a characteristic is changed
    by an event on the peripheral. The \a newValue parameter contains the
    updated value of the \a characteristic.

    The signal emission implies that change notifications must
    have been activated via the characteristic's
    \l {QBluetoothUuid::ClientCharacteristicConfiguration}{ClientCharacteristicConfiguration}
    descriptor prior to the change event on the peripheral. More details on how this might be
    done can be found further \l{notifications}{above}.
 */

/*!
    \fn void QLowEnergyService::descriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue)

    This signal is emitted when the value of \a descriptor
    is successfully changed to \a newValue. The change must have been caused
    by calling \l writeDescriptor().

    \sa writeDescriptor()
 */

/*!
  \internal

  QLowEnergyControllerPrivate creates instances of this class.
  The user gets access to class instances via
  \l QLowEnergyController::services().
 */
QLowEnergyService::QLowEnergyService(QSharedPointer<QLowEnergyServicePrivate> p,
                                     QObject *parent)
    : QObject(parent),
      d_ptr(p)
{
    qRegisterMetaType<QLowEnergyService::ServiceState>("QLowEnergyService::ServiceState");
    qRegisterMetaType<QLowEnergyService::ServiceError>("QLowEnergyService::ServiceError");

    connect(p.data(), SIGNAL(error(QLowEnergyService::ServiceError)),
            this, SIGNAL(error(QLowEnergyService::ServiceError)));
    connect(p.data(), SIGNAL(stateChanged(QLowEnergyService::ServiceState)),
            this, SIGNAL(stateChanged(QLowEnergyService::ServiceState)));
    connect(p.data(), SIGNAL(characteristicChanged(QLowEnergyCharacteristic,QByteArray)),
            this, SIGNAL(characteristicChanged(QLowEnergyCharacteristic,QByteArray)));
    connect(p.data(), SIGNAL(characteristicWritten(QLowEnergyCharacteristic,QByteArray)),
            this, SIGNAL(characteristicWritten(QLowEnergyCharacteristic,QByteArray)));
    connect(p.data(), SIGNAL(descriptorWritten(QLowEnergyDescriptor,QByteArray)),
            this, SIGNAL(descriptorWritten(QLowEnergyDescriptor,QByteArray)));
}
Ejemplo n.º 10
0
bool RMemoryStorage::isSelected(REntity::Id entityId) {
    QSharedPointer<REntity> e = queryEntityDirect(entityId);
    return (!e.isNull() && e->isSelected());
}
Ejemplo n.º 11
0
void RMemoryStorage::toggleUndoStatus(RObject::Id objectId) {
    QSharedPointer<RObject> obj = queryObjectDirect(objectId);
    if (!obj.isNull()) {
        obj->setUndone(!obj->isUndone());
    }
}
Ejemplo n.º 12
0
bool RMemoryStorage::saveObject(QSharedPointer<RObject> object, bool checkBlockRecursion, bool keepHandles) {
    if (object.isNull()) {
        return false;
    }

    // never allow two layers with identical names, update layer instead:
    QSharedPointer<RLayer> layer = object.dynamicCast<RLayer>();
    if (!layer.isNull()) {
        RLayer::Id id = getLayerId(layer->getName());
        if (id != RLayer::INVALID_ID) {
            setObjectId(*layer, id);
        }
    }

    // never allow two blocks with identical names, update block instead:
    QSharedPointer<RBlock> block = object.dynamicCast<RBlock> ();
    if (!block.isNull()) {
        RBlock::Id id = getBlockId(block->getName());
        if (id != RBlock::INVALID_ID) {
            setObjectId(*block, id);
        }
    }

    // avoid block recursions:
    if (checkBlockRecursion) {
        /*
        QSharedPointer<RBlockReferenceEntity> blockRef = object.dynamicCast<RBlockReferenceEntity> ();
        if (!blockRef.isNull()) {
            RBlock::Id id = blockRef->getBlockId();
            RBlock::Id refId = blockRef->getReferencedBlockId();
            // check if block with 'id' may contain a block reference which refers to
            // block with 'refid':
            // 201308: too slow for large, complex drawings:
            if (checkRecursion(id, refId)) {
                qCritical("RMemoryStorage::saveObject: recursion found");
                return false;
            }
        }
        */
    }

    QSharedPointer<REntity> entity = object.dynamicCast<REntity> ();

    // assign new object ID to new objects:
    if (object->getId() == RObject::INVALID_ID) {
        setObjectId(*object, getNewObjectId());

        // only set new handle if handle is not set already:
        if (!keepHandles || object->getHandle()==RObject::INVALID_HANDLE) {
            setObjectHandle(*object, getNewObjectHandle());
        }

        // assign draw order to new entities:
        if (!entity.isNull()) {
            entity->setDrawOrder(getMaxDrawOrder());
            setMaxDrawOrder(getMaxDrawOrder()+1);
        }
    }

    // TODO: save original object for rollback:
    //if (inTransaction) {
        //transactionObjectMap[object->getId()] = object;
    //}

    objectMap[object->getId()] = object;

    //QSharedPointer<REntity> entity = object.dynamicCast<REntity> ();
    if (!entity.isNull()) {
        entityMap[entity->getId()] = entity;
        blockEntityMap.insert(entity->getBlockId(), entity);
        //qDebug() << "added " << entity->getId() << " to block " << entity->getBlockId();
        setMaxDrawOrder(qMax(entity->getDrawOrder()+1, getMaxDrawOrder()));
    }

    if (!layer.isNull()) {
        layerMap[object->getId()] = layer;
    }

    if (!block.isNull()) {
        blockMap[object->getId()] = block;
    }

    return true;
}
Ejemplo n.º 13
0
 virtual void SetSharedPointer(const QSharedPointer<Filter> &filter)
 {
   _filter = filter.toWeakRef();
 }
Ejemplo n.º 14
0
ShareWidget::ShareWidget(QSharedPointer<Share> share,
                         bool isFile,
                         QWidget *parent) :
  QWidget(parent),
  _ui(new Ui::ShareWidget),
  _share(share),
  _isFile(isFile)
{
    _ui->setupUi(this);

    _ui->sharedWith->setText(share->getShareWith()->format());
 
    // Create detailed permissions menu
    QMenu *menu = new QMenu(this);
    _permissionCreate = new QAction(tr("create"), this);
    _permissionCreate->setCheckable(true);
    _permissionUpdate = new QAction(tr("change"), this);
    _permissionUpdate->setCheckable(true);
    _permissionDelete = new QAction(tr("delete"), this);
    _permissionDelete->setCheckable(true);

    menu->addAction(_permissionUpdate);
    /*
     * Files can't have create or delete permissions
     */
    if (!_isFile) {
        menu->addAction(_permissionCreate);
        menu->addAction(_permissionDelete);
    }
    _ui->permissionToolButton->setMenu(menu);
    _ui->permissionToolButton->setPopupMode(QToolButton::InstantPopup);

    QIcon icon(QLatin1String(":/client/resources/more.png"));
    _ui->permissionToolButton->setIcon(icon);

    // Set the permissions checkboxes
    displayPermissions();

    connect(_permissionUpdate, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged()));
    connect(_permissionCreate, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged()));
    connect(_permissionDelete, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged()));
    connect(_ui->permissionShare,  SIGNAL(clicked(bool)), SLOT(slotPermissionsChanged()));
    connect(_ui->permissionsEdit,  SIGNAL(clicked(bool)), SLOT(slotEditPermissionsChanged()));

    /*
     * We don't show permssion share for federated shares
     * https://github.com/owncloud/core/issues/22122#issuecomment-185637344
     */
    if (share->getShareType() == Share::TypeRemote) {
        _ui->permissionShare->setVisible(false);
        _ui->permissionToolButton->setVisible(false);
    }

    connect(share.data(), SIGNAL(permissionsSet()), SLOT(slotPermissionsSet()));
    connect(share.data(), SIGNAL(shareDeleted()), SLOT(slotShareDeleted()));

    _ui->deleteShareButton->setIcon(QIcon::fromTheme(QLatin1String("user-trash"),
                                                     QIcon(QLatin1String(":/client/resources/delete.png"))));

    if (!share->account()->capabilities().shareResharing()) {
        _ui->permissionShare->hide();
    }
}
Ejemplo n.º 15
0
QSharedPointer<IChatMsg> ConversationService::sendMessage(quint32 conversationId, quint32 userId, const QSharedPointer<QString> & message) const {
    qDebug() << "[ConversationService][sendMessage] c: " << conversationId << " u: " << userId << " message: " << *message;

    //Filter invalid user
    if(userId <= 0){ return manager->getProtocol().createResponse(RequestType::SendMessage, ErrorType::Custom, QStringLiteral("You have to login, before sending messages")); }

    //Create new message
    StreamableVector messages(new QVector<IStreamable*>());
    messages->push_back(new Message());
    Message * msg = static_cast<Message*>(messages->last());
    msg->message = message;
    msg->time = QDateTime::currentDateTime().toTime_t();
    msg->conversationId = conversationId;
    msg->userId = userId;

    //Filter invalid messages
    int messageLength = msg->message->length();
    if(messageLength < 1 || messageLength > 500){ return manager->getProtocol().createResponse(RequestType::SendMessage, ErrorType::Custom, QStringLiteral("Invalid message size")); }

    //Insert new message
    QSharedPointer<QSqlQuery> query = manager->getDbService().prepare(
        "INSERT INTO message (`message`, `time`, `conversation_id`, `user_id`) "
        "VALUES (:message, :time, :conversationid, :userid);");
    bool ok = false;
    if(!query.isNull()){
        query->bindValue(":message", *msg->message);
        query->bindValue(":time", msg->time);
        query->bindValue(":conversationid", msg->conversationId);
        query->bindValue(":userid", msg->userId);
        ok = manager->getDbService().exec(query);
    }
    if(!ok){ return manager->getProtocol().createResponse(RequestType::SendMessage, ErrorType::Internal, QStringLiteral("")); }
    msg->id = query->lastInsertId().toInt();

    //Get username for this message
    QSharedPointer<QSqlQuery> userQuery = manager->getDbService().prepare("SELECT username FROM user WHERE user.id = :userid");
    ok = false;
    if(!userQuery.isNull()){
        userQuery->bindValue(":userid", userId);
        ok = manager->getDbService().exec(userQuery);
    }
    if(!ok || !userQuery->next()){ return manager->getProtocol().createResponse(RequestType::SendMessage, ErrorType::Internal, QStringLiteral("")); }
    msg->username = QSharedPointer<QString>(new QString(userQuery->value(0).toString()));

    //Send notifications to users
    QSharedPointer<IChatMsg> response = manager->getProtocol().createResponseMessages(RequestType::SendMessage, true, messages, conversationId);
    emit manager->getNotificationSender().newNotification(*response, QList<int>());

    return QSharedPointer<IChatMsg>(); //No direct response; Sending user gets notification as well
}
Ejemplo n.º 16
0
void View3D::setModel(QSharedPointer<Data3DTreeModel> pModel)
{
    pModel->getRootEntity()->setParent(m_p3DObjectsEntity);
}
Ejemplo n.º 17
0
void LayoutTest::layoutToXml() const {

	QImage imgQt(mConfig.imagePath());
	cv::Mat img = Image::qImage2Mat(imgQt);

	Timer dt;

	// find super pixels
	rdf::SuperPixel superPixel(img);

	if (!superPixel.compute())
		qWarning() << "could not compute super pixel!";

	QVector<QSharedPointer<Pixel> > sp = superPixel.getSuperPixels();

	// find local orientation per pixel
	rdf::LocalOrientation lo(sp);
	if (!lo.compute())
		qWarning() << "could not compute local orientation";

	// smooth estimation
	rdf::GraphCutOrientation pse(sp);

	if (!pse.compute())
		qWarning() << "could not compute set orientation";

	//// find tab stops
	//rdf::TabStopAnalysis tabStops(sp);
	//if (!tabStops.compute())
	//	qWarning() << "could not compute text block segmentation!";

	// find text lines
	rdf::TextLineSegmentation textLines(sp);
	
	if (!textLines.compute())
		qWarning() << "could not compute text block segmentation!";

	qInfo() << "algorithm computation time" << dt;

	// drawing
	cv::Mat rImg = img.clone();

	// save super pixel image
	//rImg = superPixel.drawSuperPixels(rImg);
	//rImg = tabStops.draw(rImg);
	rImg = textLines.draw(rImg);
	QString dstPath = rdf::Utils::instance().createFilePath(mConfig.outputPath(), "-textlines");
	rdf::Image::save(rImg, dstPath);
	qDebug() << "debug image saved: " << dstPath;


	// write XML -----------------------------------
	QString loadXmlPath = rdf::PageXmlParser::imagePathToXmlPath(mConfig.imagePath());

	rdf::PageXmlParser parser;
	parser.read(loadXmlPath);
	auto pe = parser.page();
	pe->setCreator(QString("CVL"));
	pe->setImageSize(QSize(img.rows, img.cols));
	pe->setImageFileName(QFileInfo(mConfig.imagePath()).fileName());

	// start writing content
	auto ps = PixelSet::fromEdges(PixelSet::connect(sp));

	if (!ps.empty()) {
		QSharedPointer<Region> textRegion = QSharedPointer<Region>(new Region());
		textRegion->setType(Region::type_text_region);
		textRegion->setPolygon(ps[0]->convexHull());
		
		for (auto tl : textLines.textLines()) {
			textRegion->addUniqueChild(tl);
		}

		pe->rootRegion()->addUniqueChild(textRegion);
	}

	parser.write(mConfig.xmlPath(), pe);
	qDebug() << "results written to" << mConfig.xmlPath();

}
Ejemplo n.º 18
0
void QWebEnginePagePrivate::javascriptDialog(QSharedPointer<JavaScriptDialogController> controller)
{
    Q_Q(QWebEnginePage);
    bool accepted = false;
    QString promptResult;
    switch (controller->type()) {
    case AlertDialog:
        q->javaScriptAlert(controller->securityOrigin(), controller->message());
        accepted = true;
        break;
    case ConfirmDialog:
        accepted = q->javaScriptConfirm(controller->securityOrigin(), controller->message());
        break;
    case PromptDialog:
        accepted = q->javaScriptPrompt(controller->securityOrigin(), controller->message(), controller->defaultPrompt(), &promptResult);
        if (accepted)
            controller->textProvided(promptResult);
        break;
    case InternalAuthorizationDialog:
        accepted = (QMessageBox::question(view, controller->title(), controller->message(), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes);
        break;
    default:
        Q_UNREACHABLE();
    }
    if (accepted)
        controller->accept();
    else
        controller->reject();
}
Ejemplo n.º 19
0
void tst_QSharedPointer::differentPointers()
{
    {
        DiffPtrDerivedData *aData = new DiffPtrDerivedData;
        Data *aBase = aData;
        Q_ASSERT(aData == aBase);
        Q_ASSERT(*reinterpret_cast<quintptr *>(&aData) != *reinterpret_cast<quintptr *>(&aBase));

        QSharedPointer<DiffPtrDerivedData> ptr = QSharedPointer<DiffPtrDerivedData>(aData);
        QSharedPointer<Data> baseptr = qSharedPointerCast<Data>(ptr);
        QVERIFY(ptr == baseptr);
        QVERIFY(ptr.data() == baseptr.data());
        QVERIFY(ptr == aBase);
        QVERIFY(ptr == aData);
        QVERIFY(baseptr == aData);
        QVERIFY(baseptr == aBase);
    }

    {
        DiffPtrDerivedData *aData = new DiffPtrDerivedData;
        Data *aBase = aData;
        Q_ASSERT(aData == aBase);
        Q_ASSERT(*reinterpret_cast<quintptr *>(&aData) != *reinterpret_cast<quintptr *>(&aBase));

        QSharedPointer<Data> baseptr = QSharedPointer<Data>(aData);
        QSharedPointer<DiffPtrDerivedData> ptr = qSharedPointerCast<DiffPtrDerivedData>(baseptr);
        QVERIFY(ptr == baseptr);
        QVERIFY(ptr.data() == baseptr.data());
        QVERIFY(ptr == aBase);
        QVERIFY(baseptr == aData);
    }

    {
        DiffPtrDerivedData *aData = new DiffPtrDerivedData;
        Data *aBase = aData;
        Q_ASSERT(aData == aBase);
        Q_ASSERT(*reinterpret_cast<quintptr *>(&aData) != *reinterpret_cast<quintptr *>(&aBase));

        QSharedPointer<DiffPtrDerivedData> ptr = QSharedPointer<DiffPtrDerivedData>(aData);
        QSharedPointer<Data> baseptr = ptr;
        QVERIFY(ptr == baseptr);
        QVERIFY(ptr.data() == baseptr.data());
        QVERIFY(ptr == aBase);
        QVERIFY(ptr == aData);
        QVERIFY(baseptr == aData);
        QVERIFY(baseptr == aBase);
    }
}
Ejemplo n.º 20
0
void cc2DLabel::drawMeOnly3D(CC_DRAW_CONTEXT& context)
{
	assert(!m_points.empty());

	//standard case: list names pushing
	bool pushName = MACRO_DrawNames(context);
	if (pushName)
		glPushName(getUniqueID());

    const float c_sizeFactor = 4.0f;
    bool loop=false;

	unsigned count = m_points.size();
    switch (count)
    {
    case 3:
		{
			glPushAttrib(GL_COLOR_BUFFER_BIT);
			glEnable(GL_BLEND);

			//we draw the triangle
			glColor4ub(255,255,0,128);
			glBegin(GL_TRIANGLES);
			for (unsigned i=0;i<count;++i)
				glVertex3fv(m_points[i].cloud->getPoint(m_points[i].index)->u);
			glEnd();

			glPopAttrib();
			loop=true;
		}
    case 2:
		{
			//segment width
			glPushAttrib(GL_LINE_BIT);
			glLineWidth(c_sizeFactor);

			//we draw the segments
			if (isSelected())
				glColor3ubv(ccColor::red);
			else
				glColor3ubv(ccColor::green);
			glBegin(GL_LINES);
			for (unsigned i=0; i<count; i++)
			{
				if (i+1<count || loop)
				{
					glVertex3fv(m_points[i].cloud->getPoint(m_points[i].index)->u);
					glVertex3fv(m_points[(i+1)%count].cloud->getPoint(m_points[(i+1)%count].index)->u);
				}
			}
			glEnd();
			glPopAttrib();
		}

    case 1:
		{
			//display point marker as spheres
			{
				if (!c_unitPointMarker)
				{
					c_unitPointMarker = QSharedPointer<ccSphere>(new ccSphere(1.0f,0,"PointMarker",12));
					c_unitPointMarker->showColors(true);
					c_unitPointMarker->setVisible(true);
					c_unitPointMarker->setEnabled(true);
				}
			
				//build-up point maker own 'context'
				bool pushName = MACRO_DrawNames(context);
				CC_DRAW_CONTEXT markerContext = context;
				markerContext.flags &= (~CC_DRAW_NAMES); //we must remove the 'push name flag' so that the sphere doesn't push its own!
				markerContext._win = 0;

				if (isSelected() && !pushName)
					c_unitPointMarker->setColor(ccColor::red);
				else
					c_unitPointMarker->setColor(ccColor::magenta);

				for (unsigned i=0; i<count; i++)
				{
					glMatrixMode(GL_MODELVIEW);
					glPushMatrix();
					const CCVector3* P = m_points[i].cloud->getPoint(m_points[i].index);
					glTranslatef(P->x,P->y,P->z);
					glScalef(context.pickedPointsRadius,context.pickedPointsRadius,context.pickedPointsRadius);
					c_unitPointMarker->draw(markerContext);
					glPopMatrix();
				}
			}

			if (m_dispIn3D && !pushName) //no need to display label in point picking mode
			{
				QFont font(context._win->getTextDisplayFont());
				//font.setPointSize(font.pointSize()+2);
				font.setBold(true);

				//draw their name
				glPushAttrib(GL_DEPTH_BUFFER_BIT);
				glDisable(GL_DEPTH_TEST);
				for (unsigned j=0; j<count; j++)
				{
					const CCVector3* P = m_points[j].cloud->getPoint(m_points[j].index);
					QString title = (count == 1 ? getName() : QString("P#%0").arg(m_points[j].index));
					context._win->display3DLabel( title, *P+CCVector3(context.pickedPointsTextShift), ccColor::magenta, font);
				}
				glPopAttrib();
			}
		}
    }

	if (pushName)
		glPopName();
}
Ejemplo n.º 21
0
void tst_QSharedPointer::dynamicCastVirtualBase()
{
    VirtualDerived *aData = new VirtualDerived;
    QSharedPointer<Data> baseptr = QSharedPointer<Data>(aData);

    {
        QSharedPointer<VirtualDerived> derivedptr = qSharedPointerDynamicCast<VirtualDerived>(baseptr);
        QVERIFY(baseptr == derivedptr);
        QCOMPARE(derivedptr.data(), aData);
        QCOMPARE(static_cast<Data *>(derivedptr.data()), baseptr.data());
    }
    QCOMPARE(int(baseptr.d->weakref), 1);
    QCOMPARE(int(baseptr.d->strongref), 1);

    {
        QWeakPointer<Data> weakptr = baseptr;
        QSharedPointer<VirtualDerived> derivedptr = qSharedPointerDynamicCast<VirtualDerived>(weakptr);
        QVERIFY(baseptr == derivedptr);
        QCOMPARE(derivedptr.data(), aData);
        QCOMPARE(static_cast<Data *>(derivedptr.data()), baseptr.data());
    }
    QCOMPARE(int(baseptr.d->weakref), 1);
    QCOMPARE(int(baseptr.d->strongref), 1);

    {
        QSharedPointer<VirtualDerived> derivedptr = baseptr.dynamicCast<VirtualDerived>();
        QVERIFY(baseptr == derivedptr);
        QCOMPARE(derivedptr.data(), aData);
        QCOMPARE(static_cast<Data *>(derivedptr.data()), baseptr.data());
    }
    QCOMPARE(int(baseptr.d->weakref), 1);
    QCOMPARE(int(baseptr.d->strongref), 1);
}
Ejemplo n.º 22
0
void ccPolyline::drawMeOnly(CC_DRAW_CONTEXT& context)
{
	unsigned vertCount = size();
	if (vertCount < 2)
		return;

	bool draw = false;

	if (MACRO_Draw3D(context))
	{
		draw = !m_mode2D;
	}
	else if (m_mode2D)
	{
		bool drawFG = MACRO_Foreground(context);
		draw = ((drawFG && m_foreground) || (!drawFG && !m_foreground));
	}

	if (!draw)
		return;
	
	//get the set of OpenGL functions (version 2.1)
	QOpenGLFunctions_2_1 *glFunc = context.glFunctions<QOpenGLFunctions_2_1>();
	assert( glFunc != nullptr );
	
	if ( glFunc == nullptr )
		return;
	
	//standard case: list names pushing
	bool pushName = MACRO_DrawEntityNames(context);
	if (pushName)
		glFunc->glPushName(getUniqueIDForDisplay());

	if (isColorOverriden())
		ccGL::Color3v(glFunc, m_tempColor.rgb);
	else if (colorsShown())
		ccGL::Color3v(glFunc, m_rgbColor.rgb);

	//display polyline
	if (vertCount > 1)
	{
		if (m_width != 0)
		{
			glFunc->glPushAttrib(GL_LINE_BIT);
			glFunc->glLineWidth(static_cast<GLfloat>(m_width));
		}

		//DGM: we do the 'GL_LINE_LOOP' manually as I have a strange bug
		//on one on my graphic card with this mode!
		//glBegin(m_isClosed ? GL_LINE_LOOP : GL_LINE_STRIP);
		glFunc->glBegin(GL_LINE_STRIP);
		for (unsigned i=0; i<vertCount; ++i)
		{
			ccGL::Vertex3v(glFunc, getPoint(i)->u);
		}
		if (m_isClosed)
		{
			ccGL::Vertex3v(glFunc, getPoint(0)->u);
		}
		glFunc->glEnd();

		//display arrow
		if (m_showArrow && m_arrowIndex < vertCount && (m_arrowIndex > 0 || m_isClosed))
		{
			const CCVector3* P0 = getPoint(m_arrowIndex == 0 ? vertCount-1 : m_arrowIndex-1);
			const CCVector3* P1 = getPoint(m_arrowIndex);
			//direction of the last polyline chunk
			CCVector3 u = *P1 - *P0;
			u.normalize();

			if (m_mode2D)
			{
				u *= -m_arrowLength;
				static const PointCoordinateType s_defaultArrowAngle = static_cast<PointCoordinateType>(15.0 * CC_DEG_TO_RAD);
				static const PointCoordinateType cost = cos(s_defaultArrowAngle);
				static const PointCoordinateType sint = sin(s_defaultArrowAngle);
				CCVector3 A(cost * u.x - sint * u.y,  sint * u.x + cost * u.y, 0);
				CCVector3 B(cost * u.x + sint * u.y, -sint * u.x + cost * u.y, 0);
				glFunc->glBegin(GL_POLYGON);
				ccGL::Vertex3v(glFunc, (A+*P1).u);
				ccGL::Vertex3v(glFunc, (B+*P1).u);
				ccGL::Vertex3v(glFunc, (  *P1).u);
				glFunc->glEnd();
			}
			else
			{
				if (!c_unitArrow)
				{
					c_unitArrow = QSharedPointer<ccCone>(new ccCone(0.5,0.0,1.0));
					c_unitArrow->showColors(true);
					c_unitArrow->showNormals(false);
					c_unitArrow->setVisible(true);
					c_unitArrow->setEnabled(true);
				}
				if (colorsShown())
					c_unitArrow->setTempColor(m_rgbColor);
				else
					c_unitArrow->setTempColor(context.pointsDefaultCol);
				//build-up unit arrow own 'context'
				CC_DRAW_CONTEXT markerContext = context;
				markerContext.flags &= (~CC_DRAW_ENTITY_NAMES); //we must remove the 'push name flag' so that the sphere doesn't push its own!
				markerContext._win = 0;

				glFunc->glMatrixMode(GL_MODELVIEW);
				glFunc->glPushMatrix();
				ccGL::Translate(glFunc,P1->x,P1->y,P1->z);
				ccGLMatrix rotMat = ccGLMatrix::FromToRotation(u,CCVector3(0,0,PC_ONE));
				glFunc->glMultMatrixf(rotMat.inverse().data());
				glFunc->glScalef(m_arrowLength,m_arrowLength,m_arrowLength);
				ccGL::Translate(glFunc,0.0,0.0,-0.5);
				c_unitArrow->draw(markerContext);
				glFunc->glPopMatrix();
			}
		}

		if (m_width != 0)
		{
			glFunc->glPopAttrib();
		}
	}

	//display vertices
	if (m_showVertices)
	{
		glFunc->glPushAttrib(GL_POINT_BIT);
		glFunc->glPointSize((GLfloat)m_vertMarkWidth);

		glFunc->glBegin(GL_POINTS);
		for (unsigned i=0; i<vertCount; ++i)
		{
			ccGL::Vertex3v(glFunc, getPoint(i)->u);
		}
		glFunc->glEnd();

		glFunc->glPopAttrib();
	}

	if (pushName)
		glFunc->glPopName();
}
void QHttpNetworkConnectionChannel::_q_connected()
{
    // For the Happy Eyeballs we need to check if this is the first channel to connect.
    if (connection->d_func()->networkLayerState == QHttpNetworkConnectionPrivate::HostLookupPending || connection->d_func()->networkLayerState == QHttpNetworkConnectionPrivate::IPv4or6) {
        if (connection->d_func()->delayedConnectionTimer.isActive())
            connection->d_func()->delayedConnectionTimer.stop();
        if (networkLayerPreference == QAbstractSocket::IPv4Protocol)
            connection->d_func()->networkLayerState = QHttpNetworkConnectionPrivate::IPv4;
        else if (networkLayerPreference == QAbstractSocket::IPv6Protocol)
            connection->d_func()->networkLayerState = QHttpNetworkConnectionPrivate::IPv6;
        else {
            if (socket->peerAddress().protocol() == QAbstractSocket::IPv4Protocol)
                connection->d_func()->networkLayerState = QHttpNetworkConnectionPrivate::IPv4;
            else
                connection->d_func()->networkLayerState = QHttpNetworkConnectionPrivate::IPv6;
        }
        connection->d_func()->networkLayerDetected(networkLayerPreference);
    } else {
        if (((connection->d_func()->networkLayerState == QHttpNetworkConnectionPrivate::IPv4) && (networkLayerPreference != QAbstractSocket::IPv4Protocol))
            || ((connection->d_func()->networkLayerState == QHttpNetworkConnectionPrivate::IPv6) && (networkLayerPreference != QAbstractSocket::IPv6Protocol))) {
            close();
            // This is the second connection so it has to be closed and we can schedule it for another request.
            QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
            return;
        }
        //The connections networkLayerState had already been decided.
    }

    // improve performance since we get the request sent by the kernel ASAP
    //socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
    // We have this commented out now. It did not have the effect we wanted. If we want to
    // do this properly, Qt has to combine multiple HTTP requests into one buffer
    // and send this to the kernel in one syscall and then the kernel immediately sends
    // it as one TCP packet because of TCP_NODELAY.
    // However, this code is currently not in Qt, so we rely on the kernel combining
    // the requests into one TCP packet.

    // not sure yet if it helps, but it makes sense
    socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

    pipeliningSupported = QHttpNetworkConnectionChannel::PipeliningSupportUnknown;

    // ### FIXME: if the server closes the connection unexpectedly, we shouldn't send the same broken request again!
    //channels[i].reconnectAttempts = 2;
    if (pendingEncrypt) {
#ifndef QT_NO_SSL
        if (connection->sslContext().isNull()) {
            // this socket is making the 1st handshake for this connection,
            // we need to set the SSL context so new sockets can reuse it
            QSharedPointer<QSslContext> socketSslContext = QSslSocketPrivate::sslContext(static_cast<QSslSocket*>(socket));
            if (!socketSslContext.isNull())
                connection->setSslContext(socketSslContext);
        }
#endif
    } else {
        state = QHttpNetworkConnectionChannel::IdleState;
        if (!reply)
            connection->d_func()->dequeueRequest(socket);
        if (reply)
            sendRequest();
    }
}
Ejemplo n.º 24
0
void Wallet::handleChallengeOwnershipPacket(QSharedPointer<ReceivedMessage> packet, SharedNodePointer sendingNode) {
    auto nodeList = DependencyManager::get<NodeList>();

    // With EC keys, we receive a nonce from the metaverse server, which is signed
    // here with the private key and returned.  Verification is done at server.

    bool challengeOriginatedFromClient = packet->getType() == PacketType::ChallengeOwnershipRequest;
    int status;
    int certIDByteArraySize;
    int textByteArraySize;
    int challengingNodeUUIDByteArraySize;

    packet->readPrimitive(&certIDByteArraySize);
    packet->readPrimitive(&textByteArraySize);  // returns a cast char*, size
    if (challengeOriginatedFromClient) {
        packet->readPrimitive(&challengingNodeUUIDByteArraySize);
    }

    // "encryptedText"  is now a series of random bytes, a nonce
    QByteArray certID = packet->read(certIDByteArraySize);
    QByteArray text = packet->read(textByteArraySize);
    QByteArray challengingNodeUUID;
    if (challengeOriginatedFromClient) {
        challengingNodeUUID = packet->read(challengingNodeUUIDByteArraySize);
    }

    EC_KEY* ec = readKeys(keyFilePath().toStdString().c_str());
    QString sig;

   if (ec) {
        ERR_clear_error();
        sig = signWithKey(text, ""); // base64 signature, QByteArray cast (on return) to QString FIXME should pass ec as string so we can tell which key to sign with
        status = 1;
    } else {
        qCDebug(commerce) << "During entity ownership challenge, creating the EC-signed nonce failed.";
        status = -1;
    }

    EC_KEY_free(ec);

    QByteArray textByteArray;
    if (status > -1) {
        textByteArray = sig.toUtf8();
    }
    textByteArraySize = textByteArray.size();
    int certIDSize = certID.size();
    // setup the packet
    if (challengeOriginatedFromClient) {
        auto textPacket = NLPacket::create(PacketType::ChallengeOwnershipReply,
            certIDSize + textByteArraySize + challengingNodeUUIDByteArraySize + 3 * sizeof(int),
            true);

        textPacket->writePrimitive(certIDSize);
        textPacket->writePrimitive(textByteArraySize);
        textPacket->writePrimitive(challengingNodeUUIDByteArraySize);
        textPacket->write(certID);
        textPacket->write(textByteArray);
        textPacket->write(challengingNodeUUID);

        qCDebug(commerce) << "Sending ChallengeOwnershipReply Packet containing signed text" << textByteArray << "for CertID" << certID;

        nodeList->sendPacket(std::move(textPacket), *sendingNode);
    } else {
        auto textPacket = NLPacket::create(PacketType::ChallengeOwnership, certIDSize + textByteArraySize + 2 * sizeof(int), true);

        textPacket->writePrimitive(certIDSize);
        textPacket->writePrimitive(textByteArraySize);
        textPacket->write(certID);
        textPacket->write(textByteArray);

        qCDebug(commerce) << "Sending ChallengeOwnership Packet containing signed text" << textByteArray << "for CertID" << certID;

        nodeList->sendPacket(std::move(textPacket), *sendingNode);
    }

    if (status == -1) {
        qCDebug(commerce) << "During entity ownership challenge, signing the text failed.";
        long error = ERR_get_error();
        if (error != 0) {
            const char* error_str = ERR_error_string(error, NULL);
            qCWarning(entities) << "EC error:" << error_str;
        }
    }
}
Ejemplo n.º 25
0
//----------------------------------------------------------------------------
ctkPluginPrivate::ctkPluginPrivate(
    QWeakPointer<ctkPlugin> qq,
    ctkPluginFrameworkContext* fw,
    QSharedPointer<ctkPluginArchive> pa)
      : q_ptr(qq), fwCtx(fw), id(pa->getPluginId()),
      location(pa->getPluginLocation().toString()), state(ctkPlugin::INSTALLED),
      archive(pa), pluginContext(0), pluginActivator(0), pluginLoader(pa->getLibLocation()),
      resolveFailException(0), eagerActivation(false), wasStarted(false)
{
  //TODO
  //checkCertificates(pa);

  // Get library load hints
  if (fw->props.contains(ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS))
  {
    QVariant loadHintsVariant = fw->props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS];
    if (loadHintsVariant.isValid())
    {
      QLibrary::LoadHints loadHints = loadHintsVariant.value<QLibrary::LoadHints>();
      pluginLoader.setLoadHints(loadHints);
    }
  }

  checkManifestHeaders();

  pluginDir = fwCtx->getDataStorage(id);
//  int oldStartLevel = archive->getStartLevel();
  try
  {
    //TODO: StartLevel Service
    //if (fwCtx->startLevelController == 0)
    //{
      archive->setStartLevel(0);
    //}
//    else
//    {
//      if (oldStartLevel == -1)
//      {
//        archive->setStartLevel(fwCtx->startLevelController->getInitialPluginStartLevel());
//      }
//    }
  }
  catch (const std::exception& e)
  {
    qDebug() << "Failed to set start level on #" << id << ":" << e.what();
  }

  lastModified = archive->getLastModified();
  if (lastModified.isNull())
  {
    modified();
  }

  // fill require list
  QString requireString = archive->getAttribute(ctkPluginConstants::REQUIRE_PLUGIN);
  QList<QMap<QString, QStringList> > requireList = ctkPluginFrameworkUtil::parseEntries(ctkPluginConstants::REQUIRE_PLUGIN,
                                                                                        requireString, true, true, false);
  QListIterator<QMap<QString, QStringList> > i(requireList);
  while (i.hasNext())
  {
    const QMap<QString, QStringList>& e = i.next();
    const QStringList& res = e.value(ctkPluginConstants::RESOLUTION_DIRECTIVE);
    const QStringList& version = e.value(ctkPluginConstants::PLUGIN_VERSION_ATTRIBUTE);
    ctkRequirePlugin* rp = new ctkRequirePlugin(this, e.value("$key").front(),
                                                res.empty() ? QString() : res.front(),
                                                version.empty() ? QString() : version.front());
    require.push_back(rp);
  }
}
Ejemplo n.º 26
0
	// if at least one SW build command is invalid
	foreach (QSharedPointer<SWBuildCommand> buildCom, swBuildComs_) {
		if (!buildCom->isValid()) {
			return false;
		}
	}
Ejemplo n.º 27
0
RS::Orientation RPolyline::getOrientation() const {
    if (!isGeometricallyClosed()) {
        return RS::Any;
    }

    RVector minV = RVector::invalid;
    QSharedPointer<RDirected> shapeBefore;
    QSharedPointer<RDirected> shapeAfter;
    QSharedPointer<RShape> shape;
    QSharedPointer<RDirected> previousShape = getSegmentAt(countSegments()-1).dynamicCast<RDirected>();

    // find minimum vertex (lower left corner):
    QList<QSharedPointer<RShape> > segments = getExploded();
    for (int i=0; i<segments.length(); i++) {
        shape = getSegmentAt(i);
        if (shape.isNull()) {
            continue;
        }
        QSharedPointer<RDirected> directed = shape.dynamicCast<RDirected>();
        if (directed.isNull()) {
            continue;
        }

        RVector v = directed->getStartPoint();
        if (!minV.isValid() || v.x<minV.x || (v.x==minV.x && v.y<minV.y)) {
            minV = v;
            shapeBefore = previousShape;
            shapeAfter = directed;
        }

        previousShape = directed;
    }

    double l;
    RVector p;
    QSharedPointer<RArc> arcBefore = shapeBefore.dynamicCast<RArc>();
    if (!arcBefore.isNull()) {
        l = arcBefore->getLength();
        p = arcBefore->getPointsWithDistanceToEnd(l/10, RS::FromStart)[0];
        shapeBefore = QSharedPointer<RLine>(new RLine(p, arcBefore->getEndPoint()));
    }

    QSharedPointer<RArc> arcAfter = shapeAfter.dynamicCast<RArc>();
    if (!arcAfter.isNull()) {
        l = arcAfter->getLength();
        p = arcAfter->getPointsWithDistanceToEnd(l/10, RS::FromEnd)[0];
        shapeAfter = QSharedPointer<RLine>(new RLine(arcAfter->getStartPoint(), p));
    }

    double xa = shapeBefore->getStartPoint().x;
    double ya = shapeBefore->getStartPoint().y;
    double xb = shapeAfter->getStartPoint().x;
    double yb = shapeAfter->getStartPoint().y;
    double xc = shapeAfter->getEndPoint().x;
    double yc = shapeAfter->getEndPoint().y;

    double det = (xb-xa) * (yc-ya) - (xc-xa) * (yb-ya);

    if (det<0.0) {
        // clockwise:
        return RS::CW;
    }
    else {
        // counter-clockwise:
        return RS::CCW;
    }
}
Ejemplo n.º 28
0
QSharedPointer<IChatMsg> ConversationService::openConversation(quint32 conversationId, quint32 userId) const {
    qDebug() << "[ConversationService][openConversation] c: " << conversationId << " u: " << userId;
    //Get newest MAX_MESSAGES_ON_OPEN messages
    QSharedPointer<QSqlQuery> query = manager->getDbService().prepare(
        "SELECT m.id, m.message, m.time, m.conversation_id, u.id, u.username "
        "FROM message AS m JOIN user AS u ON m.user_id = u.id "
        "WHERE m.conversation_id = :conversationid "
        "ORDER BY m.time DESC "
        "LIMIT 0, :max;");
    bool ok = false;
    if(!query.isNull()){
        query->bindValue(":conversationid", conversationId);
        query->bindValue(":max", MAX_MESSAGES_ON_OPEN);
        ok = manager->getDbService().exec(query);
    }
    if(!ok){ return manager->getProtocol().createResponse(RequestType::OpenConversation, ErrorType::Internal, QStringLiteral("")); }
    StreamableVector messages(new QVector<IStreamable*>()); //Potential performance improvement: predefine row count
    while(query->next()){
        messages->push_back(new Message());
        Message * msg = static_cast<Message*>(messages->last());
        msg->id = query->value(0).toInt();
        msg->message = QSharedPointer<QString>(new QString(query->value(1).toString()));
        msg->time = query->value(2).toDateTime().toTime_t();
        msg->conversationId = query->value(3).toInt();
        msg->userId = query->value(4).toInt();
        msg->username = QSharedPointer<QString>(new QString(query->value(5).toString()));
    }
    return manager->getProtocol().createResponseMessages(RequestType::OpenConversation, true, messages, conversationId);
}
Ejemplo n.º 29
0
void ChildObject::setParentObject2(const QSharedPointer<ParentObject> &parentObject)
{
    m_parentObject2 = parentObject.toWeakRef();
}
Ejemplo n.º 30
0
bool
AudioEngine::loadTrack( const Tomahawk::result_ptr& result )
{
    bool err = false;
    {
        QSharedPointer<QIODevice> io;

        if ( result.isNull() )
            err = true;
        else
        {
            setCurrentTrack( result );

            if ( !isHttpResult( m_currentTrack->url() ) && !isLocalResult( m_currentTrack->url() ) )
            {
                io = Servent::instance()->getIODeviceForUrl( m_currentTrack );

                if ( !io || io.isNull() )
                {
                    tLog() << "Error getting iodevice for" << result->url();
                    err = true;
                }
            }
        }

        if ( !err )
        {
            tLog() << "Starting new song:" << m_currentTrack->url();
            emit loading( m_currentTrack );

            if ( !isHttpResult( m_currentTrack->url() ) && !isLocalResult( m_currentTrack->url() ) )
            {
                if ( QNetworkReply* qnr_io = qobject_cast< QNetworkReply* >( io.data() ) )
                    m_mediaObject->setCurrentSource( new QNR_IODeviceStream( qnr_io, this ) );
                else
                    m_mediaObject->setCurrentSource( io.data() );
                m_mediaObject->currentSource().setAutoDelete( false );
            }
            else
            {
                if ( !isLocalResult( m_currentTrack->url() ) )
                {
                    QUrl furl = m_currentTrack->url();
                    if ( m_currentTrack->url().contains( "?" ) )
                    {
                        furl = QUrl( m_currentTrack->url().left( m_currentTrack->url().indexOf( '?' ) ) );
                        furl.setEncodedQuery( QString( m_currentTrack->url().mid( m_currentTrack->url().indexOf( '?' ) + 1 ) ).toLocal8Bit() );
                    }
                    m_mediaObject->setCurrentSource( furl );
                }
                else
                {
                    QString furl = m_currentTrack->url();
#ifdef Q_WS_WIN
                    if ( furl.startsWith( "file://" ) )
                        furl = furl.right( furl.length() - 7 );
#endif
                    tLog( LOGVERBOSE ) << "Passing to Phonon:" << furl << furl.toLatin1();
                    m_mediaObject->setCurrentSource( furl );
                }

                m_mediaObject->currentSource().setAutoDelete( true );
            }

            if ( !m_input.isNull() )
            {
                m_input->close();
                m_input.clear();
            }
            m_input = io;
            m_mediaObject->play();
            emit started( m_currentTrack );

            if ( TomahawkSettings::instance()->verboseNotifications() )
                sendNowPlayingNotification();

            if ( TomahawkSettings::instance()->privateListeningMode() != TomahawkSettings::FullyPrivate )
            {
                DatabaseCommand_LogPlayback* cmd = new DatabaseCommand_LogPlayback( m_currentTrack, DatabaseCommand_LogPlayback::Started );
                Database::instance()->enqueue( QSharedPointer<DatabaseCommand>(cmd) );

                Tomahawk::InfoSystem::InfoStringHash trackInfo;
                trackInfo["title"] = m_currentTrack->track();
                trackInfo["artist"] = m_currentTrack->artist()->name();
                trackInfo["album"] = m_currentTrack->album()->name();

                Tomahawk::InfoSystem::InfoSystem::instance()->pushInfo(
                    s_aeInfoIdentifier,
                    Tomahawk::InfoSystem::InfoNowPlaying,
                    QVariant::fromValue< Tomahawk::InfoSystem::InfoStringHash >( trackInfo ) );
            }
        }
    }

    if ( err )
    {
        stop();
        return false;
    }

    m_waitingOnNewTrack = false;
    return true;
}