Beispiel #1
0
void mythfile_open_register_callback(const char *pathname, void* object,
                                     callback_t func)
{
    m_callbackLock.lock();
    QString path(pathname);
    if (m_fileOpenCallbacks.contains(path))
    {
        // if we already have a callback registered for this path with this
        // object then remove the callback and return (i.e. end callback)
        QMutableHashIterator<QString,Callback> it(m_fileOpenCallbacks);
        while (it.hasNext())
        {
            it.next();
            if (object == it.value().m_object)
            {
                it.remove();
                VERBOSE(VB_PLAYBACK, LOC +
                    QString("Removing fileopen callback for %1").arg(path));
                VERBOSE(VB_PLAYBACK, LOC + QString("%1 callbacks remaining")
                    .arg(m_fileOpenCallbacks.size()));
                m_callbackLock.unlock();
                return;
            }
        }
    }

    Callback new_callback(object, func);
    m_fileOpenCallbacks.insert(path, new_callback);
    VERBOSE(VB_PLAYBACK, LOC +
        QString("Added fileopen callback for %1").arg(path));
    VERBOSE(VB_PLAYBACK, LOC + QString("%1 callbacks open")
        .arg(m_fileOpenCallbacks.size()));

    m_callbackLock.unlock();
}
bool ProjectCollection::addProject(const QString& name, const QString& author, const QString& description, const QMultiHash<int, QString> & users)
{
    if (!k->db->exists(name)) {
        if (!k->projects.contains(name)) {
            
            QMultiHash<SProject::UserType, QString> newusers; 
            foreach (int type, users.uniqueKeys()) {
                     foreach (QString login, users.values(type))
                              newusers.insert( SProject::UserType(type), login);
            }

            if (newusers.values(SProject::Owner).empty())
                return false;
            
            SProject *project = new SProject( kAppProp->cacheDir() +"/"+ k->db->nextFileName());
            project->setProjectName(name);
            project->setAuthor(author);
            project->setDescription(description);
            bool okAddProject = false;
            
            project->setUsers(newusers);
            
            bool okSaveProject = project->save();
            if (okSaveProject)
                okAddProject = k->db->addProject(project);

            delete project;

            return okAddProject;
        }
    }
Beispiel #3
0
void tst_QVersitDocument::testRemoveProperty()
{
    // Remove an empty property.
    QCOMPARE(mVersitDocument->properties().count(), 0);
    QVersitProperty property;
    mVersitDocument->addProperty(property);
    mVersitDocument->removeProperty(property);
    QCOMPARE(mVersitDocument->properties().count(), 0);

    // A full property.
    property.setName(QLatin1String("TEL"));
    property.setGroups(QStringList(QLatin1String("HOME")));
    QMultiHash<QString, QString> params;
    params.insert(QLatin1String("TYPE"), QLatin1String("HOME"));
    property.setParameters(params);
    property.setValue(QLatin1String("123"));
    mVersitDocument->addProperty(property);
    QCOMPARE(mVersitDocument->properties().count(), 1);
    QVersitProperty property2;
    property2.setName(QLatin1String("TEL"));
    // Remove with a partial property fails.
    mVersitDocument->removeProperty(property2);
    QCOMPARE(mVersitDocument->properties().count(), 1);
    property2.setGroups(QStringList(QLatin1String("HOME")));
    property2.setParameters(params);
    property2.setValue(QLatin1String("123"));
    // Remove with a fully specified property succeeds.
    mVersitDocument->removeProperty(property2);
    QCOMPARE(mVersitDocument->properties().count(), 0);
}
Beispiel #4
0
void XKCommon::saveClusters(QDataStream&stream,SuperVoxelClusters&clusters)
{
    QMultiHash<uint32_t,QByteArray> qClusters;
    foreach (SuperVoxelClusters::value_type v, clusters) {
        QByteArray data;
        QDataStream stream(&data,QIODevice::WriteOnly);
        saveSuperVoxel(stream,*v.second);
        qClusters.insert(v.first,data);
    }
Beispiel #5
0
bool LimitedNodeList::packetVersionMatch(const udt::Packet& packet) {
    PacketType headerType = NLPacket::typeInHeader(packet);
    PacketVersion headerVersion = NLPacket::versionInHeader(packet);
    
    if (headerVersion != versionForPacketType(headerType)) {
        
        static QMultiHash<QUuid, PacketType> sourcedVersionDebugSuppressMap;
        static QMultiHash<HifiSockAddr, PacketType> versionDebugSuppressMap;
        
        bool hasBeenOutput = false;
        QString senderString;
        
        if (NON_SOURCED_PACKETS.contains(headerType)) {
            const HifiSockAddr& senderSockAddr = packet.getSenderSockAddr();
            hasBeenOutput = versionDebugSuppressMap.contains(senderSockAddr, headerType);
            
            if (!hasBeenOutput) {
                versionDebugSuppressMap.insert(senderSockAddr, headerType);
                senderString = QString("%1:%2").arg(senderSockAddr.getAddress().toString()).arg(senderSockAddr.getPort());
            }
        } else {
            QUuid sourceID = NLPacket::sourceIDInHeader(packet);
            
            hasBeenOutput = sourcedVersionDebugSuppressMap.contains(sourceID, headerType);
            
            if (!hasBeenOutput) {
                sourcedVersionDebugSuppressMap.insert(sourceID, headerType);
                senderString = uuidStringWithoutCurlyBraces(sourceID.toString());
            }
        }
        
        if (!hasBeenOutput) {
            qCDebug(networking) << "Packet version mismatch on" << headerType << "- Sender"
                << senderString << "sent" << qPrintable(QString::number(headerVersion)) << "but"
                << qPrintable(QString::number(versionForPacketType(headerType))) << "expected.";
            
            emit packetVersionMismatch(headerType);
        }
        
        return false;
    } else {
        return true;
    }
}
Beispiel #6
0
SessionsManagerDialog::SessionsManagerDialog(QWidget *parent) : Dialog(parent),
	m_ui(new Ui::SessionsManagerDialog)
{
	m_ui->setupUi(this);
	m_ui->openInExistingWindowCheckBox->setChecked(SettingsManager::getValue(SettingsManager::Sessions_OpenInExistingWindowOption).toBool());

	const QStringList sessions(SessionsManager::getSessions());
	QMultiHash<QString, SessionInformation> information;

	for (int i = 0; i < sessions.count(); ++i)
	{
		const SessionInformation session(SessionsManager::getSession(sessions.at(i)));

		information.insert((session.title.isEmpty() ? tr("(Untitled)") : session.title), session);
	}

	QStandardItemModel *model(new QStandardItemModel(this));
	model->setHorizontalHeaderLabels(QStringList({tr("Title"), tr("Identifier"), tr("Windows")}));

	const QList<SessionInformation> sorted(information.values());
	const QString currentSession(SessionsManager::getCurrentSession());
	int row(0);

	for (int i = 0; i < sorted.count(); ++i)
	{
		int windows(0);

		for (int j = 0; j < sorted.at(i).windows.count(); ++j)
		{
			windows += sorted.at(i).windows.at(j).windows.count();
		}

		if (sorted.at(i).path == currentSession)
		{
			row = i;
		}

		QList<QStandardItem*> items({new QStandardItem(sorted.at(i).title.isEmpty() ? tr("(Untitled)") : sorted.at(i).title), new QStandardItem(sorted.at(i).path), new QStandardItem(tr("%n window(s) (%1)", "", sorted.at(i).windows.count()).arg(tr("%n tab(s)", "", windows)))});
		items[0]->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
		items[1]->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
		items[2]->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);

		model->appendRow(items);
	}

	m_ui->sessionsViewWidget->setModel(model);

	connect(m_ui->openButton, SIGNAL(clicked()), this, SLOT(openSession()));
	connect(m_ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteSession()));
	connect(m_ui->sessionsViewWidget, SIGNAL(needsActionsUpdate()), this, SLOT(updateActions()));

	m_ui->sessionsViewWidget->setCurrentIndex(m_ui->sessionsViewWidget->getIndex(row, 0));
}
Beispiel #7
0
void MainWindow::menuSessionsAboutToShow()
{
	if (m_sessionsGroup)
	{
		m_sessionsGroup->deleteLater();

		QAction *saveSessionAction = m_ui->menuSessions->actions().at(0);
		saveSessionAction->setParent(this);

		QAction *manageSessionsAction = m_ui->menuSessions->actions().at(1);
		manageSessionsAction->setParent(this);

		m_ui->menuSessions->clear();
		m_ui->menuSessions->addAction(saveSessionAction);
		m_ui->menuSessions->addAction(manageSessionsAction);
		m_ui->menuSessions->addSeparator();
	}

	m_sessionsGroup = new QActionGroup(this);
	m_sessionsGroup->setExclusive(true);

	const QStringList sessions = SessionsManager::getSessions();
	QMultiHash<QString, SessionInformation> information;

	for (int i = 0; i < sessions.count(); ++i)
	{
		const SessionInformation session = SessionsManager::getSession(sessions.at(i));

		information.insert((session.title.isEmpty() ? tr("(Untitled)") : session.title), session);
	}

	const QList<SessionInformation> sorted = information.values();
	const QString currentSession = SessionsManager::getCurrentSession();

	for (int i = 0; i < sorted.count(); ++i)
	{
		int windows = 0;

		for (int j = 0; j < sorted.at(i).windows.count(); ++j)
		{
			windows += sorted.at(i).windows.at(j).windows.count();
		}

		QAction *action = m_ui->menuSessions->addAction(tr("%1 (%n tab(s))", "", windows).arg(sorted.at(i).title.isEmpty() ? tr("(Untitled)") : QString(sorted.at(i).title).replace(QLatin1Char('&'), QLatin1String("&&"))));
		action->setData(sorted.at(i).path);
		action->setCheckable(true);
		action->setChecked(sorted.at(i).path == currentSession);

		m_sessionsGroup->addAction(action);
	}
}
bool PtDrugDatatabaseStep::createDatabase()
{
    Q_EMIT progressLabelChanged(tr("Preparing raw source files"));
    Q_EMIT progressRangeChanged(0, 1);
    Q_EMIT progress(0);

    if (!DrugsDB::Tools::createMasterDrugInteractionDatabase())
        return false;

    QMultiHash<QString, QVariant> labels;
    labels.insert("fr","Base de données thérapeutique du portugaise");
    labels.insert("en","Portuguese therapeutic database");
    labels.insert("de","Portugiesische Therapeutische Datenbank");

    if (DrugsDB::Tools::createNewDrugsSource(Core::Constants::MASTER_DATABASE_NAME, PT_DRUGS_DATABASE_NAME, labels) == -1) {
        LOG_ERROR("Unable to create the PT drugs sources");
        return false;
    }

    LOG(QString("Database schema created"));
    Q_EMIT progress(1);
    return true;
}
Beispiel #9
0
    bool operator()(SceneNode *n, const glm::mat4 &v)
    {
        if(!n->m_properties)
            return true;

        for (GroupProperty_Data &prop : *n->m_properties)
        {
            if(prop.propName == "SpawnLocation")
            {
                //qCDebug(logPlayerSpawn) << "Spawner:" << prop.propValue << prop.propertyType;
                m_targets->insert(prop.propValue, v);
                return false;
            }
        }
        return true;
    }
SessionsManagerDialog::SessionsManagerDialog(QWidget *parent) : Dialog(parent),
	m_ui(new Ui::SessionsManagerDialog)
{
	m_ui->setupUi(this);
	m_ui->openInExistingWindowCheckBox->setChecked(SettingsManager::getValue(QLatin1String("Sessions/OpenInExistingWindow")).toBool());

	const QStringList sessions = SessionsManager::getSessions();
	QMultiHash<QString, SessionInformation> information;

	for (int i = 0; i < sessions.count(); ++i)
	{
		const SessionInformation session = SessionsManager::getSession(sessions.at(i));

		information.insert((session.title.isEmpty() ? tr("(Untitled)") : session.title), session);
	}

	const QList<SessionInformation> sorted = information.values();
	const QString currentSession = SessionsManager::getCurrentSession();
	int index = 0;

	m_ui->sessionsWidget->setRowCount(sorted.count());

	for (int i = 0; i < sorted.count(); ++i)
	{
		int windows = 0;

		for (int j = 0; j < sorted.at(i).windows.count(); ++j)
		{
			windows += sorted.at(i).windows.at(j).windows.count();
		}

		if (sorted.at(i).path == currentSession)
		{
			index = i;
		}

		m_ui->sessionsWidget->setItem(i, 0, new QTableWidgetItem(sorted.at(i).title.isEmpty() ? tr("(Untitled)") : sorted.at(i).title));
		m_ui->sessionsWidget->setItem(i, 1, new QTableWidgetItem(sorted.at(i).path));
		m_ui->sessionsWidget->setItem(i, 2, new QTableWidgetItem(QStringLiteral("%1 (%2)").arg(sorted.at(i).windows.count()).arg(windows)));
	}

	connect(m_ui->openButton, SIGNAL(clicked()), this, SLOT(openSession()));
	connect(m_ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteSession()));
	connect(m_ui->sessionsWidget, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(currentChanged(int)));

	m_ui->sessionsWidget->setCurrentCell(index, 0);
}
// Add the given name/value pair to the current class info hash.
PyObject *qpycore_ClassInfo(const char *name, const char *value)
{
    PyFrameObject *frame = PyEval_GetFrame();

    // We need the frame we were called from, not the current one.
    if (frame)
        frame = frame->f_back;

    if (!frame)
    {
        PyErr_SetString(PyExc_RuntimeError, "no current frame");
        return 0;
    }

    class_info_hash.insert(frame,
            ClassInfo(QByteArray(name), QByteArray(value)));

    Py_INCREF(Py_None);
    return Py_None;
}
Beispiel #12
0
void IcecastService::ParseDirectoryFinished(
    QFuture<IcecastBackend::StationList> future) {
  IcecastBackend::StationList all_stations = future.result();
  sort(all_stations.begin(), all_stations.end(),
       StationSorter<IcecastBackend::Station>());
  // Remove duplicates by name. These tend to be multiple URLs for the same
  // station.
  IcecastBackend::StationList::iterator it =
      unique(all_stations.begin(), all_stations.end(),
             StationEquality<IcecastBackend::Station>());
  all_stations.erase(it, all_stations.end());

  // Cluster stations by genre.
  QMultiHash<QString, IcecastBackend::Station*> genres;

  // Add stations.
  for (int i = 0; i < all_stations.count(); ++i) {
    IcecastBackend::Station& s = all_stations[i];
    genres.insert(s.genre, &s);
  }

  QSet<QString> genre_set = genres.keys().toSet();

  // Merge genres with only 1 or 2 stations into "Other".
  for (const QString& genre : genre_set) {
    if (genres.count(genre) < 3) {
      const QList<IcecastBackend::Station*>& small_genre = genres.values(genre);
      for (IcecastBackend::Station* s : small_genre) {
        s->genre = "Other";
      }
    }
  }

  backend_->ClearAndAddStations(all_stations);

  app_->task_manager()->SetTaskFinished(load_directory_task_id_);
  load_directory_task_id_ = 0;
}
bool OsmAnd::MapRendererTiledSymbolsResource::uploadToGPU()
{
    typedef std::pair< std::shared_ptr<MapSymbol>, std::shared_ptr<const GPUAPI::ResourceInGPU> > SymbolResourceEntry;

    bool ok;
    bool anyUploadFailed = false;

    const auto link_ = link.lock();
    const auto collection = static_cast<MapRendererTiledSymbolsResourcesCollection*>(&link_->collection);

    // Unique
    QMultiHash< std::shared_ptr<GroupResources>, SymbolResourceEntry > uniqueUploaded;
    for (const auto& groupResources : constOf(_uniqueGroupsResources))
    {
        for (const auto& symbol : constOf(groupResources->group->symbols))
        {
            // Prepare data and upload to GPU
            std::shared_ptr<const GPUAPI::ResourceInGPU> resourceInGPU;
            ok = resourcesManager->uploadSymbolToGPU(symbol, resourceInGPU);

            // If upload have failed, stop
            if (!ok)
            {
                LogPrintf(LogSeverityLevel::Error, "Failed to upload unique symbol in %dx%d@%d tile",
                    tileId.x, tileId.y, zoom);

                anyUploadFailed = true;
                break;
            }

            // Mark this symbol as uploaded
            uniqueUploaded.insert(groupResources, qMove(SymbolResourceEntry(symbol, resourceInGPU)));
        }
        if (anyUploadFailed)
            break;
    }

    // Shared
    QMultiHash< std::shared_ptr<GroupResources>, SymbolResourceEntry > sharedUploaded;
    QMultiHash< std::shared_ptr<GroupResources>, SymbolResourceEntry > sharedReferenced;
    for (const auto& groupResources : constOf(_referencedSharedGroupsResources))
    {
        if (groupResources->group->symbols.isEmpty())
            continue;

        // This check means "continue if shared symbols were uploaded by other resource"
        // This check needs no special handling, since all GPU resources work is done from same thread.
        if (!groupResources->resourcesInGPU.isEmpty())
        {
            for (const auto& entryResourceInGPU : rangeOf(constOf(groupResources->resourcesInGPU)))
            {
                const auto& symbol = entryResourceInGPU.key();
                auto& resourceInGPU = entryResourceInGPU.value();

                sharedReferenced.insert(groupResources, qMove(SymbolResourceEntry(symbol, resourceInGPU)));
            }
            continue;
        }

        for (const auto& symbol : constOf(groupResources->group->symbols))
        {
            // Prepare data and upload to GPU
            std::shared_ptr<const GPUAPI::ResourceInGPU> resourceInGPU;
            ok = resourcesManager->uploadSymbolToGPU(symbol, resourceInGPU);

            // If upload have failed, stop
            if (!ok)
            {
                LogPrintf(LogSeverityLevel::Error, "Failed to upload unique symbol in %dx%d@%d tile",
                    tileId.x, tileId.y, zoom);

                anyUploadFailed = true;
                break;
            }

            // Mark this symbol as uploaded
            sharedUploaded.insert(groupResources, qMove(SymbolResourceEntry(symbol, resourceInGPU)));
        }
        if (anyUploadFailed)
            break;
    }

    // If at least one symbol failed to upload, consider entire tile as failed to upload,
    // and unload its partial GPU resources
    if (anyUploadFailed)
    {
        uniqueUploaded.clear();
        sharedUploaded.clear();

        return false;
    }

    // All resources have been uploaded to GPU successfully by this point,
    // so it's safe to walk across symbols and remove bitmaps:

    // Unique
    for (const auto& entry : rangeOf(constOf(uniqueUploaded)))
    {
        const auto& groupResources = entry.key();
        const auto& symbol = entry.value().first;
        auto& resource = entry.value().second;

        // Unload GPU data from symbol, since it's uploaded already
        resourcesManager->releaseGpuUploadableDataFrom(symbol);

        // Add GPU resource reference
        _symbolToResourceInGpuLUT.insert(symbol, resource);
#if OSMAND_LOG_MAP_SYMBOLS_TO_GPU_RESOURCES_MAP_CHANGES
        LogPrintf(LogSeverityLevel::Debug,
            "Inserted GPU resource %p for map symbol %p in %p (uploadToGPU-uniqueUploaded)",
            resource.get(),
            symbol.get(),
            this);
#endif // OSMAND_LOG_MAP_SYMBOLS_TO_GPU_RESOURCES_MAP_CHANGES
        groupResources->resourcesInGPU.insert(qMove(symbol), qMove(resource));
    }

    // Shared (uploaded)
    for (const auto& entry : rangeOf(constOf(sharedUploaded)))
    {
        const auto& groupResources = entry.key();
        auto symbol = entry.value().first;
        auto& resource = entry.value().second;

        // Unload GPU data from symbol, since it's uploaded already
        resourcesManager->releaseGpuUploadableDataFrom(symbol);

        // Add GPU resource reference
        _symbolToResourceInGpuLUT.insert(symbol, resource);
#if OSMAND_LOG_MAP_SYMBOLS_TO_GPU_RESOURCES_MAP_CHANGES
        LogPrintf(LogSeverityLevel::Debug,
            "Inserted GPU resource %p for map symbol %p in %p (uploadToGPU-sharedUploaded)",
            resource.get(),
            symbol.get(),
            this);
#endif // OSMAND_LOG_MAP_SYMBOLS_TO_GPU_RESOURCES_MAP_CHANGES
        groupResources->resourcesInGPU.insert(qMove(symbol), qMove(resource));
    }

    // Shared (referenced)
    for (const auto& entry : rangeOf(constOf(sharedReferenced)))
    {
        const auto& groupResources = entry.key();
        auto symbol = entry.value().first;
        auto& resource = entry.value().second;

        // Add GPU resource reference
        _symbolToResourceInGpuLUT.insert(symbol, resource);
#if OSMAND_LOG_MAP_SYMBOLS_TO_GPU_RESOURCES_MAP_CHANGES
        LogPrintf(LogSeverityLevel::Debug,
            "Inserted GPU resource %p for map symbol %p in %p (uploadToGPU-sharedReferenced)",
            resource.get(),
            symbol.get(),
            this);
#endif // OSMAND_LOG_MAP_SYMBOLS_TO_GPU_RESOURCES_MAP_CHANGES
    }

    return true;
}
bool UnicodeTournamentTrie::Preprocess( IImporter* importer, QString dir )
{
	QString filename = fileInDirectory( dir, "Unicode Tournament Trie" );

	QFile subTrieFile( filename + "_sub" );
	QFile wayFile( filename + "_ways" );

	if ( !openQFile( &subTrieFile, QIODevice::WriteOnly ) )
		return false;
	if ( !openQFile( &wayFile, QIODevice::WriteOnly ) )
		return false;

	std::vector< IImporter::Place > inputPlaces;
	std::vector< IImporter::Address > inputAddress;
	std::vector< UnsignedCoordinate > inputWayBuffer;
	std::vector< QString > inputWayNames;
	if ( !importer->GetAddressData( &inputPlaces, &inputAddress, &inputWayBuffer, &inputWayNames ) )
		return false;

	Timer time;

	std::sort( inputAddress.begin(), inputAddress.end() );
	qDebug() << "Unicode Tournament Trie: sorted addresses by importance:" << time.restart() << "ms";

	std::vector< UnsignedCoordinate > wayBuffer;
	std::vector< utt::Node > trie( 1 );
	unsigned address = 0;

	// build address name index
	QMultiHash< unsigned, unsigned > addressByName;
	for ( ; address < inputAddress.size(); address++ ) {
		addressByName.insert( inputAddress[address].name, address );
	}

	// compute way lengths
	QList< unsigned > uniqueNames = addressByName.uniqueKeys();
	std::vector< std::pair< double, unsigned > > wayLengths;
	for ( unsigned name = 0; name < ( unsigned ) uniqueNames.size(); name++ ) {
		QList< unsigned > segments = addressByName.values( uniqueNames[name] );
		double distance = 0;
		for( unsigned segment = 0; segment < ( unsigned ) segments.size(); segment++ ) {
			const IImporter::Address segmentAddress = inputAddress[segment];
			for ( unsigned coord = 1; coord < segmentAddress.pathLength; ++coord ) {
				GPSCoordinate sourceGPS = inputWayBuffer[segmentAddress.pathID + coord - 1].ToProjectedCoordinate().ToGPSCoordinate();
				GPSCoordinate targetGPS = inputWayBuffer[segmentAddress.pathID + coord].ToProjectedCoordinate().ToGPSCoordinate();
				distance += sourceGPS.ApproximateDistance( targetGPS );
			}
		}
		wayLengths.push_back( std::pair< double, unsigned >( distance, name ) );
	}

	// sort ways by aggregate lengths
	std::sort( wayLengths.begin(), wayLengths.end() );
	std::vector< unsigned > wayImportance( uniqueNames.size() );
	for ( unsigned way = 0; way < wayLengths.size(); way++ )
		wayImportance[wayLengths[way].second] = way;
	wayLengths.clear();

	std::vector< utt::Node > subTrie( 1 );

	for ( unsigned name = 0; name < ( unsigned ) uniqueNames.size(); name++ ) {
		QList< unsigned > segments = addressByName.values( uniqueNames[name] );

		// build edge connector data structures
		std::vector< EdgeConnector< UnsignedCoordinate>::Edge > connectorEdges;
		std::vector< unsigned > resultSegments;
		std::vector< unsigned > resultSegmentDescriptions;
		std::vector< bool > resultReversed;

		for ( unsigned segment = 0; segment < ( unsigned ) segments.size(); segment++ ) {
			const IImporter::Address& segmentAddress = inputAddress[segments[segment]];
			EdgeConnector< UnsignedCoordinate >::Edge newEdge;
			newEdge.source = inputWayBuffer[segmentAddress.pathID];
			newEdge.target = inputWayBuffer[segmentAddress.pathID + segmentAddress.pathLength - 1];
			newEdge.reverseable = true;
			connectorEdges.push_back( newEdge );
		}

		EdgeConnector< UnsignedCoordinate >::run( &resultSegments, &resultSegmentDescriptions, &resultReversed, connectorEdges );

		// string places with the same name together
		unsigned nextID = 0;
		for ( unsigned segment = 0; segment < resultSegments.size(); segment++ ) {
			utt::Data subEntry;
			subEntry.start = wayBuffer.size();

			for ( unsigned description = 0; description < resultSegments[segment]; description++ ) {
				unsigned segmentID = resultSegmentDescriptions[nextID + description];
				const IImporter::Address& segmentAddress = inputAddress[segments[segmentID]];
				std::vector< UnsignedCoordinate > path;
				for ( unsigned pathID = 0; pathID < segmentAddress.pathLength; pathID++ )
					path.push_back( inputWayBuffer[pathID + segmentAddress.pathID]);
				if ( resultReversed[segmentID] )
					std::reverse( path.begin(), path.end() );
				int skipFirst = description == 0 ? 0 : 1;
				assert( skipFirst == 0 || wayBuffer.back() == path.front() );
				wayBuffer.insert( wayBuffer.end(), path.begin() + skipFirst, path.end() );
			}
			
			utt::PlaceData placeData;
			placeData.name = inputPlaces[inputAddress[segments[resultSegmentDescriptions[nextID]]].nearPlace].name;

			subEntry.length = wayBuffer.size() - subEntry.start;
			insert( &subTrie, wayImportance[name], inputWayNames[uniqueNames[name]], subEntry, placeData );

			nextID += resultSegments[segment];
		}
	}

	writeTrie( &subTrie, subTrieFile );

	assert( address == inputAddress.size() );
	qDebug() << "Unicode Tournament Trie: build tries and tournament trees:" << time.restart() << "ms";

	for ( std::vector< UnsignedCoordinate >::const_iterator i = wayBuffer.begin(), e = wayBuffer.end(); i != e; ++i ) {
		wayFile.write( ( char* ) &i->x, sizeof( i->x ) );
		wayFile.write( ( char* ) &i->y, sizeof( i->y ) );
	}
	qDebug() << "Unicode Tournament Trie: wrote ways:" << time.restart() << "ms";

	return true;
}
void QNetworkConfigurationManagerPrivate::doUpdateConfigurations(QList<Maemo::IcdScanResult> scanned)
{
    /* Contains all known iap_ids from storage */
    QList<QString> knownConfigs = accessPointConfigurations.keys();

    /* Contains all known WLAN network ids (like ssid) from storage */
    QMultiHash<QByteArray, SSIDInfo* > notDiscoveredWLANConfigs;

    QList<QString> all_iaps;
    Maemo::IAPConf::getAll(all_iaps);

    foreach (const QString &iap_id, all_iaps) {
	QByteArray ssid;

	Maemo::IAPConf saved_ap(iap_id);
	bool is_temporary = saved_ap.value("temporary").toBool();
    if (is_temporary) {
#ifdef BEARER_MANAGEMENT_DEBUG
	    qDebug() << "IAP" << iap_id << "is temporary, skipping it.";
#endif
	    continue;
	}

	QString iap_type = saved_ap.value("type").toString();
    if (iap_type.startsWith(QLatin1String("WLAN"))) {
	    ssid = saved_ap.value("wlan_ssid").toByteArray();
	    if (ssid.isEmpty()) {
		qWarning() << "Cannot get ssid for" << iap_id;
		continue;
	    }

	    QString security_method = saved_ap.value("wlan_security").toString();
	    SSIDInfo *info = new SSIDInfo;
	    info->iap_id = iap_id;
	    info->wlan_security = security_method;
            notDiscoveredWLANConfigs.insert(ssid, info);
	} else if (iap_type.isEmpty()) {
	    qWarning() << "IAP" << iap_id << "network type is not set! Skipping it";
	    continue;
	} else {
#ifdef BEARER_MANAGEMENT_DEBUG
	    qDebug() << "IAP" << iap_id << "network type is" << iap_type;
#endif
	    ssid.clear();
	}

	if (!accessPointConfigurations.contains(iap_id)) {
	    QNetworkConfigurationPrivate* cpPriv = new QNetworkConfigurationPrivate();
	    cpPriv->name = saved_ap.value("name").toString();
	    if (cpPriv->name.isEmpty()) {
		if (!ssid.isEmpty() && ssid.size() > 0)
		    cpPriv->name = ssid.data();
		else
		    cpPriv->name = iap_id;
	    }
            cpPriv->isValid = true;
	    cpPriv->id = iap_id;
	    cpPriv->network_id = ssid;
	    cpPriv->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString());
	    cpPriv->iap_type = iap_type;
	    cpPriv->service_id = saved_ap.value("service_id").toString();
	    cpPriv->service_type = saved_ap.value("service_type").toString();
	    cpPriv->type = QNetworkConfiguration::InternetAccessPoint;
	    cpPriv->state = QNetworkConfiguration::Defined;
	    cpPriv->manager = this;

	    QExplicitlySharedDataPointer<QNetworkConfigurationPrivate> ptr(cpPriv);
	    accessPointConfigurations.insert(iap_id, ptr);

#ifdef BEARER_MANAGEMENT_DEBUG
	    qDebug("IAP: %s, name: %s, ssid: %s, added to known list", iap_id.toAscii().data(), cpPriv->name.toAscii().data(), !ssid.isEmpty() ? ssid.data() : "-");
#endif
	} else {
            knownConfigs.removeOne(iap_id);
#ifdef BEARER_MANAGEMENT_DEBUG
	    qDebug("IAP: %s, ssid: %s, already exists in the known list", iap_id.toAscii().data(), !ssid.isEmpty() ? ssid.data() : "-");
#endif
	}
    }
Beispiel #16
0
static QMultiHash<QByteArray, QPair<int, float> > createChannelNameMap() {
    QMultiHash<QByteArray, QPair<QByteArray, float> > blendshapeMap;
    blendshapeMap.insert("EyeBlink_L", QPair<QByteArray, float>("Mix::Blink_Left", 1.0f));
    blendshapeMap.insert("EyeBlink_R", QPair<QByteArray, float>("Mix::Blink_Right", 1.0f));
    blendshapeMap.insert("BrowsD_L", QPair<QByteArray, float>("Mix::BrowsDown_Left", 1.0f));
    blendshapeMap.insert("BrowsD_R", QPair<QByteArray, float>("Mix::BrowsDown_Right", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::BrowsIn_Left", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::BrowsIn_Right", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::BrowsOuterLower_Left", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::BrowsOuterLower_Right", 1.0f));
    blendshapeMap.insert("BrowsU_L", QPair<QByteArray, float>("Mix::BrowsUp_Left", 10.0f));
    blendshapeMap.insert("BrowsU_R", QPair<QByteArray, float>("Mix::BrowsUp_Right", 10.0f));
    blendshapeMap.insert("EyeOpen_L", QPair<QByteArray, float>("Mix::EyesWide_Left", 1.0f));
    blendshapeMap.insert("EyeOpen_R", QPair<QByteArray, float>("Mix::EyesWide_Right", 1.0f));
    blendshapeMap.insert("MouthFrown_L", QPair<QByteArray, float>("Mix::Frown_Left", 1.0f));
    blendshapeMap.insert("MouthFrown_R", QPair<QByteArray, float>("Mix::Frown_Right", 1.0f));
    blendshapeMap.insert("JawLeft", QPair<QByteArray, float>("Mix::Jaw_RotateY_Left", 1.0f));
    blendshapeMap.insert("JawRight", QPair<QByteArray, float>("Mix::Jaw_RotateY_Right", 1.0f));
    blendshapeMap.insert("LipsLowerDown", QPair<QByteArray, float>("Mix::LowerLipDown_Left", 0.5f));
    blendshapeMap.insert("LipsLowerDown", QPair<QByteArray, float>("Mix::LowerLipDown_Right", 0.5f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::LowerLipIn", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::LowerLipOut", 1.0f));
    blendshapeMap.insert("MouthLeft", QPair<QByteArray, float>("Mix::Midmouth_Left", 1.0f));
    blendshapeMap.insert("MouthRight", QPair<QByteArray, float>("Mix::Midmouth_Right", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::MouthDown", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::MouthNarrow_Left", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::MouthNarrow_Right", 1.0f));
    blendshapeMap.insert("JawOpen", QPair<QByteArray, float>("Mix::MouthOpen", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::MouthUp", 1.0f));
    blendshapeMap.insert("LipsPucker", QPair<QByteArray, float>("Mix::MouthWhistle_NarrowAdjust_Left", 0.5f));
    blendshapeMap.insert("LipsPucker", QPair<QByteArray, float>("Mix::MouthWhistle_NarrowAdjust_Right", 0.5f));
    blendshapeMap.insert("Sneer", QPair<QByteArray, float>("Mix::NoseScrunch_Left", 0.5f));
    blendshapeMap.insert("Sneer", QPair<QByteArray, float>("Mix::NoseScrunch_Right", 0.5f));
    blendshapeMap.insert("MouthSmile_L", QPair<QByteArray, float>("Mix::Smile_Left", 1.0f));
    blendshapeMap.insert("MouthSmile_R", QPair<QByteArray, float>("Mix::Smile_Right", 1.0f));
    blendshapeMap.insert("EyeSquint_L", QPair<QByteArray, float>("Mix::Squint_Left", 1.0f));
    blendshapeMap.insert("EyeSquint_R", QPair<QByteArray, float>("Mix::Squint_Right", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::UpperLipIn", 1.0f));
    blendshapeMap.insert("...", QPair<QByteArray, float>("Mix::UpperLipOut", 1.0f));
    blendshapeMap.insert("LipsUpperUp", QPair<QByteArray, float>("Mix::UpperLipUp_Left", 0.5f));
    blendshapeMap.insert("LipsUpperUp", QPair<QByteArray, float>("Mix::UpperLipUp_Right", 0.5f));
    
    QMultiHash<QByteArray, QPair<int, float> > channelNameMap;
    for (int i = 0;; i++) {
        QByteArray blendshape = FACESHIFT_BLENDSHAPES[i];
        if (blendshape.isEmpty()) {
            break;
        }
        for (QMultiHash<QByteArray, QPair<QByteArray, float> >::const_iterator it = blendshapeMap.constFind(blendshape);
                it != blendshapeMap.constEnd() && it.key() == blendshape; it++) {
            channelNameMap.insert(it.value().first, QPair<int, float>(i, it.value().second));
        }
    }
    
    return channelNameMap;
}
Beispiel #17
0
void TcDatabase::loadEngine(const QString& filename)
{
    m_sqls.clear();
    if ( m_handle.isOpen() )
    {
        if ( dbType() == SQLSERVER )
        {
            // 取出存储过程名
            QSqlQuery procedures_query = QSqlQuery(m_handle);
            QSqlQuery query = QSqlQuery(m_handle);
            if ( procedures_query.exec("exec sp_procedures_rowset2") )
            {
                while(procedures_query.next())
                {
                    QSqlRecord procedures = procedures_query.record();
                    QSqlField  fieldSchema = procedures.field("PROCEDURE_SCHEMA");
                    if ( fieldSchema.isValid() && fieldSchema.value() != "sys" )
                    {
                        QSqlField  field = procedures.field("PROCEDURE_NAME");
                        if ( field.isValid() )
                        {
                            SQLContext cnt;
                            QString procedureID = field.value().toString().toLower();
                            int index = procedureID.indexOf(";");
                            if ( index >= 0 )
                            {
                                procedureID = procedureID.left(index);
                            }
                            cnt.id = procedureID;
                            QString paramsLine;
                            if ( query.exec("exec sp_procedure_params_rowset '"+procedureID+"'") )
                            {
                                while(query.next())
                                {
                                    QSqlRecord paramField = query.record();
                                    QSqlField  paramName = paramField.field("PARAMETER_NAME");
                                    QString pname = paramName.value().toString();

                                    if ( pname.compare("@RETURN_VALUE", Qt::CaseInsensitive) != 0 )
                                    {
                                        QSqlField  paramType = paramField.field("TYPE_NAME");
                                        pname.remove(0, 1);

                                        QString ptype = paramType.value().toString().toLower();
                                        if ( ptype == "nvarchar" )
                                        {
                                            ptype = "string";
                                        }

                                        cnt.params.insert(pname, ptype);
                                        paramsLine += ", :" + pname;
                                    }
                                }
                                query.finish();

                                if ( ! paramsLine.isEmpty() )
                                {
                                    paramsLine.remove(0, 2);
                                }
                            }
                            cnt.text = "exec " + procedureID + " " + paramsLine;
                            m_sqls[procedureID] = cnt;
                            Q_EMIT dbiLoading(m_sqls.count(), procedureID);
                        }
                    }
                }
                procedures_query.finish();
            }
        }else
        if ( dbType() == MYSQL )
        {
            // 取出存储过程名
            QString sql = "SELECT `name`, `param_list`, `body`, `returns` FROM `mysql`.`proc` WHERE `language` = 'SQL' AND `db` = '"+dbName()+"';";
            QSqlQuery query = QSqlQuery(m_handle);
            if ( query.exec(sql) )
            {
                QSqlField  field;
                while(query.next())
                {
                    QSqlRecord procedures = query.record();

                    QString param_line;

                    SQLContext cnt;
                    cnt.id     = procedures.field("name").value().toString();
                    cnt.params =  getParamList(param_line, procedures.field("param_list").value().toString());
                    cnt.text   = "call " + cnt.id + "(" + param_line + ");";
                    //cnt.text   = procedures.field("body").value().toString();
                    m_sqls[cnt.id] = cnt;
                    Q_EMIT dbiLoading(m_sqls.count(), cnt.id);
                    Q_EMIT dbiLoading(m_sqls.count(), cnt.text);
                }
                query.finish();
            }
        }else
        if ( dbType() == POSTGRESQL )
        {
            // 取出存储过程名
            QSqlQuery storedproc_query = QSqlQuery(m_handle);
            QSqlQuery query = QSqlQuery(m_handle);
            if ( storedproc_query.exec("SELECT specific_name"
                                           " , routine_name"
                                        " FROM information_schema.routines"
                                       " WHERE specific_schema = 'public'"
                                         " AND routine_schema  = 'public'"
                                         " AND routine_type    = 'FUNCTION';") )
            {
                while(storedproc_query.next())
                {
                    QSqlRecord storedprocs = storedproc_query.record();
                    QSqlField  fieldspecific = storedprocs.field("specific_name");
                    QSqlField  fieldsqlid    = storedprocs.field("routine_name" );
                    if ( fieldspecific.isValid() && fieldsqlid.isValid() )
                    {
                        SQLContext cnt;
                        cnt.id = fieldsqlid.value().toString().toLower();
                        QString paramsLine;
                        if ( query.exec("SELECT parameter_name"
                                            " , udt_name"
                                         " FROM information_schema.parameters"
                                        " WHERE specific_schema = 'public'"
                                          " AND specific_name   = '"+fieldspecific.value().toString()+"'"
                                          " AND parameter_mode   = 'IN'"
                                        " ORDER BY ordinal_position;") )
                        {
                            while(query.next())
                            {
                                QSqlRecord fields = query.record();
                                QSqlField  paramName = fields.field("parameter_name");
                                QSqlField  paramType = fields.field("udt_name"      );
                                if ( paramName.isValid() && paramType.isValid() )
                                {
                                    cnt.params.insert(paramName.value().toString(),
                                                      paramType.value().toString());
                                    paramsLine += ", :" + paramName.value().toString();
                                }
                            }
                            query.finish();

                            if ( ! paramsLine.isEmpty() )
                            {
                                paramsLine.remove(0, 2);
                            }
                        }
                        cnt.text = "SELECT * FROM " + cnt.id + "(" + paramsLine + ");";
                        m_sqls[cnt.id] = cnt;
                        Q_EMIT dbiLoading(m_sqls.count(), cnt.id);
                    }
                }
                storedproc_query.finish();
            }
        }
    }
    QStringList filenames;
    QDir dir(filename);
    if ( dir.exists() )
    {
        filenames = dir.entryList(QStringList(), QDir::Files, QDir::Name);
        for( int i=0; i<filenames.count(); i++ )
        {
            QString ddlfile = filenames.at(i);
            filenames[i] = dir.absolutePath() + QDir::separator() + ddlfile;
        }
    }else
    {
        QFileInfo sqlsInfo(filename);
        if ( sqlsInfo.exists() )
        {
            filenames.append(filename);
        }
    }
    foreach(QString ddlfile, filenames)
    {
        QFile f(ddlfile);
        if ( f.open(QFile::Text | QFile::ReadOnly) )
        {
            m_engineFile = ddlfile;

            QTextStream in(&f);

            int                     rdType = 0;
            QString                 sqlId;
            QString                 sqlText;
            QMultiHash<QString, QString> sqlParams;
            while(!in.atEnd())
            {
                QString line = in.readLine().trimmed();
                clearComment(line);
                if ( line.isEmpty() )
                {

                }else
                if ( line.startsWith("SQL:", Qt::CaseInsensitive) )
                {
                    if ( ! sqlId.isEmpty() && ! sqlText.isEmpty() )
                    {
                        sqlText.replace("@", ":");

                        SQLContext cnt;
                        cnt.id     = sqlId;
                        cnt.text   = sqlText;
                        cnt.params = sqlParams;
                        m_sqls[sqlId] = cnt;
                        Q_EMIT dbiLoading(m_sqls.count(), sqlId);
                    }
                    sqlId = line.mid(4).trimmed().toLower();
                    sqlText.clear();
                    sqlParams.clear();
                    rdType = 1;
                }else
                if ( line.startsWith("Params:", Qt::CaseInsensitive) )
                {
                    rdType = 2;
                }else
                if ( ! sqlId.isEmpty() )
                {
                    switch(rdType)
                    {
                    case 1:
                        sqlText += line + "\n";
                        break;
                    case 2:
                    {
                        QString paramName;
                        QString paramType = "string";
                        int pos;
                        if ( (pos=line.indexOf(" ")) >0 )
                        {
                            paramName = line.left(pos);
                            line = line.remove(0, pos).trimmed();
                            if ( (pos=line.indexOf(" ")) >0 )
                            {
                                paramType = line.left(pos);
                            }else
                            {
                                paramType = line;
                            }
                        }else
                        {
                            paramName = line;
                        }
                        QChar c = paramName.at(0);
                        if ( c == ':' || c == '@' )
                        {
                            paramName.remove(0, 1);
                        }
                        sqlParams.insert(paramName, paramType.toLower());
                        break;
                    }
                    }
                }
            }
            f.close();

            if ( ! sqlId.isEmpty() && ! sqlText.isEmpty() )
            {
                SQLContext cnt;
                cnt.id     = sqlId;
                cnt.text   = sqlText;
                cnt.params = sqlParams;
                m_sqls[sqlId] = cnt;
                Q_EMIT dbiLoading(m_sqls.count(), sqlId);
            }
        }
    }
Beispiel #18
0
/** Applies the current network configuration settings to Tor. If
 * <b>errmsg</b> is specified and an error occurs while applying the settings,
 * it will be set to a string describing the error. */
bool
NetworkSettings::apply(QString *errmsg)
{
  QMultiHash<QString, QString> conf;
  quint32 torVersion = torControl()->getTorVersion();

  conf.insert(SETTING_REACHABLE_ADDRESSES,
    (getFascistFirewall() ? 
      localValue(SETTING_REACHABLE_ADDRESSES).toStringList().join(",") : ""));
 
  QString socks4, socks5, http, https;
  QString addr, user, pass, auth;

  addr = localValue(SETTING_PROXY_ADDRESS).toString();
  user = localValue(SETTING_PROXY_USERNAME).toString();
  pass = localValue(SETTING_PROXY_PASSWORD).toString();

  if (!user.isEmpty() || !pass.isEmpty())
    auth = QString("%1:%2").arg(user).arg(pass);
 
  switch (getProxyType()) {
    case NoProxy:
      break;
    case Socks4Proxy:
      socks4 = addr;
      break;
    case Socks5Proxy:
      socks5 = addr;
      break;
    case HttpHttpsProxy:
      http = addr;
      https = http;
      break;
  }

  if (torVersion >= 0x020201) {
    /* SOCKS support was implemented in 0.2.2.1 */
    conf.insert(SETTING_SOCKS4_PROXY, socks4);
    conf.insert(SETTING_SOCKS5_PROXY, socks5);
    conf.insert(SETTING_SOCKS5_USERNAME, user);
    conf.insert(SETTING_SOCKS5_PASSWORD, pass);
  }

  conf.insert(SETTING_HTTPS_PROXY, https);
  conf.insert(SETTING_HTTPS_PROXY_AUTH, auth);

  if (getUseBridges()) {
    /* We want to always enable TunnelDirConns and friends when using
     * bridge relays. */
    conf.insert(SETTING_TUNNEL_DIR_CONNS, "1");
    conf.insert(SETTING_PREFER_TUNNELED_DIR_CONNS, "1");
  } else if (torVersion <= 0x020021) {
    /* TunnelDirConns is enabled by default on Tor >= 0.2.0.22-rc, so don't
     * disable it if our Tor is recent enough. */
    conf.insert(SETTING_TUNNEL_DIR_CONNS, "0");
    conf.insert(SETTING_PREFER_TUNNELED_DIR_CONNS, "0");
  }

  if (torVersion >= 0x020003) {
    /* Do the bridge stuff only on Tor >= 0.2.0.3-alpha */
    QStringList bridges = localValue(SETTING_BRIDGE_LIST).toStringList();
    if (getUseBridges() && !bridges.isEmpty()) {
      conf.insert(SETTING_USE_BRIDGES, "1");
      conf.insert(SETTING_UPDATE_BRIDGES, "1");
      foreach (QString bridge, bridges) {
        conf.insert(SETTING_BRIDGE_LIST, bridge);
      }
Beispiel #19
0
QMultiHash<int, SceneValue> FixtureManager::setFixtureCapabilities(quint32 fxID, bool enable)
{
    int capDelta = 1;
    bool hasDimmer = false, hasColor = false, hasPosition = false;

    QMultiHash<int, SceneValue> channelsMap;

    Fixture *fixture = m_doc->fixture(fxID);
    if (fixture == NULL)
        return channelsMap;

    if (enable == false)
        capDelta = -1;

    for (quint32 ch = 0; ch < fixture->channels(); ch++)
    {
        const QLCChannel* channel(fixture->channel(ch));
        if(channel == NULL)
            continue;

        int chType = channel->group();

        switch (channel->group())
        {
            case QLCChannel::Intensity:
            {
                QLCChannel::PrimaryColour col = channel->colour();
                switch (col)
                {
                    case QLCChannel::NoColour:
                        hasDimmer = true;
                    break;
                    case QLCChannel::Red:
                    case QLCChannel::Green:
                    case QLCChannel::Blue:
                    case QLCChannel::Cyan:
                    case QLCChannel::Magenta:
                    case QLCChannel::Yellow:
                    case QLCChannel::White:
                        hasColor = true;
                    break;
                    default: break;
                }
                chType = col;
            }
            break;
            case QLCChannel::Pan:
            case QLCChannel::Tilt:
                hasPosition = true;
            break;
            default:
            break;
        }
        if (hasDimmer)
        {
            QQuickItem *dimmerCapItem = qobject_cast<QQuickItem*>(m_view->rootObject()->findChild<QObject *>("capIntensity"));
            dimmerCapItem->setProperty("counter", dimmerCapItem->property("counter").toInt() + capDelta);
        }
        if (hasColor)
        {
            QQuickItem *colorCapItem = qobject_cast<QQuickItem*>(m_view->rootObject()->findChild<QObject *>("capColor"));
            colorCapItem->setProperty("counter", colorCapItem->property("counter").toInt() + capDelta);
        }
        if (hasPosition)
        {
            QQuickItem *positionCapItem = qobject_cast<QQuickItem*>(m_view->rootObject()->findChild<QObject *>("capPosition"));
            positionCapItem->setProperty("counter", positionCapItem->property("counter").toInt() + capDelta);
        }

        channelsMap.insert(chType, SceneValue(fxID, ch));
    }
    return channelsMap;
}
Beispiel #20
0
void SwitchWindow::makeMenu()
{
    m_menu->clear();
    Plasma::DataEngine *tasks = dataEngine("tasks");
    if (!tasks->isValid()) {
        return;
    }

    QMultiHash<int, QAction*> desktops;

    //make all the window actions
    foreach (const QString &source, tasks->sources()) {
        Plasma::DataEngine::Data window = tasks->query(source);
        if (window.value("startup").toBool()) {
            //kDebug() << "skipped fake task" << source;
            continue;
        }
        if (!window.value("onCurrentActivity").toBool()) {
            continue;
        }

        QString name = window.value("visibleNameWithState").toString();
        if (name.isEmpty()) {
            kDebug() << "failed source" << source;
            continue;
        }

        QAction *action = new QAction(name, m_menu);
        action->setIcon(window.value("icon").value<QIcon>());
        action->setData(source);
        desktops.insert(window.value("desktop").toInt(), action);
    }

    //sort into menu
    if (m_mode == CurrentDesktop) {
        int currentDesktop = KWindowSystem::currentDesktop();
        m_menu->addTitle(i18n("Windows"));
        m_menu->addActions(desktops.values(currentDesktop));
        m_menu->addActions(desktops.values(-1));
    } else {
        int numDesktops = KWindowSystem::numberOfDesktops();
        if (m_mode == AllFlat) {
            for (int i = 1; i <= numDesktops; ++i) {
                if (desktops.contains(i)) {
                    QString name = KWindowSystem::desktopName(i);
                    name = QString("%1: %2").arg(i).arg(name);
                    m_menu->addTitle(name);
                    m_menu->addActions(desktops.values(i));
                }
            }
            if (desktops.contains(-1)) {
                m_menu->addTitle(i18n("All Desktops"));
                m_menu->addActions(desktops.values(-1));
            }
        } else { //submenus
            for (int i = 1; i <= numDesktops; ++i) {
                if (desktops.contains(i)) {
                        QString name = KWindowSystem::desktopName(i);
                        name = QString("%1: %2").arg(i).arg(name);
                        KMenu *subMenu = new KMenu(name, m_menu);
                        subMenu->addActions(desktops.values(i));
                        m_menu->addMenu(subMenu);
                }
            }
            if (desktops.contains(-1)) {
                KMenu *subMenu = new KMenu(i18n("All Desktops"), m_menu);
                subMenu->addActions(desktops.values(-1));
                m_menu->addMenu(subMenu);
            }
        }
    }

    m_menu->adjustSize();
}
bool QIcnsIconEnginePrivate::loadIcnsData(QIODevice *dev, QIcon::Mode mode,
                                          QIcon::State state)
{
	QByteArray id, data;
	qint32 length;

	QDataStream ds(dev);
	ds.setByteOrder(QDataStream::BigEndian);

	id = dev->read(4);
	if (!id.startsWith("icns"))
		return false;

	ds >> length;
	if (dev->isSequential() && length != dev->size())
		return false;

	while (! dev->atEnd()) {
		int npixels = 0;

		id = dev->read(4);
		ds >> length;
		data = dev->read(length - 8);

		if (id == "ic09")        /* 512x512 JPEG2000 */
			npixels = 512;
		else if (id == "ic08")   /* 256x256 JPEG2000 */
			npixels = 256;
		else if (id == "it32")   /* 128x128 24-bit RGB */
			npixels = 128;
		else if (id == "ih32")   /* 48x48 24-bit RGB */
			npixels = 48;
		else if (id == "il32")   /* 32x32 24-bit RGB */
			npixels = 32;
		else if (id == "is32")   /* 16x16 24-bit RGB */
			npixels = 16;
		else
			continue;

		/*
		 * JPEG2000-based icons.
		 */
		if (npixels > 128) {
			QList<QByteArray> formats = QImageReader::supportedImageFormats();
			if (!formats.contains(QByteArray("jp2")))
				continue;
		} else {
			/*
			 * Apparently, the 128x128 image can have 4 extra bytes prepended
			 * to them. GDK-pixbuf does this, too.
			 */
			if (npixels == 128) {
				if (data.startsWith("\0\0\0\0")) {
					data.remove(0, 4);
				}
			}

			QByteArray rgb = decompressIconData(data, npixels);

			/*
			 * Determine if there is an alpha channel for this image in
			 * the stream.
			 */
			id = dev->peek(4);
			if (id == "t8mk" || id == "h8mk" || id == "l8mk" || id == "s8mk") {
				id = dev->read(4);
				ds >> length;
				data = dev->read(length - 8);

				int length = data.length();

				if (length != npixels*npixels) {
					qWarning("QIcnsIconEnginePrivate::loadIcnsData: mask"
					         " size mismatch");
					continue;
				}

				for (int i = 0; i < length; i++)
					rgb[i*4 + 3] = data[i];
			}

			imageBuffers.insert(hashKey(mode, state, QSize(npixels, npixels)), rgb);
			iconSizes.insert(hashKey(mode, state), QSize(npixels, npixels));
		}
	}
QString timetrackerstorage::buildTaskView( const KTimeTracker::KTTCalendar::Ptr &calendar,
                                           TaskView *view )
// makes *view contain the tasks out of *rc.
{
    kDebug(5970) << "Entering function";
    QString err;
    KCalCore::Todo::List todoList;
    KCalCore::Todo::List::ConstIterator todo;
    QMultiHash< QString, Task* > map;
    QVector<QString> runningTasks;
    QVector<QDateTime> startTimes;

    // remember tasks that are running and their start times
    QTreeWidgetItemIterator it( view );
    while ( *it )
    {
        Task *task = static_cast< Task* >( *it );
        if ( task->isRunning() )
        {
            runningTasks.append( task->uid() );
            startTimes.append( task->startTime() );
        }
        ++it;
    }

    view->clear();
    todoList = calendar->rawTodos();
    for ( todo = todoList.constBegin(); todo != todoList.constEnd(); ++todo )
    {
        Task* task = new Task(*todo, view);
        task->setWhatsThis(0,i18n("The task name is what you call the task, it can be chosen freely."));
        task->setWhatsThis(1,i18n("The session time is the time since you last chose \"start new session.\""));
        map.insert( (*todo)->uid(), task );
        view->setRootIsDecorated(true);
        task->setPixmapProgress();
    }

    // 1.1. Load each task under it's parent task.
    for( todo = todoList.constBegin(); todo != todoList.constEnd(); ++todo )
    {
        Task* task = map.value( (*todo)->uid() );
        // No relatedTo incident just means this is a top-level task.
        if ( !(*todo)->relatedTo().isEmpty() )
        {
            Task* newParent = map.value( (*todo)->relatedTo() );
            // Complete the loading but return a message
            if ( !newParent )
                err = i18n("Error loading \"%1\": could not find parent (uid=%2)",
                    task->name(),
                    (*todo)->relatedTo());
            else task->move( newParent );
        }
    }

    view->clearActiveTasks();
    // restart tasks that have been running with their start times
    for ( int i=0; i<view->count(); i++)
    {
        for ( int n = 0; n < runningTasks.count(); ++n )
        {
            if ( runningTasks[n] == view->itemAt(i)->uid() )
            {
                view->startTimerFor( view->itemAt(i), startTimes[n] );
            }
        }
    }

    view->refresh();
    return err;
}
Beispiel #23
0
QString VideoMetaDataUtil::GetArtPath(const QString &pathname,
                                      const QString &type)
{
    QString basename = pathname.section('/', -1);

    if (basename == pathname)
    {
        LOG(VB_GENERAL, LOG_WARNING, LOC +
                "Programmer Error: Cannot determine art path\n\t\t\t"
                "until the ProgramInfo pathname has been fully resolved.");
        return QString();
    }

    art_path_map_lock.lockForRead();
    ArtList ret(art_path_map.values(basename));
    art_path_map_lock.unlock();
    for (ArtList::const_iterator i = ret.begin();
            i != ret.end(); ++i)
    {
        if ((*i).first == type)
            return (*i).second;
    }

    QString fn = basename;
    fn.prepend("%");

    QString dbcolumn;
    if (type == "Coverart")
        dbcolumn = "coverfile";
    else if (type == "Fanart")
        dbcolumn = "fanart";
    else if (type == "Banners")
        dbcolumn = "banner";
    else if (type == "Screenshots")
        dbcolumn = "screenshot";

    QString querystr = QString("SELECT %1 "
        "FROM videometadata WHERE filename "
        "LIKE :FILENAME").arg(dbcolumn);

    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare(querystr);
    query.bindValue(":FILENAME", fn);

    QString artpath;
    if (query.exec() && query.next())
        artpath = query.value(0).toString();

    if (!artpath.startsWith('/') && pathname.startsWith("myth://"))
    {
        QString workURL = pathname;
        QUrl baseURL(workURL);
        baseURL.setUserName(type);
        QString finalURL =
            baseURL.toString(QUrl::RemovePath) + '/' + artpath;
        artpath = finalURL;
    }

    ArtPair ins(type, artpath);
    art_path_map_lock.lockForWrite();
    art_path_map.insert(basename, ins);
    art_path_map_lock.unlock();

    return artpath;
}
Beispiel #24
0
static QMultiHash<QByteArray, QPair<int, float> > createActionUnitNameMap() {
    QMultiHash<QByteArray, QPair<QByteArray, float> > blendshapeMap;
    blendshapeMap.insert("JawFwd", QPair<QByteArray, float>("au_jaw_z_push", 1.0f));
    blendshapeMap.insert("JawLeft", QPair<QByteArray, float>("au_jaw_x_push", 1.0f));
    blendshapeMap.insert("JawOpen", QPair<QByteArray, float>("au_jaw_drop", 1.0f));
    blendshapeMap.insert("LipsLowerDown", QPair<QByteArray, float>("au_lower_lip_drop", 1.0f));
    blendshapeMap.insert("LipsUpperOpen", QPair<QByteArray, float>("au_upper_lip_raiser", 1.0f));
    blendshapeMap.insert("LipsStretch_R", QPair<QByteArray, float>("au_lip_stretcher_left", 0.5f));
    blendshapeMap.insert("MouthSmile_L", QPair<QByteArray, float>("au_lip_corner_depressor", -1.0f));
    blendshapeMap.insert("MouthSmile_R", QPair<QByteArray, float>("au_lip_corner_depressor", -1.0f));
    blendshapeMap.insert("BrowsU_R", QPair<QByteArray, float>("au_left_outer_brow_raiser", 1.0f));
    blendshapeMap.insert("BrowsU_C", QPair<QByteArray, float>("au_left_inner_brow_raiser", 1.0f));
    blendshapeMap.insert("BrowsD_R", QPair<QByteArray, float>("au_left_brow_lowerer", 1.0f));
    blendshapeMap.insert("EyeBlink_L", QPair<QByteArray, float>("au_leye_closed", 1.0f));
    blendshapeMap.insert("EyeBlink_R", QPair<QByteArray, float>("au_reye_closed", 1.0f));
    blendshapeMap.insert("EyeOpen_L", QPair<QByteArray, float>("au_upper_lid_raiser", 1.0f));
    blendshapeMap.insert("EyeOpen_R", QPair<QByteArray, float>("au_upper_lid_raiser", 1.0f));
    blendshapeMap.insert("LipLowerOpen", QPair<QByteArray, float>("au_lower_lip_x_push", 1.0f));
    blendshapeMap.insert("LipsStretch_L", QPair<QByteArray, float>("au_lip_stretcher_right", 0.5f));
    blendshapeMap.insert("BrowsU_L", QPair<QByteArray, float>("au_right_outer_brow_raiser", 1.0f));
    blendshapeMap.insert("BrowsU_C", QPair<QByteArray, float>("au_right_inner_brow_raiser", 1.0f));
    blendshapeMap.insert("BrowsD_L", QPair<QByteArray, float>("au_right_brow_lowerer", 1.0f));
    
    QMultiHash<QByteArray, QPair<int, float> > actionUnitNameMap;
    for (int i = 0;; i++) {
        QByteArray blendshape = FACESHIFT_BLENDSHAPES[i];
        if (blendshape.isEmpty()) {
            break;
        }
        if (blendshape == "EyeBlink_L") {
            leftEyeBlinkIndex = i;
        
        } else if (blendshape == "EyeBlink_R") {
            rightEyeBlinkIndex = i;   
        }
        for (QMultiHash<QByteArray, QPair<QByteArray, float> >::const_iterator it = blendshapeMap.constFind(blendshape);
                it != blendshapeMap.constEnd() && it.key() == blendshape; it++) {
            actionUnitNameMap.insert(it.value().first, QPair<int, float>(i, it.value().second));
        }
    }
    
    return actionUnitNameMap;
}
QString timetrackerstorage::load(TaskView* view, const QString &fileName)
// loads data from filename into view. If no filename is given, filename from preferences is used.
// filename might be of use if this program is run as embedded konqueror plugin.
{
    Q_UNUSED(fileName); // TODO: receive changes from akonadi
    kDebug(5970) << "Entering function";
    QString err;
    KEMailSettings settings;

    // If file doesn't exist, create a blank one to avoid ResourceLocal load
    // error.  We make it user and group read/write, others read.  This is
    // masked by the users umask.  (See man creat)
    if ( d->mCalendar )
        closeStorage();
    // Create local file resource and add to resources
    d->mICalFile = "";
    d->mCalendar = KTTCalendar::createInstance();

    QObject::connect( d->mCalendar.data(), SIGNAL(calendarChanged()),
                      view, SLOT(iCalFileModified()) );
    d->mCalendar->setTimeSpec( KSystemTimeZones::local() );
    d->mCalendar->reload();

    // Claim ownership of iCalendar file if no one else has.
    KCalCore::Person::Ptr owner = d->mCalendar->owner();
    if ( owner && owner->isEmpty() )
    {
        // TODO
        d->mCalendar->setOwner( KCalCore::Person::Ptr(
           new KCalCore::Person( settings.getSetting( KEMailSettings::RealName ),
                                 settings.getSetting( KEMailSettings::EmailAddress ) ) ) );
    }

    // TODO
    // Build task view from iCal data
    if (!err.isEmpty())
    {
        KCalCore::Todo::List todoList;
        KCalCore::Todo::List::ConstIterator todo;
        QMultiHash< QString, Task* > map;

        // Build dictionary to look up Task object from Todo uid.  Each task is a
        // QListViewItem, and is initially added with the view as the parent.
        todoList = d->mCalendar->rawTodos();
        kDebug(5970) << "timetrackerstorage::load"
            << "rawTodo count (includes completed todos) ="
            << todoList.count();
        for (todo = todoList.constBegin(); todo != todoList.constEnd(); ++todo)
        {
            Task* task = new Task(*todo, view);
            map.insert( (*todo)->uid(), task );
            view->setRootIsDecorated(true);
            task->setPixmapProgress();
        }

        // Load each task under it's parent task.
        for (todo = todoList.constBegin(); todo != todoList.constEnd(); ++todo)
        {
            Task* task = map.value( (*todo)->uid() );
            // No relatedTo incident just means this is a top-level task.
            if ( !(*todo)->relatedTo().isEmpty() )
            {
                Task *newParent = map.value( (*todo)->relatedTo() );

                // Complete the loading but return a message
                if ( !newParent )
                    err = i18n("Error loading \"%1\": could not find parent (uid=%2)",
                        task->name(), (*todo)->relatedTo()  );

                if (!err.isEmpty()) task->move( newParent );
            }
        }

        kDebug(5970) << "timetrackerstorage::load - loaded" << view->count()
            << "tasks from" << d->mICalFile;
    }

    if ( view ) buildTaskView(d->mCalendar->weakPointer(), view);

    this->save(view); // FIXME ?

    return err;
}
bool QgsGeometryAnalyzer::eventLayer( QgsVectorLayer* lineLayer, QgsVectorLayer* eventLayer, int lineField, int eventField, QgsFeatureIds &unlocatedFeatureIds, const QString& outputLayer,
                                      const QString& outputFormat, int locationField1, int locationField2, int offsetField, double offsetScale,
                                      bool forceSingleGeometry, QgsVectorDataProvider* memoryProvider, QProgressDialog* p )
{
  if ( !lineLayer || !eventLayer || !lineLayer->isValid() || !eventLayer->isValid() )
  {
    return false;
  }

  //create line field / id map for line layer
  QMultiHash< QString, QgsFeature > lineLayerIdMap; //1:n possible (e.g. several linear reference geometries for one feature in the event layer)
  QgsFeatureIterator fit = lineLayer->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QgsAttributeList() << lineField ) );
  QgsFeature fet;
  while ( fit.nextFeature( fet ) )
  {
    lineLayerIdMap.insert( fet.attribute( lineField ).toString(), fet );
  }

  //create output datasource or attributes in memory provider
  QgsVectorFileWriter* fileWriter = nullptr;
  QgsFeatureList memoryProviderFeatures;
  if ( !memoryProvider )
  {
    QgsWkbTypes::Type memoryProviderType = QgsWkbTypes::MultiLineString;
    if ( locationField2 == -1 )
    {
      memoryProviderType = forceSingleGeometry ? QgsWkbTypes::Point : QgsWkbTypes::MultiPoint;
    }
    else
    {
      memoryProviderType = forceSingleGeometry ? QgsWkbTypes::LineString : QgsWkbTypes::MultiLineString;
    }
    fileWriter = new QgsVectorFileWriter( outputLayer,
                                          eventLayer->dataProvider()->encoding(),
                                          eventLayer->fields(),
                                          memoryProviderType,
                                          lineLayer->crs(),
                                          outputFormat );
  }
  else
  {
    memoryProvider->addAttributes( eventLayer->fields().toList() );
  }

  //iterate over eventLayer and write new features to output file or layer
  fit = eventLayer->getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ) );
  QgsGeometry lrsGeom;
  double measure1, measure2 = 0.0;

  int nEventFeatures = eventLayer->featureCount();
  int featureCounter = 0;
  int nOutputFeatures = 0; //number of output features for the current event feature
  if ( p )
  {
    p->setWindowModality( Qt::WindowModal );
    p->setMinimum( 0 );
    p->setMaximum( nEventFeatures );
    p->show();
  }

  while ( fit.nextFeature( fet ) )
  {
    nOutputFeatures = 0;

    //update progress dialog
    if ( p )
    {
      if ( p->wasCanceled() )
      {
        break;
      }
      p->setValue( featureCounter );
      ++featureCounter;
    }

    measure1 = fet.attribute( locationField1 ).toDouble();
    if ( locationField2 != -1 )
    {
      measure2 = fet.attribute( locationField2 ).toDouble();
      if ( qgsDoubleNear(( measure2 - measure1 ), 0.0 ) )
      {
        continue;
      }
    }

    QList<QgsFeature> featureIdList = lineLayerIdMap.values( fet.attribute( eventField ).toString() );
    QList<QgsFeature>::iterator featureIdIt = featureIdList.begin();
    for ( ; featureIdIt != featureIdList.end(); ++featureIdIt )
    {
      if ( locationField2 == -1 )
      {
        lrsGeom = locateAlongMeasure( measure1, featureIdIt->geometry() );
      }
      else
      {
        lrsGeom = locateBetweenMeasures( measure1, measure2, featureIdIt->geometry() );
      }

      if ( !lrsGeom.isEmpty() )
      {
        ++nOutputFeatures;
        addEventLayerFeature( fet, lrsGeom, featureIdIt->geometry(), fileWriter, memoryProviderFeatures, offsetField, offsetScale, forceSingleGeometry );
      }
    }
    if ( nOutputFeatures < 1 )
    {
      unlocatedFeatureIds.insert( fet.id() );
    }
  }

  if ( p )
  {
    p->setValue( nEventFeatures );
  }

  if ( memoryProvider )
  {
    memoryProvider->addFeatures( memoryProviderFeatures );
  }
  delete fileWriter;
  return true;
}
//------------------------------------------------------------------------------
//	FUNCTION: invalidate [ public ]
//------------------------------------------------------------------------------
void csvFilterProxyModel::invalidate()
{
	m_filterMapping.clear();

	if (!m_filterModel)
		return;

	// Make a hash of all the groups in the filter
	QMultiHash<size_t, int> groups;
	std::set<int> unusedFilterColumns;

	for (int filterCol = 0; filterCol < m_filterModel->columnCount(); ++filterCol)
	{
		unusedFilterColumns.insert(filterCol);

		size_t group = m_filterModel->data(m_filterModel->index(1, filterCol)).toULongLong();
		groups.insert(group, filterCol);
	}

	// filter in column order, but each group aside from 0 should be filtered using logical 'and' with all group members
	for (auto itr = unusedFilterColumns.begin(); itr != unusedFilterColumns.end(); ++itr)
	{
		int							filterCol = *itr;
		QString						columnName = m_filterModel->headerData(filterCol, Qt::Horizontal, Qt::DisplayRole).toString();
		size_t						group = m_filterModel->data(m_filterModel->index(1, filterCol)).toULongLong();
		size_t						numInGroup = (group == 0 ? 1 : groups.count(group));
		QList<QString>				filterColumnNames;

		// make a list of filter values, i.e. all the things in the filter column
		auto filterColumns = groups.values(group);
		qSort(filterColumns);

		if (group != 0)
		{
			// for each filter in the group
			for (auto groupColumnItr = filterColumns.begin(); groupColumnItr != filterColumns.end(); ++groupColumnItr)
			{
				int column = *groupColumnItr;

				filterColumnNames.push_back(m_filterModel->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString());

				// erase other columns that are part of this group so we don't check them twice
				if (groupColumnItr != filterColumns.begin()) 
					unusedFilterColumns.erase(column);				
			}
		}
		else
		{
			filterColumnNames.push_back(columnName);
			filterColumns.clear();
			filterColumns.push_back(filterCol);
		}

		// find the corresponding column in this spreadsheet
		QList<int> masterColumns;
		for (int i = 0; i < filterColumnNames.size(); ++i)
		{
			for (int masterColumn = 0; masterColumn < sourceModel()->columnCount(); masterColumn++)
			{
				QString masterColunName = sourceModel()->headerData(masterColumn, Qt::Horizontal, Qt::DisplayRole).toString();
				if (masterColunName == filterColumnNames.at(i))
				{
					masterColumns.push_back(masterColumn);
					break;
				}
			}
		}

		// add the mappings to the mapping table
		QList<QPair<int, int>> filterMapping;
		for (int i = 0; i < filterColumns.size(); ++i)
		{
			filterMapping.push_back(QPair<int, int>(filterColumns.at(i), masterColumns.at(i)));
		}
		m_filterMapping.push_back(filterMapping);
	}

	QSortFilterProxyModel::invalidate();
}
Beispiel #28
0
bool QxtRPCServiceIntrospector::addSignal(QObject* obj, const char* signature, const QString& rpcFunction)
{
    const QMetaObject* meta = obj->metaObject();
    QByteArray norm = QxtMetaObject::methodSignature(signature);
    QxtRPCServicePrivate::MetaMethodDef signal = qMakePair(meta, norm);
    int sigID, methodID;

    if(!signalIDs.count(signal)) {
        // This signal hasn't been encountered before, so read the metaobject and cache the results.
        methodID = meta->indexOfMethod(norm.constData());
        if(methodID < 0) {
            // indexOfMethod() returns -1 if the signal was not found, so report a warning and return an error.
            qWarning() << "QxtRPCService::attachSignal: " << obj << "::" << signature << " does not exist";
            return false;
        }

        // Look up the signal's parameter list, ensure each parameter is queueable, and cache the type IDs.
        QList<QByteArray> types = meta->method(methodID).parameterTypes();
        QList<int> typeIDs;
        int ct = types.count();
        for(int i = 0; i < ct; i++) {
            int typeID = QMetaType::type(types.value(i).constData());
            if(typeID <= 0) {
                qWarning() << "QxtRPCService::attachSignal: cannot queue arguments of type " << types.value(i);
                return false;
            }
            typeIDs.append(typeID);
        }

        // Cache the looked-up parameter list, associate the list with the signal definition, and cache the signal's
        // QMetaObject method index.
        int nextSignalID = signalParameters.count();
        signalParameters.append(typeIDs);
        signalIDs[signal] = nextSignalID;
        methodIDs[signal] = methodID;

        // And finally, set the signal ID for the connect call below.
        sigID = nextSignalID;
    } else {
        // Use the cached values from before.
        sigID = signalIDs.value(signal);
        methodID = methodIDs.value(signal);
    }

    // Use an undocumented function from QMetaObject to connect the incoming signal to the next dynamic slot.
    bool success = QMetaObject::connect(obj, methodID, this, nextSlotID);
    if(!success) {
        // Presumedly connect() will output its own warning.
        // The remaining setup is unnecessary if the connection failed.
        return false; 
    }

    // Associate the signal and source object with the dynamic slot.
    signalToId.insert(qMakePair(obj, norm), nextSlotID);

    // Associate the new dynamic slot with an RPC message, or use the signal signature as the default message.
    idToRpc.insert(nextSlotID, rpcFunction.isEmpty() ? norm : rpcFunction);

    // Associate the new dynamic slot with the parameter list definition.
    idToParams[nextSlotID] = sigID;

    do {
        // This variable is perfectly allowed to wrap around; it's terribly unlikely to have four billion
        // concurrent connections but a particularly long-lived object with a lot of disconnects and
        // reconnects might survive to see a wraparound.
        nextSlotID++;
        // But of course we need to make sure the next ID isn't in use.
    } while(nextSlotID < quint32(QObject::staticMetaObject.methodCount()) || idToParams.contains(nextSlotID));

    return true;
}
Beispiel #29
0
void tst_QVCard30Writer::testEncodeParameters()
{
    QByteArray encodedParameters;
    QBuffer buffer(&encodedParameters);
    mWriter->setDevice(&buffer);
    buffer.open(QIODevice::WriteOnly);

    QString typeParameterName(QString::fromAscii("TYPE"));
    QString encodingParameterName(QString::fromAscii("ENCODING"));

    // No parameters
    QMultiHash<QString,QString> parameters;
    mWriter->encodeParameters(parameters);
    QCOMPARE(encodedParameters, QByteArray(""));

    // One TYPE parameter
    parameters.insert(typeParameterName,QString::fromAscii("HOME"));
    mWriter->writeCrlf(); // so it doesn't start folding
    buffer.close();
    encodedParameters.clear();
    buffer.open(QIODevice::WriteOnly);
    mWriter->encodeParameters(parameters);
    QCOMPARE(encodedParameters, QByteArray(";TYPE=HOME"));

    // Two TYPE parameters
    parameters.insert(typeParameterName,QString::fromAscii("VOICE"));
    mWriter->writeCrlf(); // so it doesn't start folding
    buffer.close();
    encodedParameters.clear();
    buffer.open(QIODevice::WriteOnly);
    mWriter->encodeParameters(parameters);
    QCOMPARE(encodedParameters, QByteArray(";TYPE=VOICE,HOME"));

    // One ENCODING parameter
    parameters.clear();
    parameters.insert(encodingParameterName,QString::fromAscii("8BIT"));
    mWriter->writeCrlf(); // so it doesn't start folding
    buffer.close();
    encodedParameters.clear();
    buffer.open(QIODevice::WriteOnly);
    mWriter->encodeParameters(parameters);
    QCOMPARE(encodedParameters, QByteArray(";ENCODING=8BIT"));

    // Two parameters
    parameters.insert(QString::fromAscii("X-PARAM"),QString::fromAscii("VALUE"));
    mWriter->writeCrlf(); // so it doesn't start folding
    buffer.close();
    encodedParameters.clear();
    buffer.open(QIODevice::WriteOnly);
    mWriter->encodeParameters(parameters);
    QCOMPARE(encodedParameters, QByteArray(";X-PARAM=VALUE;ENCODING=8BIT"));

    // Parameter with characters that require backslash escaping
    parameters.clear();
    parameters.insert(QString::fromAscii("X-P;ARAM"),QString::fromAscii("VA,LUE"));
    mWriter->writeCrlf(); // so it doesn't start folding
    buffer.close();
    encodedParameters.clear();
    buffer.open(QIODevice::WriteOnly);
    mWriter->encodeParameters(parameters);
    QCOMPARE(encodedParameters, QByteArray(";X-P\\;ARAM=VA\\,LUE"));
}
Beispiel #30
0
void SwitchWindow::makeMenu()
{
    qDeleteAll(m_actions);
    m_actions.clear();

    if (m_tasksModel->rowCount() == 0) {
        return;
    }

    QMultiHash<int, QAction*> desktops;

    //make all the window actions
    for (int i = 0; i < m_tasksModel->rowCount(); ++i) {
        if (m_tasksModel->data(m_tasksModel->index(i, 0), LegacyTaskManager::TasksModel::IsStartup).toBool()) {
            qDebug() << "skipped fake task";
            continue;
        }

        QString name = m_tasksModel->data(m_tasksModel->index(i, 0), Qt::DisplayRole).toString();

        if (name.isEmpty()) {
            continue;
        }

        QAction *action = new QAction(name, this);
        action->setIcon(m_tasksModel->data(m_tasksModel->index(i, 0), Qt::DecorationRole).value<QIcon>());
        action->setData(m_tasksModel->data(m_tasksModel->index(i, 0), LegacyTaskManager::TasksModel::Id).toString());
        desktops.insert(m_tasksModel->data(m_tasksModel->index(i, 0), LegacyTaskManager::TasksModel::Desktop).toInt(), action);
        connect(action, &QAction::triggered, [=]() {
            switchTo(action);
        });
    }

    //sort into menu
    if (m_mode == CurrentDesktop) {
        int currentDesktop = KWindowSystem::currentDesktop();

        QAction *a = new QAction(i18nc("plasma_containmentactions_switchwindow", "Windows"), this);
        a->setSeparator(true);
        m_actions << a;
        m_actions << desktops.values(currentDesktop);
        m_actions << desktops.values(-1);

    } else {
        int numDesktops = KWindowSystem::numberOfDesktops();
        if (m_mode == AllFlat) {
            for (int i = 1; i <= numDesktops; ++i) {
                if (desktops.contains(i)) {
                    QString name = KWindowSystem::desktopName(i);
                    name = QStringLiteral("%1: %2").arg(i).arg(name);
                    QAction *a = new QAction(name, this);
                    a->setSeparator(true);
                    m_actions << a;
                    m_actions << desktops.values(i);
                }
            }
            if (desktops.contains(-1)) {
                QAction *a = new QAction(i18nc("plasma_containmentactions_switchwindow", "All Desktops"), this);
                a->setSeparator(true);
                m_actions << a;
                m_actions << desktops.values(-1);
            }

        } else { //submenus
            for (int i = 1; i <= numDesktops; ++i) {
                if (desktops.contains(i)) {
                    QString name = KWindowSystem::desktopName(i);
                    name = QStringLiteral("%1: %2").arg(i).arg(name);
                    QMenu *subMenu = new QMenu(name);
                    subMenu->addActions(desktops.values(i));

                    QAction *a = new QAction(name, this);
                    a->setMenu(subMenu);
                    m_actions << a;
                }
            }
            if (desktops.contains(-1)) {
                QMenu *subMenu = new QMenu(i18nc("plasma_containmentactions_switchwindow", "All Desktops"));
                subMenu->addActions(desktops.values(-1));
                QAction *a = new QAction(i18nc("plasma_containmentactions_switchwindow", "All Desktops"), this);
                a->setMenu(subMenu);
                m_actions << a;
            }
        }
    }
}