void TransitionTerrain::addTransitionOnMap(Tiled::Map &tiledMap)
{
    const unsigned int w=tiledMap.width();
    const unsigned int h=tiledMap.height();

    //list the layer name to parse
    QHash<QString,LoadMap::Terrain> transition;
    QStringList transitionList;
    for(int height=0;height<5;height++)
        for(int moisure=0;moisure<6;moisure++)
        {
            LoadMap::Terrain &terrain=LoadMap::terrainList[height][moisure];
            if(!terrain.tmp_layerString.isEmpty())
            {
                if(!transitionList.contains(terrain.terrainName))
                {
                    transition[terrain.terrainName]=terrain;
                    transitionList << terrain.terrainName;
                }
            }
        }

    {
        Tiled::TileLayer * transitionLayerMask=LoadMap::searchTileLayerByName(tiledMap,"OnGrass");
        Tiled::TileLayer * const colisionLayerMask=LoadMap::searchTileLayerByName(tiledMap,"Collisions");
        unsigned int index=0;
        while(index<(unsigned int)transitionList.size())
        {
            const LoadMap::Terrain &terrain=transition.value(transitionList.at(index));
            Tiled::TileLayer * terrainLayer=terrain.tileLayer;
            Tiled::TileLayer * transitionLayer=NULL;
            uint16_t XORop;
            if(terrain.outsideBorder)
            {
                transitionLayer=terrainLayer;
                XORop=0x01ff;
            }
            else
            {
                const unsigned int index=LoadMap::searchTileIndexByName(tiledMap,terrain.tmp_layerString);
                Tiled::Layer * rawLayer=tiledMap.layerAt(index+1);
                if(!rawLayer->isTileLayer())
                {
                    std::cerr << "Next layer after " << terrain.tmp_layerString.toStdString() << "is not tile layer (abort)" << std::endl;
                    abort();
                }
                transitionLayer=static_cast<Tiled::TileLayer *>(rawLayer);
                transitionLayerMask=transitionLayer;
                XORop=0x0000;
            }
            unsigned int y=0;
            while(y<h)
            {
                unsigned int x=0;
                while(x<w)
                {
                    const bool innerBool=!XORop && (terrainLayer->cellAt(x,y).tile==terrain.tile);
                    const unsigned int &bitMask=x+y*w;
                    const bool outerBool=XORop && terrainLayer->cellAt(x,y).tile!=terrain.tile && !(MapBrush::mapMask[bitMask/8] & (1<<(7-bitMask%8)));
                    if(
                            //inner
                            innerBool ||
                            //outer
                            outerBool
                            )
                    {
                        //check the near tile and determine what transition use
                        const uint16_t to_type_match=layerMask(terrainLayer,x,y,terrain.tile,XORop);
                        if(to_type_match>512)
                            abort();

                        if(to_type_match!=0 && to_type_match!=16)
                        {
                            unsigned int indexTile=0;
                            if(XORop)
                            {
                                const uint16_t to_type_match_collision=layerMask(colisionLayerMask,x,y,NULL,false);
                                const bool onGrass=transitionLayerMask->cellAt(x,y).tile!=NULL;
                                bool forceDisplay=false;
                                //outer border
                                if(to_type_match&2)
                                {
                                    if(to_type_match&8)
                                    {
                                        indexTile=8;
                                    }
                                    else if(to_type_match&32)
                                    {
                                        indexTile=9;
                                    }
                                    else
                                    {
                                        indexTile=5;
                                        if(to_type_match_collision&8 && to_type_match_collision&32)
                                            forceDisplay=true;
                                    }
                                }
                                else if(to_type_match&128)
                                {
                                    if(to_type_match&8)
                                    {
                                        indexTile=11;
                                    }
                                    else if(to_type_match&32)
                                    {
                                        indexTile=10;
                                    }
                                    else
                                    {
                                        indexTile=1;
                                        if(to_type_match_collision&8 && to_type_match_collision&32)
                                            forceDisplay=true;
                                    }
                                }
                                else if(to_type_match&8)
                                {
                                    indexTile=3;
                                    if(to_type_match_collision&2 && to_type_match_collision&128)
                                        forceDisplay=true;
                                }
                                else if(to_type_match&32)
                                {
                                    indexTile=7;
                                    if(to_type_match_collision&2 && to_type_match_collision&128)
                                        forceDisplay=true;
                                }
                                else if(to_type_match&256)
                                {
                                    indexTile=0;
                                    if(!(to_type_match_collision&256))
                                    {
                                        if(to_type_match_collision&32 && to_type_match_collision&128)
                                            forceDisplay=true;
                                        if(to_type_match_collision&8 && to_type_match_collision&32)
                                            forceDisplay=true;
                                        if(to_type_match_collision&2 && to_type_match_collision&128)
                                            forceDisplay=true;
                                    }
                                }
                                else if(to_type_match&64)
                                {
                                    indexTile=2;
                                    if(!(to_type_match_collision&64))
                                    {
                                        if(to_type_match_collision&8 && to_type_match_collision&128)
                                            forceDisplay=true;
                                        if(to_type_match_collision&8 && to_type_match_collision&32)
                                            forceDisplay=true;
                                        if(to_type_match_collision&2 && to_type_match_collision&128)
                                            forceDisplay=true;
                                    }
                                }
                                else if(to_type_match&1)
                                {
                                    indexTile=4;
                                    if(!(to_type_match_collision&1))
                                    {
                                        if(to_type_match_collision&2 && to_type_match_collision&8)
                                            forceDisplay=true;
                                        if(to_type_match_collision&8 && to_type_match_collision&32)
                                            forceDisplay=true;
                                        if(to_type_match_collision&2 && to_type_match_collision&128)
                                            forceDisplay=true;
                                    }
                                }
                                else if(to_type_match&4)
                                {
                                    indexTile=6;
                                    if(!(to_type_match_collision&4))
                                    {
                                        if(to_type_match_collision&2 && to_type_match_collision&32)
                                            forceDisplay=true;
                                        if(to_type_match_collision&8 && to_type_match_collision&32)
                                            forceDisplay=true;
                                        if(to_type_match_collision&2 && to_type_match_collision&128)
                                            forceDisplay=true;
                                    }
                                }

                                if(!onGrass || forceDisplay)
                                {
                                    Tiled::Cell cell;
                                    cell.tile=terrain.transition_tile.at(indexTile);
                                    cell.flippedHorizontally=false;
                                    cell.flippedVertically=false;
                                    cell.flippedAntiDiagonally=false;
                                    transitionLayer->setCell(x,y,cell);
                                }
                            }
                            else
                            {
                                //inner border
                                if(to_type_match&2)
                                {
                                    if(to_type_match&8)
                                        indexTile=0;
                                    else if(to_type_match&32)
                                        indexTile=2;
                                    else
                                        indexTile=1;
                                }
                                else if(to_type_match&128)
                                {
                                    if(to_type_match&8)
                                        indexTile=6;
                                    else if(to_type_match&32)
                                        indexTile=4;
                                    else
                                        indexTile=5;
                                }
                                else if(to_type_match&8)
                                    indexTile=7;
                                else if(to_type_match&32)
                                    indexTile=3;
                                else if(to_type_match&256)
                                    indexTile=8;
                                else if(to_type_match&64)
                                    indexTile=9;
                                else if(to_type_match&1)
                                    indexTile=10;
                                else if(to_type_match&4)
                                    indexTile=11;

                                Tiled::Cell cell;
                                cell.tile=terrain.transition_tile.at(indexTile);
                                cell.flippedHorizontally=false;
                                cell.flippedVertically=false;
                                cell.flippedAntiDiagonally=false;
                                transitionLayer->setCell(x,y,cell);
                            }
                        }
                    }
                    x++;
                }
                y++;
            }
            index++;
        }
    }
}
示例#2
0
// Upload notes that belong to me
qint32 SyncRunner::uploadPersonalNotes() {
    QLOG_TRACE_IN();
    qint32 usn;
    qint32 maxUsn = 0;
    NotebookTable notebookTable(db);
    LinkedNotebookTable linkedNotebookTable(db);
    NoteTable noteTable(db);
    QList<qint32> lids, validLids, deletedLids, movedLids;
    QStringList deleteQueueGuids;
    noteTable.getAllDirty(lids);

    // Get all of the notes that were deleted, and then removed from the trash
    noteTable.getAllDeleteQueue(deleteQueueGuids);


    // Get a list of all notes that are both dirty and in an account we own and isn't deleted
    for (int i = 0; i < lids.size(); i++) {
        qint32 notebookLid = noteTable.getNotebookLid(lids[i]);
        if (!linkedNotebookTable.exists(notebookLid)) {
            if (!notebookTable.isLocal(notebookLid)) {
                if (noteTable.isDeleted(lids[i]))
                    deletedLids.append(lids[i]);
                else
                    validLids.append(lids[i]);
            } else {
                // We have a note that is local.  Check if it was once
                // synchronized.  If so, it was moved to a local notebook
                // and now needs to be deleted on the remote end
                Note n;
                noteTable.get(n, lids[i], false, false);
                if (n.updateSequenceNum.isSet() && n.updateSequenceNum > 0) {
                    movedLids.append(lids[i]);
                }
            }
        }
    }

    // Start deleting notes
    for (int i = 0; i < deletedLids.size(); i++) {
        QString guid = noteTable.getGuid(deletedLids[i]);
        noteTable.setDirty(lids[i], false);
        usn = comm->deleteNote(guid);
        if (usn > maxUsn) {
            maxUsn = usn;
            noteTable.setUpdateSequenceNumber(deletedLids[i], usn);
            noteTable.setDirty(deletedLids[i], false);
            if (!finalSync)
                emit(noteSynchronized(deletedLids[i], false));
        }
    }

    // Start handling notes moved to a local notebook.  What
    // we do is to delete the note on Evernote, then give the
    // note in the local notebook a new GUID & set the
    // update sequence number to 0.
    for (int i = 0; i < movedLids.size(); i++) {
        QUuid uuid;
        Guid newGuid = uuid.createUuid().toString().replace("{", "").replace("}", "");
        QString guid = noteTable.getGuid(movedLids[i]);
        noteTable.setDirty(movedLids[i], false);
        noteTable.updateGuid(movedLids[i], newGuid);
        noteTable.setUpdateSequenceNumber(movedLids[0], 0);
        usn = comm->deleteNote(guid);
        if (usn > maxUsn) {
            maxUsn = usn;
        }
        if (!finalSync)
            emit(noteSynchronized(movedLids[i], false));
    }


    // Delete any notes that were deleted, but emptied from the trash
    for (int i = 0; i < deleteQueueGuids.size(); i++) {
        QString guid = deleteQueueGuids[i];
        usn = comm->deleteNote(guid);
        if (usn > maxUsn) {
            maxUsn = usn;
        }
        noteTable.expungeFromDeleteQueue(guid);
    }


    // Start uploading notes
    for (int i = 0; i < validLids.size(); i++) {
        Note note;
        noteTable.get(note, validLids[i], true, true);

        qint32 oldUsn = 0;
        if (note.updateSequenceNum.isSet())
            oldUsn = note.updateSequenceNum;
        usn = comm->uploadNote(note);
        if (usn == 0) {
            this->communicationErrorHandler();
            if (note.title.isSet())
                QLOG_ERROR() << tr("Error uploading note:") + note.title;
            else QLOG_ERROR() << tr("Error uploading note with a missing title!");
            error = true;
            //return maxUsn;
        }
        if (usn > maxUsn) {
            maxUsn = usn;
            if (oldUsn == 0)
                noteTable.updateGuid(validLids[i], note.guid);
            noteTable.setUpdateSequenceNumber(validLids[i], usn);
            noteTable.setDirty(validLids[i], false);
            if (!finalSync)
                emit(noteSynchronized(validLids[i], false));
        } else {
            error = true;
        }
    }
    QLOG_TRACE_OUT();
    return maxUsn;
}
void Manager::reactionAddRequest(QString name, int type, QStringList speciesin, QString speciesout, QStringList speciesoptional){

    switch(type){
        case CST_COMPLEXATION:{
                Species *tab = NULL;
                Species out;
                int tab_size = 0;
                for(int i=0;i<speciesin.size();i++){
                    for(int j=0;j<species_list_size;j++){
                        if(species_list[j].Get_name() == speciesin.at(i).toStdString()){
                            Species *new_tab = new Species[tab_size+1];
                            for(int n=0;n<tab_size;n++){
                                new_tab[n].Set_name(tab[n].Get_name());
                                new_tab[n].Set_initial_state(tab[n].Get_initial_state());
                            }
                            new_tab[tab_size] = species_list[i];
                            tab = new_tab;
                            tab_size++;
                        }
                    }
                }
                for(int j=0;j<species_list_size;j++){
                    if(species_list[j].Get_name() == speciesout.toStdString()){
                        out = species_list[j];
                        break;
                    }
                }
                Complex *tmp = new Complex("E_" + name.toStdString(),name.toStdString(),name.toStdString(),tab, speciesin.size(),out);
                bool res = addReactionToList(tmp);
                emit reactionAddingSuccess(res, name, CST_COMPLEXATION, speciesin, speciesout);
            break;
        }
        case CST_SYNTHESIS:{
                Species *tab_act = NULL;
                int tab_act_size = 0;
                for(int i=0;i<speciesin.size();i++){
                    for(int j=0;j<species_list_size;j++){
                        if(species_list[j].Get_name() == speciesin.at(i).toStdString()){
                            Species *new_tab = new Species[tab_act_size+1];
                            for(int n=0;n<tab_act_size;n++){
                                new_tab[n].Set_name(tab_act[n].Get_name());
                                new_tab[n].Set_initial_state(tab_act[n].Get_initial_state());
                            }
                            new_tab[tab_act_size] = species_list[i];
                            tab_act = new_tab;
                            tab_act_size++;
                        }
                    }
                }
                Species *tab_rep = NULL;
                int tab_rep_size = 0;
                for(int i=0;i<speciesoptional.size();i++){
                    for(int j=0;j<species_list_size;j++){
                        if(species_list[j].Get_name() == speciesoptional.at(i).toStdString()){
                            Species *new_tab_2 = new Species[tab_rep_size+1];
                            for(int n=0;n<tab_rep_size;n++){
                                new_tab_2[n].Set_name(tab_rep[n].Get_name());
                                new_tab_2[n].Set_initial_state(tab_rep[n].Get_initial_state());
                            }
                            new_tab_2[tab_rep_size] = species_list[j];
                            tab_rep = new_tab_2;
                            tab_rep_size++;
                        }
                    }
                }
                Species out;
                for(int j=0;j<species_list_size;j++){
                    if(species_list[j].Get_name() == speciesout.toStdString()){
                        out = species_list[j];
                        break;
                    }
                }
                Synth *tmp = new Synth("E_" + name.toStdString(),name.toStdString(),name.toStdString(), tab_act, tab_rep, tab_act_size, tab_rep_size, out);
                bool res = addReactionToList(tmp);
                emit reactionAddingSuccess(res, name, CST_SYNTHESIS, speciesin, speciesout, speciesoptional);
            break;
        }
    }
}
示例#4
0
/** Load the research stats */
bool loadResearch(QString filename)
{
	WzConfig ini(filename, WzConfig::ReadOnlyAndRequired);
	QStringList list = ini.childGroups();
	PLAYER_RESEARCH dummy;
	memset(&dummy, 0, sizeof(dummy));
	QVector<QStringList> preResearch;
	preResearch.resize(list.size());
	for (int inc = 0; inc < list.size(); ++inc)
	{
		// HACK FIXME: the code assumes we have empty PLAYER_RESEARCH entries to throw around
		for (int j = 0; j < MAX_PLAYERS; j++)
		{
			asPlayerResList[j].push_back(dummy);
		}

		ini.beginGroup(list[inc]);
		RESEARCH research;
		research.index = inc;
		research.name = ini.value("name").toString();
		research.id = list[inc];

		//check the name hasn't been used already
		ASSERT_OR_RETURN(false, checkResearchName(&research, inc), "Research name '%s' used already", getName(&research));

		research.ref = REF_RESEARCH_START + inc;

		research.results = ini.json("results", QJsonArray());

		//set subGroup icon
		QString subGroup = ini.value("subgroupIconID", "").toString();
		if (subGroup.compare("") != 0)
		{
			research.subGroup = setIconID(subGroup.toUtf8().data(), getName(&research));
		}
		else
		{
			research.subGroup = NO_RESEARCH_ICON;
		}

		//set key topic
		unsigned int keyTopic = ini.value("keyTopic", 0).toUInt();
		ASSERT(keyTopic <= 1, "Invalid keyTopic for research topic - '%s' ", getName(&research));
		if (keyTopic <= 1)
		{
			research.keyTopic = ini.value("keyTopic", 0).toUInt();
		}
		else
		{
			research.keyTopic = 0;
		}

		//set tech code
		UBYTE techCode = ini.value("techCode", 0).toUInt();
		ASSERT(techCode <= 1, "Invalid tech code for research topic - '%s' ", getName(&research));
		if (techCode == 0)
		{
			research.techCode = TC_MAJOR;
		}
		else
		{
			research.techCode = TC_MINOR;
		}

		//set the iconID
		QString iconID = ini.value("iconID", "").toString();
		if (iconID.compare("") != 0)
		{
			research.iconID = setIconID(iconID.toUtf8().data(), getName(&research));
		}
		else
		{
			research.iconID = NO_RESEARCH_ICON;
		}

		//get the IMDs used in the interface
		QString statID = ini.value("statID", "").toString();
		research.psStat = NULL;
		if (statID.compare("") != 0)
		{
			//try find the structure stat with given name
			research.psStat = getCompStatsFromName(statID);
			ASSERT_OR_RETURN(false, research.psStat, "Could not find stats for %s research %s", statID.toUtf8().constData(), getName(&research));
		}

		QString imdName = ini.value("imdName", "").toString();
		if (imdName.compare("") != 0)
		{
			research.pIMD = modelGet(imdName);
			ASSERT(research.pIMD != NULL, "Cannot find the research PIE '%s' for record '%s'", imdName.toUtf8().data(), getName(&research));
		}

		QString imdName2 = ini.value("imdName2", "").toString();
		if (imdName2.compare("") != 0)
		{
			research.pIMD2 = modelGet(imdName2);
			ASSERT(research.pIMD2 != NULL, "Cannot find the 2nd research '%s' PIE for record '%s'", imdName2.toUtf8().data(), getName(&research));
		}

		QString msgName = ini.value("msgName", "").toString();
		if (msgName.compare("") != 0)
		{
			//check its a major tech code
			ASSERT(research.techCode == TC_MAJOR, "This research should not have a message associated with it, '%s' the message will be ignored!", getName(&research));
			if (research.techCode == TC_MAJOR)
			{
				research.pViewData = getViewData(msgName.toUtf8().data());
			}
		}

		//set the researchPoints
		unsigned int resPoints = ini.value("researchPoints", 0).toUInt();
		ASSERT_OR_RETURN(false, resPoints <= UWORD_MAX, "Research Points too high for research topic - '%s' ", getName(&research));
		research.researchPoints = resPoints;

		//set the research power
		unsigned int resPower = ini.value("researchPower", 0).toUInt();
		ASSERT_OR_RETURN(false, resPower <= UWORD_MAX, "Research Power too high for research topic - '%s' ", getName(&research));
		research.researchPower = resPower;

		//rememeber research pre-requisites for futher checking
		preResearch[inc] = ini.value("requiredResearch").toStringList();

		//set components results
		QStringList compResults = ini.value("resultComponents").toStringList();
		for (int j = 0; j < compResults.size(); j++)
		{
			QString compID = compResults[j].trimmed();
			COMPONENT_STATS *pComp = getCompStatsFromName(compID);
			if (pComp != NULL)
			{
				research.componentResults.push_back(pComp);
			}
			else
			{
				ASSERT(false, "Invalid item '%s' in list of result components of research '%s' ", compID.toUtf8().constData(), getName(&research));
			}
		}

		//set replaced components
		QStringList replacedComp = ini.value("replacedComponents").toStringList();
		for (int j = 0; j < replacedComp.size(); j++)
		{
			//read pair of components oldComponent:newComponent
			QStringList pair = replacedComp[j].split(':');
			ASSERT(pair.size() == 2, "Invalid item '%s' in list of replaced components of research '%s'. Required format: 'oldItem:newItem, item1:item2'", replacedComp[j].toUtf8().constData(), getName(&research));
			if (pair.size() != 2)
			{
				continue; //skip invalid entries
			}
			QString oldCompID = pair[0].trimmed();
			QString newCompID = pair[1].trimmed();
			COMPONENT_STATS *oldComp = getCompStatsFromName(oldCompID);
			if (oldComp == NULL)
			{
				ASSERT(false, "Invalid item '%s' in list of replaced components of research '%s'. Wrong component code.", oldCompID.toUtf8().constData(), getName(&research));
				continue;
			}
			COMPONENT_STATS *newComp = getCompStatsFromName(newCompID);
			if (newComp == NULL)
			{
				ASSERT(false, "Invalid item '%s' in list of replaced components of research '%s'. Wrong component code.", newCompID.toUtf8().constData(), getName(&research));
				continue;
			}
			RES_COMP_REPLACEMENT replItem;
			replItem.pOldComponent = oldComp;
			replItem.pNewComponent = newComp;
			research.componentReplacement.push_back(replItem);
		}

		//set redundant components
		QStringList redComp = ini.value("redComponents").toStringList();
		for (int j = 0; j < redComp.size(); j++)
		{
			QString compID = redComp[j].trimmed();
			COMPONENT_STATS *pComp = getCompStatsFromName(compID);
			if (pComp == NULL)
			{
				ASSERT(false, "Invalid item '%s' in list of redundant components of research '%s' ", compID.toUtf8().constData(), getName(&research));
			}
			else
			{
				research.pRedArtefacts.push_back(pComp);
			}
		}

		//set result structures
		QStringList resStruct = ini.value("resultStructures").toStringList();
		for (int j = 0; j < resStruct.size(); j++)
		{
			QString strucID = resStruct[j].trimmed();
			int structIndex = getStructStatFromName(strucID.toUtf8().data());
			ASSERT(structIndex >= 0, "Invalid item '%s' in list of result structures of research '%s' ", strucID.toUtf8().constData(), getName(&research));
			if (structIndex >= 0)
			{
				research.pStructureResults.push_back(structIndex);
			}
		}

		//set required structures
		QStringList reqStruct = ini.value("requiredStructures").toStringList();
		for (int j = 0; j < reqStruct.size(); j++)
		{
			QString strucID = reqStruct[j].trimmed();
			int structIndex = getStructStatFromName(strucID.toUtf8().data());
			ASSERT(structIndex >= 0, "Invalid item '%s' in list of required structures of research '%s' ", strucID.toUtf8().constData(), getName(&research));
			if (structIndex >= 0)
			{
				research.pStructList.push_back(structIndex);
			}
		}

		//set redundant structures
		QStringList redStruct = ini.value("redStructures").toStringList();
		for (int j = 0; j < redStruct.size(); j++)
		{
			QString strucID = redStruct[j].trimmed();
			int structIndex = getStructStatFromName(strucID.toUtf8().data());
			ASSERT(structIndex >= 0, "Invalid item '%s' in list of redundant structures of research '%s' ", strucID.toUtf8().constData(), getName(&research));
			if (structIndex >= 0)
			{
				research.pRedStructs.push_back(structIndex);
			}
		}

		asResearch.push_back(research);
		ini.endGroup();
	}

	//Load and check research pre-requisites (need do it AFTER loading research items)
	for (int inc = 0; inc < asResearch.size(); inc++)
	{
		QStringList preRes = preResearch[inc];
		for (int j = 0; j < preRes.size(); j++)
		{
			QString resID = preRes[j].trimmed();
			RESEARCH *preResItem = getResearch(resID.toUtf8().constData());
			ASSERT(preResItem != NULL, "Invalid item '%s' in list of pre-requisites of research '%s' ", resID.toUtf8().constData(), getName(&asResearch[inc]));
			if (preResItem != NULL)
			{
				asResearch[inc].pPRList.push_back(preResItem->index);
			}
		}
	}

	return true;
}
示例#5
0
/**
 * Retrieves the data stored in this object and store the result in
 * pMedium.
 *
 * @return  IPRT status code.
 * @return  HRESULT
 * @param   pFormatEtc
 * @param   pMedium
 */
STDMETHODIMP UIDnDDataObject::GetData(FORMATETC *pFormatEtc, STGMEDIUM *pMedium)
{
    AssertPtrReturn(pFormatEtc, DV_E_FORMATETC);
    AssertPtrReturn(pMedium, DV_E_FORMATETC);

#ifdef VBOX_DND_DEBUG_FORMATS
    LogFlowFunc(("pFormatEtc=%p, pMedium=%p\n", pFormatEtc, pMedium));
#endif

    ULONG lIndex;
    if (!LookupFormatEtc(pFormatEtc, &lIndex)) /* Format supported? */
        return DV_E_FORMATETC;
    if (lIndex >= mcFormats) /* Paranoia. */
        return DV_E_FORMATETC;

    FORMATETC *pThisFormat = &mpFormatEtc[lIndex];
    AssertPtr(pThisFormat);

    STGMEDIUM *pThisMedium = &mpStgMedium[lIndex];
    AssertPtr(pThisMedium);

    HRESULT hr = DV_E_FORMATETC;

    LogFlowFunc(("mStatus=%ld\n", mStatus));
    if (mStatus == Dropping)
    {
        LogFlowFunc(("Waiting for event ...\n"));
        int rc2 = RTSemEventWait(mSemEvent, RT_INDEFINITE_WAIT);
        LogFlowFunc(("rc=%Rrc, mStatus=%ld\n", rc2, mStatus));
    }

    if (mStatus == Dropped)
    {
        LogFlowFunc(("cfFormat=%RI16, sFormat=%s, tyMed=%RU32, dwAspect=%RU32\n",
                     pThisFormat->cfFormat, UIDnDDataObject::ClipboardFormatToString(pFormatEtc->cfFormat),
                     pThisFormat->tymed, pThisFormat->dwAspect));
        LogFlowFunc(("Got strFormat=%s, pvData=%p, cbData=%RU32\n",
                     mstrFormat.toAscii().constData(), mpvData, mcbData));

        QVariant::Type vaType;
        QString strMIMEType;
        if (    (pFormatEtc->tymed & TYMED_HGLOBAL)
             && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
             && (   pFormatEtc->cfFormat == CF_TEXT
                 || pFormatEtc->cfFormat == CF_UNICODETEXT)
           )
        {
            strMIMEType = "text/plain"; /** @todo Indicate UTF8 encoding? */
            vaType = QVariant::String;
        }
        else if (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                 && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                 && (pFormatEtc->cfFormat == CF_HDROP))
        {
            strMIMEType = "text/uri-list";
            vaType = QVariant::StringList;
        }
#if 0 /* More formats; not needed right now. */
        else if (   (pFormatEtc->tymed & TYMED_ISTREAM)
                && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                && (pFormatEtc->cfFormat == CF_FILECONTENTS))
        {

        }
        else if  (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                  && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                  && (pFormatEtc->cfFormat == CF_FILEDESCRIPTOR))
        {

        }
        else if (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                 && (pFormatEtc->cfFormat == CF_PREFERREDDROPEFFECT))
        {
            HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, sizeof(DWORD));
            DWORD *pdwEffect = (DWORD *)GlobalLock(hData);
            AssertPtr(pdwEffect);
            *pdwEffect = DROPEFFECT_COPY;
            GlobalUnlock(hData);

            pMedium->hGlobal = hData;
            pMedium->tymed = TYMED_HGLOBAL;
        }
#endif
        LogFlowFunc(("strMIMEType=%s, vaType=%ld\n",
                     strMIMEType.toAscii().constData(), vaType));

        int rc;
        if (!mVaData.isValid())
        {
            rc = UIDnDDrag::RetrieveData(mSession,
                                         mDnDSource,
                                         /** @todo Support other actions. */
                                         Qt::CopyAction,
                                         strMIMEType, vaType, mVaData,
                                         mpParent);
        }
        else
            rc = VINF_SUCCESS; /* Data already retrieved. */

        if (RT_SUCCESS(rc))
        {
            if (   strMIMEType.startsWith("text/uri-list")
                       /* One item. */
                && (   mVaData.canConvert(QVariant::String)
                       /* Multiple items. */
                    || mVaData.canConvert(QVariant::StringList))
               )
            {
                QStringList lstFilesURI = mVaData.toStringList();
                QStringList lstFiles;
                for (size_t i = 0; i < lstFilesURI.size(); i++)
                {
                    /* Extract path from URI. */
                    char *pszPath = RTUriPath(lstFilesURI.at(i).toAscii().constData());
                    if (   pszPath
                        && strlen(pszPath) > 1)
                    {
                        pszPath++; /** @todo Skip first '/' (part of URI). Correct? */
                        pszPath = RTPathChangeToDosSlashes(pszPath, false /* fForce */);
                        lstFiles.append(pszPath);
                    }
                }

                size_t cFiles = lstFiles.size();
                Assert(cFiles);
#ifdef DEBUG
                LogFlowFunc(("Files (%zu)\n", cFiles));
                for (size_t i = 0; i < cFiles; i++)
                    LogFlowFunc(("\tFile: %s\n", lstFiles.at(i).toAscii().constData()));
#endif
                size_t cchFiles = 0; /* Number of ASCII characters. */
                for (size_t i = 0; i < cFiles; i++)
                {
                    cchFiles += strlen(lstFiles.at(i).toAscii().constData());
                    cchFiles += 1; /* Terminating '\0'. */
                }

                size_t cbBuf = sizeof(DROPFILES) + ((cchFiles + 1) * sizeof(RTUTF16));
                DROPFILES *pDropFiles = (DROPFILES *)RTMemAllocZ(cbBuf);
                if (pDropFiles)
                {
                    pDropFiles->pFiles = sizeof(DROPFILES);
                    pDropFiles->fWide = 1; /* We use unicode. Always. */

                    uint8_t *pCurFile = (uint8_t *)pDropFiles + pDropFiles->pFiles;
                    AssertPtr(pCurFile);

                    for (size_t i = 0; i < cFiles; i++)
                    {
                        size_t cchCurFile;
                        PRTUTF16 pwszFile;
                        rc = RTStrToUtf16(lstFiles.at(i).toAscii().constData(), &pwszFile);
                        if (RT_SUCCESS(rc))
                        {
                            cchCurFile = RTUtf16Len(pwszFile);
                            Assert(cchCurFile);
                            memcpy(pCurFile, pwszFile, cchCurFile * sizeof(RTUTF16));
                            RTUtf16Free(pwszFile);
                        }
                        else
                            break;

                        pCurFile += cchCurFile * sizeof(RTUTF16);

                        /* Terminate current file name. */
                        *pCurFile = L'\0';
                        pCurFile += sizeof(RTUTF16);
                    }

                    if (RT_SUCCESS(rc))
                    {
                        *pCurFile = L'\0'; /* Final list terminator. */

                        pMedium->tymed = TYMED_HGLOBAL;
                        pMedium->pUnkForRelease = NULL;
                        pMedium->hGlobal = GlobalAlloc(  GMEM_ZEROINIT
                                                       | GMEM_MOVEABLE
                                                       | GMEM_DDESHARE, cbBuf);
                        if (pMedium->hGlobal)
                        {
                            LPVOID pvMem = GlobalLock(pMedium->hGlobal);
                            if (pvMem)
                            {
                                memcpy(pvMem, pDropFiles, cbBuf);
                                GlobalUnlock(pMedium->hGlobal);

                                hr = S_OK;
                            }
                            else
                                rc = VERR_ACCESS_DENIED;
                        }
                        else
                            rc = VERR_NO_MEMORY;
                    }

                    RTMemFree(pDropFiles);
                }
            }
            else if (   strMIMEType.startsWith("text/plain")
                     && mVaData.canConvert(QVariant::String))
            {
                bool fUnicode = pFormatEtc->cfFormat == CF_UNICODETEXT;
                int cbCh = fUnicode
                         ? sizeof(WCHAR) : sizeof(char);

                QString strText = mVaData.toString();
                size_t cbSrc = strText.length() * cbCh;
                Assert(cbSrc);
                LPCVOID pvSrc = fUnicode
                              ? (void *)strText.unicode()
                              : (void *)strText.toAscii().constData();
                AssertPtr(pvSrc);

                LogFlowFunc(("pvSrc=0x%p, cbSrc=%zu, cbch=%d, fUnicode=%RTbool\n",
                             pvSrc, cbSrc, cbCh, fUnicode));

                pMedium->tymed = TYMED_HGLOBAL;
                pMedium->pUnkForRelease = NULL;
                pMedium->hGlobal = GlobalAlloc(  GMEM_ZEROINIT
                                               | GMEM_MOVEABLE
                                               | GMEM_DDESHARE,
                                               cbSrc);
                if (pMedium->hGlobal)
                {
                    LPVOID pvDst = GlobalLock(pMedium->hGlobal);
                    if (pvDst)
                    {
                        memcpy(pvDst, pvSrc, cbSrc);
                        GlobalUnlock(pMedium->hGlobal);
                    }
                    else
                        rc = VERR_ACCESS_DENIED;

                    hr = S_OK;
                }
                else
                    hr  = VERR_NO_MEMORY;
            }
            else
                LogFlowFunc(("MIME type=%s not supported\n",
                             strMIMEType.toAscii().constData()));

            LogFlowFunc(("Handling formats ended with rc=%Rrc\n", rc));
        }
    }

    /*
     * Fallback in error case.
     */
    if (FAILED(hr))
    {
        LogFlowFunc(("Error hr=%Rhrc while handling data, copying raw medium data ...\n", hr));

        switch (pThisMedium->tymed)
        {

        case TYMED_HGLOBAL:
            pMedium->hGlobal = (HGLOBAL)OleDuplicateData(pThisMedium->hGlobal,
                                                         pThisFormat->cfFormat,
                                                         0 /* Flags */);
            break;

        default:
            break;
        }

        pMedium->tymed          = pFormatEtc->tymed;
        pMedium->pUnkForRelease = NULL;
    }

    LogFlowFunc(("Returning hr=%Rhrc\n", hr));
    return hr;
}
示例#6
0
void NetTree::showWebVideo()
{
    ResultItem *item;

    if (m_type == DLG_TREE)
        item = qVariantValue<ResultItem *>(m_siteMap->GetCurrentNode()->GetData());
    else
    {
        MythGenericTree *node = GetNodePtrFromButton(m_siteButtonList->GetItemCurrent());

        if (!node)
            return;

        item = qVariantValue<ResultItem *>(node->GetData());
    }

    if (!item)
        return;

    if (!item->GetPlayer().isEmpty())
    {
        QString cmd = item->GetPlayer();
        QStringList args = item->GetPlayerArguments();
        if (!args.size())
        {
            args += item->GetMediaURL();
            if (!args.size())
                args += item->GetURL();
        }
        else
        {
            args.replaceInStrings("%DIR%", QString(GetConfDir() + "/MythNetvision"));
            args.replaceInStrings("%MEDIAURL%", item->GetMediaURL());
            args.replaceInStrings("%URL%", item->GetURL());
            args.replaceInStrings("%TITLE%", item->GetTitle());
        }
        QString playerCommand = cmd + " " + args.join(" ");

        myth_system(playerCommand);
    }
    else
    {
        QString url = item->GetURL();

        LOG(VB_GENERAL, LOG_DEBUG, QString("Web URL = %1").arg(url));

        if (url.isEmpty())
            return;

        QString browser = gCoreContext->GetSetting("WebBrowserCommand", "");
        QString zoom = gCoreContext->GetSetting("WebBrowserZoomLevel", "1.0");

        if (browser.isEmpty())
        {
            ShowOkPopup(tr("No browser command set! MythNetTree needs MythBrowser "
                           "installed to display the video."));
            return;
        }

        if (browser.toLower() == "internal")
        {
            GetMythMainWindow()->HandleMedia("WebBrowser", url);
            return;
        }
        else
        {
            QString cmd = browser;
            cmd.replace("%ZOOM%", zoom);
            cmd.replace("%URL%", url);
            cmd.replace('\'', "%27");
            cmd.replace("&","\\&");
            cmd.replace(";","\\;");

            GetMythMainWindow()->AllowInput(false);
            myth_system(cmd, kMSDontDisableDrawing);
            GetMythMainWindow()->AllowInput(true);
            return;
        }
    }
}
/*
 * Because Maemo 5 is using a special dialog design this window is declared
 * as a tool window.
 */
SettingsPagePointDataLoading::SettingsPagePointDataLoading( QWidget *parent ) :
  QWidget( parent )
{
  setObjectName("SettingsPagePointDataLoading");
  setAttribute( Qt::WA_DeleteOnClose );
  setWindowFlags( Qt::Tool );
  setWindowTitle(tr("Point data loading settings"));
  setWindowModality( Qt::WindowModal );

  if( _globalMainWindow )
    {
      // Resize the window to the same size as the main window has. That will
      // completely hide the parent window.
      resize( _globalMainWindow->size() );
    }

  QStringList mapDirs = GeneralConfig::instance()->getMapDirectories();

  QVBoxLayout *topLayout = new QVBoxLayout( this );
  topLayout->setSpacing(10);

  m_fileTable = new QTableWidget( 0, 1, this );
  m_fileTable->setToolTip( tr("Uncheck All to enable loading of single files.") );
  m_fileTable->setSelectionBehavior( QAbstractItemView::SelectRows );
  m_fileTable->setAlternatingRowColors( true );
  m_fileTable->setShowGrid( true );

  // set new row height from configuration
  int afMargin = GeneralConfig::instance()->getListDisplayAFMargin();
  m_fileTable->setItemDelegate( new RowDelegate( m_fileTable, afMargin ) );

  m_fileTable->setVerticalScrollMode( QAbstractItemView::ScrollPerPixel );
  m_fileTable->setHorizontalScrollMode( QAbstractItemView::ScrollPerPixel );

#ifdef ANDROID
  QScrollBar* lvsb = m_fileTable->verticalScrollBar();
  lvsb->setStyleSheet( Layout::getCbSbStyle() );
#endif

#ifdef QSCROLLER
  QScroller::grabGesture( m_fileTable->viewport(), QScroller::LeftMouseButtonGesture );
#endif

#ifdef QTSCROLLER
  QtScroller::grabGesture( m_fileTable->viewport(), QtScroller::LeftMouseButtonGesture );
#endif

  QString style = "QTableView QTableCornerButton::section { background: gray }";
  m_fileTable->setStyleSheet( style );

  QHeaderView *vHeader = m_fileTable->verticalHeader();
  style = "QHeaderView::section { width: 2em }";
  vHeader->setStyleSheet( style );

  connect( m_fileTable, SIGNAL(cellClicked ( int, int )),
           SLOT(slot_toggleCheckBox( int, int )) );

  connect( m_fileTable, SIGNAL(itemSelectionChanged()),
           this, SLOT(slot_itemSelectionChanged()) );

  QHeaderView* hHeader = m_fileTable->horizontalHeader();
  hHeader->setStretchLastSection( true );

  QString loadDirs;

  for( int i = 0; i < mapDirs.size(); i++ )
    {
      if( i > 0 )
        {
          loadDirs.append("\n");
        }

      loadDirs += mapDirs.at(i) + "/points";
    }

  QTableWidgetItem *item = new QTableWidgetItem( loadDirs );
  item->setTextAlignment( Qt::AlignLeft );
  m_fileTable->setHorizontalHeaderItem( 0, item );

  topLayout->addWidget( m_fileTable, 10 );

  int buttonSize = Layout::getButtonSize();
  int iconSize   = buttonSize - 5;

  m_delButton = new QPushButton;
  m_delButton->setIcon( QIcon( GeneralConfig::instance()->loadPixmap( "delete.png" ) ) );
  m_delButton->setIconSize(QSize(iconSize, iconSize));
  m_delButton->setMinimumSize(buttonSize, buttonSize);
  m_delButton->setMaximumSize(buttonSize, buttonSize);
  m_delButton->setEnabled( false );

  QPushButton *okButton = new QPushButton;
  okButton->setIcon(QIcon(GeneralConfig::instance()->loadPixmap("ok.png")));
  okButton->setIconSize(QSize(iconSize, iconSize));
  okButton->setMinimumSize(buttonSize, buttonSize);
  okButton->setMaximumSize(buttonSize, buttonSize);

  QPushButton *cancelButton = new QPushButton;
  cancelButton->setIcon(QIcon(GeneralConfig::instance()->loadPixmap("cancel.png")));
  cancelButton->setIconSize(QSize(iconSize, iconSize));
  cancelButton->setMinimumSize(buttonSize, buttonSize);
  cancelButton->setMaximumSize(buttonSize, buttonSize);

  connect( m_delButton, SIGNAL(clicked() ), this, SLOT(slot_DeleteRows()) );
  connect( okButton, SIGNAL(clicked() ), this, SLOT(slot_save()) );
  connect( cancelButton, SIGNAL(clicked() ), this, SLOT(close()) );

  // box with operator buttons
  QHBoxLayout *buttonBox = new QHBoxLayout;

  buttonBox->setSpacing(0);
  buttonBox->addWidget( m_delButton );
  buttonBox->addStretch(2);
  buttonBox->addWidget( cancelButton );
  buttonBox->addSpacing(32);
  buttonBox->addWidget( okButton );
  topLayout->addLayout( buttonBox );

  //---------------------------------------------------------------------------
  // Load table with POI files
  QStringList preselect;

  for ( int i = 0; i < mapDirs.size(); ++i )
    {
      MapContents::addDir(preselect, mapDirs.at(i) + "/points", "*_wpt.aip");
      MapContents::addDir(preselect, mapDirs.at(i) + "/points", "*_nav.aip");
      MapContents::addDir(preselect, mapDirs.at(i) + "/points", "*_hot.aip");
    }

  preselect.sort();

  int row = 0;
  m_fileTable->setRowCount( row + 1 );

  item = new QTableWidgetItem( tr("Check or Uncheck all"), 0 );
  item->setFlags( Qt::ItemIsEnabled );
  item->setCheckState( Qt::Unchecked );
  m_fileTable->setItem( row, 0, item );
  row++;

  for( int i = 0; i < preselect.size(); i++ )
    {
      m_fileTable->setRowCount( row + 1 );

      QString file = QFileInfo( preselect.at(i) ).fileName();
      item = new QTableWidgetItem( file, row );
      item->setFlags( Qt::ItemIsEnabled|Qt::ItemIsSelectable );
      item->setData( Qt::UserRole, preselect.at(i) );
      item->setCheckState( Qt::Unchecked );
      m_fileTable->setItem( row, 0, item );
      row++;
    }

  QStringList& files = GeneralConfig::instance()->getOpenAipPoiFileList();

  if( files.isEmpty() )
    {
      return;
    }

  if( files.at(0) == "All" )
    {
      // Set all items to checked, if All is contained in the list at the first
      // position.
      for( int i = 0; i < m_fileTable->rowCount(); i++ )
        {
          m_fileTable->item( i, 0 )->setCheckState( Qt::Checked );
        }
    }
  else
    {
      // Set the All item to unchecked.
      m_fileTable->item( 0, 0 )->setCheckState( Qt::Unchecked );

      for( int i = 1; i < m_fileTable->rowCount(); i++ )
        {
          QTableWidgetItem* item = m_fileTable->item( i, 0 );

          if( files.contains( item->text()) )
            {
              m_fileTable->item( i, 0 )->setCheckState( Qt::Checked );
            }
          else
            {
              m_fileTable->item( i, 0 )->setCheckState( Qt::Unchecked );
            }
        }
    }

  m_fileTable->resizeColumnsToContents();
  m_fileTable->resizeRowsToContents();
}
示例#8
0
QgsAbout::QgsAbout( QWidget *parent )
    : QDialog( parent, Qt::WindowSystemMenuHint )  // Modeless dialog with close button only
#else
QgsAbout::QgsAbout( QWidget *parent )
    : QDialog( parent )  // Normal dialog in non Mac-OS
#endif
{
  setupUi( this );
  init();
}

QgsAbout::~QgsAbout()
{
}

void QgsAbout::init()
{
  setPluginInfo();

  setWindowTitle( QString( "%1 - %2 Bit" ).arg( windowTitle() ).arg( QSysInfo::WordSize ) );

  // set the 60x60 icon pixmap
  QPixmap icon( QgsApplication::iconsPath() + "qgis-icon-60x60.png" );
  qgisIcon->setPixmap( icon );

  //read the authors file to populate the svn committers list
  QStringList lines;

  //
  // Load the authors (svn committers) list
  //
  QFile file( QgsApplication::authorsFilePath() );
  if ( file.open( QIODevice::ReadOnly ) )
  {
    QTextStream stream( &file );
    // Always use UTF-8
    stream.setCodec( "UTF-8" );
    QString line;
    while ( !stream.atEnd() )
    {
      line = stream.readLine(); // line of text excluding '\n'
      //ignore the line if it starts with a hash....
      if ( line.left( 1 ) == "#" )
        continue;
      QStringList myTokens = line.split( "\t", QString::SkipEmptyParts );
      lines << myTokens[0];
    }
    file.close();
    lstDevelopers->clear();
    lstDevelopers->insertItems( 0, lines );

    if ( lstDevelopers->count() > 0 )
    {
      lstDevelopers->setCurrentRow( 0 );
    }
  }

  lines.clear();
  //
  // Now load up the contributors list
  //
  QFile file2( QgsApplication::contributorsFilePath() );
  printf( "Reading contributors file %s.............................................\n",
          file2.fileName().toLocal8Bit().constData() );
  if ( file2.open( QIODevice::ReadOnly ) )
  {
    QTextStream stream( &file2 );
    // Always use UTF-8
    stream.setCodec( "UTF-8" );
    QString line;
    while ( !stream.atEnd() )
    {
      line = stream.readLine(); // line of text excluding '\n'
      //ignore the line if it starts with a hash....
      if ( line.left( 1 ) == "#" )
        continue;
      lines += line;
    }
    file2.close();
    lstContributors->clear();
    lstContributors->insertItems( 0, lines );
    if ( lstContributors->count() > 0 )
    {
      lstContributors->setCurrentRow( 0 );
    }
  }



  // read the DONORS file and populate the text widget
  QFile donorsFile( QgsApplication::donorsFilePath() );
#ifdef QGISDEBUG
  printf( "Reading donors file %s.............................................\n",
          donorsFile.fileName().toLocal8Bit().constData() );
#endif
  if ( donorsFile.open( QIODevice::ReadOnly ) )
  {
    QString donorsHTML = ""
                         + tr( "<p>For a list of individuals and institutions who have contributed "
                               "money to fund QGIS development and other project costs see "
                               "<a href=\"http://qgis.org/en/sponsorship/donors.html\">"
                               "http://qgis.org/en/sponsorship/donors.html</a></p>" );
#if 0
    QString website;
    QTextStream donorsStream( &donorsFile );
    // Always use UTF-8
    donorsStream.setCodec( "UTF-8" );
    QString sline;
    while ( !donorsStream.atEnd() )
    {
      sline = donorsStream.readLine(); // line of text excluding '\n'
      //ignore the line if it starts with a hash....
      if ( sline.left( 1 ) == "#" )
        continue;
      QStringList myTokens = sline.split( "|", QString::SkipEmptyParts );
      if ( myTokens.size() > 1 )
      {
        website = "<a href=\"" + myTokens[1].remove( ' ' ) + "\">" + myTokens[1] + "</a>";
      }
      else
      {
        website = "&nbsp;";
      }
      donorsHTML += "<tr>";
      donorsHTML += "<td>" + myTokens[0] + "</td><td>" + website + "</td>";
      // close the row
      donorsHTML += "</tr>";
    }
    donorsHTML += "</table>";
#endif

    QString myStyle = QgsApplication::reportStyleSheet();
    txtDonors->clear();
    txtDonors->document()->setDefaultStyleSheet( myStyle );
    txtDonors->setHtml( donorsHTML );
    QgsDebugMsg( QString( "donorsHTML:%1" ).arg( donorsHTML.toAscii().constData() ) );
  }

  // read the TRANSLATORS file and populate the text widget
  QFile translatorFile( QgsApplication::translatorsFilePath() );
#ifdef QGISDEBUG
  printf( "Reading translators file %s.............................................\n",
          translatorFile.fileName().toLocal8Bit().constData() );
#endif
  if ( translatorFile.open( QIODevice::ReadOnly ) )
  {
    QString translatorHTML = "";
    QTextStream translatorStream( &translatorFile );
    // Always use UTF-8
    translatorStream.setCodec( "UTF-8" );
    QString myStyle = QgsApplication::reportStyleSheet();
    translatorHTML += "<style>" + myStyle + "</style>";
    while ( !translatorStream.atEnd() )
    {
      translatorHTML += translatorStream.readLine();
    }
    txtTranslators->setHtml( translatorHTML );
    QgsDebugMsg( QString( "translatorHTML:%1" ).arg( translatorHTML.toAscii().constData() ) );
  }
  setWhatsNew();
  setLicence();
}
示例#9
0
void ScServer::onScLangReponse( const QString & selector, const QString & data )
{
    static QString defaultServerRunningChangedSelector("defaultServerRunningChanged");
    static QString mutedSelector("serverMuted");
    static QString unmutedSelector("serverUnmuted");
    static QString ampSelector("serverAmp");
    static QString ampRangeSelector("serverAmpRange");
    static QString startDumpOSCSelector("dumpOSCStarted");
    static QString stopDumpOSCSelector("dumpOSCStopped");
    static QString startRecordingSelector("recordingStarted");
    static QString pauseRecordingSelector("recordingPaused");
    static QString stopRecordingSelector("recordingStopped");
    static QString recordingDurationSelector("recordingDuration");

    if (selector == defaultServerRunningChangedSelector)
        handleRuningStateChangedMsg(data);
    else if(selector == mutedSelector) {
        mActions[Mute]->setChecked(true);
    } else if (selector == unmutedSelector) {
        mActions[Mute]->setChecked(false);
    }
    else if (selector == startDumpOSCSelector) {
        mActions[DumpOSC]->setChecked(true);
    }
    else if (selector == stopDumpOSCSelector) {
        mActions[DumpOSC]->setChecked(false);
    }
	else if (selector == recordingDurationSelector) {
        bool ok;
        float duration = data.mid(1, data.size() - 2).toFloat(&ok);
        if (ok) {
            mRecordingSeconds = (int) duration;
            updateRecordingAction();
        }
    }
    else if (selector == startRecordingSelector) {
        setRecording(true);
    }
    else if (selector == startRecordingSelector) {
        setRecording(true);
    }
    else if (selector == pauseRecordingSelector) {
        pauseRecording(true);
    }
    else if (selector == stopRecordingSelector) {
        setRecording(false);
    }
    else if (selector == ampSelector) {
        bool ok;
        float volume = data.mid(1, data.size() - 2).toFloat(&ok);
        if (ok) {
            mVolume = volume;
            emit volumeChanged( volume );
        }
    }
    else if (selector == ampRangeSelector) {
        bool ok;
        QStringList dataList = data.mid(1, data.size() - 2).split(',');
        if (dataList.size() < 2)
            return;
        float min = dataList[0].toFloat(&ok);
        if (!ok) return;
        float max = dataList[1].toFloat(&ok);
        if (!ok) return;
        mVolumeMin = min;
        mVolumeMax = max;
        setVolumeRange( min, max );
    }
}
示例#10
0
文件: ssdp.cpp 项目: royboy626/mythtv
void SSDP::ProcessData( MSocketDevice *pSocket )
{
    QByteArray buffer;
    long nBytes = 0;

    while ((nBytes = pSocket->bytesAvailable()) > 0)
    {
        buffer.resize(nBytes);

        long nRead = 0;
        do
        {
            long ret = pSocket->readBlock( buffer.data() + nRead, nBytes );
            if (ret < 0)
            {
                LOG(VB_GENERAL, LOG_ERR, QString("Socket readBlock error %1")
                    .arg(pSocket->error()));
                buffer.clear();
                break;
            }

            nRead += ret;

            if (0 == ret)
            {
                LOG(VB_SOCKET, LOG_WARNING,
                    QString("%1 bytes reported available, "
                            "but only %2 bytes read.")
                    .arg(nBytes).arg(nRead));
                nBytes = nRead;
                buffer.resize(nBytes);
                break;
            }
        }
        while (nRead < nBytes);

        if (buffer.isEmpty())
            continue;

        QHostAddress  peerAddress = pSocket->peerAddress();
        quint16       peerPort    = pSocket->peerPort   ();

        // ------------------------------------------------------------------
        QString     str          = QString(buffer.constData());
        QStringList lines        = str.split("\r\n", QString::SkipEmptyParts);
        QString     sRequestLine = lines.size() ? lines[0] : "";

        lines.pop_front();

        // ------------------------------------------------------------------
        // Parse request Type
        // ------------------------------------------------------------------

        LOG(VB_UPNP, LOG_DEBUG, QString("SSDP::ProcessData - requestLine: %1")
                .arg(sRequestLine));

        SSDPRequestType eType = ProcessRequestLine( sRequestLine );

        // ------------------------------------------------------------------
        // Read Headers into map
        // ------------------------------------------------------------------

        QStringMap  headers;

        for ( QStringList::Iterator it = lines.begin();
                                    it != lines.end(); ++it ) 
        {
            QString sLine  = *it;
            QString sName  = sLine.section( ':', 0, 0 ).trimmed();
            QString sValue = sLine.section( ':', 1 );

            sValue.truncate( sValue.length() );  //-2

            if ((sName.length() != 0) && (sValue.length() !=0))
                headers.insert( sName.toLower(), sValue.trimmed() );
        }

#if 0
        pSocket->SetDestAddress( peerAddress, peerPort );
#endif

        // --------------------------------------------------------------
        // See if this is a valid request
        // --------------------------------------------------------------

        switch( eType )
        {
            case SSDP_MSearch:
            {
                // ----------------------------------------------------------
                // If we haven't enabled notifications yet, then we don't 
                // want to answer search requests.
                // ----------------------------------------------------------

                if (m_pNotifyTask != NULL)
                    ProcessSearchRequest( headers, peerAddress, peerPort ); 

                break;
            }

            case SSDP_MSearchResp:
                ProcessSearchResponse( headers); 
                break;

            case SSDP_Notify:
                ProcessNotify( headers ); 
                break;

            case SSDP_Unknown:
            default:
                LOG(VB_UPNP, LOG_ERR,
                    "SSPD::ProcessData - Unknown request Type.");
                break;
        }
    }
}
示例#11
0
void QgsSingleBandPseudoColorRendererWidget::on_mLoadFromFileButton_clicked()
{
  int lineCounter = 0;
  bool importError = false;
  QString badLines;
  QSettings settings;
  QString lastDir = settings.value( "lastRasterFileFilterDir", "" ).toString();
  QString fileName = QFileDialog::getOpenFileName( this, tr( "Open file" ), lastDir, tr( "Textfile (*.txt)" ) );
  QFile inputFile( fileName );
  if ( inputFile.open( QFile::ReadOnly ) )
  {
    //clear the current tree
    mColormapTreeWidget->clear();

    QTextStream inputStream( &inputFile );
    QString inputLine;
    QStringList inputStringComponents;
    QList<QgsColorRampShader::ColorRampItem> colorRampItems;

    //read through the input looking for valid data
    while ( !inputStream.atEnd() )
    {
      lineCounter++;
      inputLine = inputStream.readLine();
      if ( !inputLine.isEmpty() )
      {
        if ( !inputLine.simplified().startsWith( "#" ) )
        {
          if ( inputLine.contains( "INTERPOLATION", Qt::CaseInsensitive ) )
          {
            inputStringComponents = inputLine.split( ":" );
            if ( inputStringComponents.size() == 2 )
            {
              if ( inputStringComponents[1].trimmed().toUpper().compare( "INTERPOLATED", Qt::CaseInsensitive ) == 0 )
              {
                mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findText( tr( "Linear" ) ) );
              }
              else if ( inputStringComponents[1].trimmed().toUpper().compare( "DISCRETE", Qt::CaseInsensitive ) == 0 )
              {
                mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findText( tr( "Discrete" ) ) );
              }
              else
              {
                mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findText( tr( "Exact" ) ) );
              }
            }
            else
            {
              importError = true;
              badLines = badLines + QString::number( lineCounter ) + ":\t[" + inputLine + "]\n";
            }
          }
          else
          {
            inputStringComponents = inputLine.split( "," );
            if ( inputStringComponents.size() == 6 )
            {
              QgsColorRampShader::ColorRampItem currentItem( inputStringComponents[0].toDouble(),
                  QColor::fromRgb( inputStringComponents[1].toInt(), inputStringComponents[2].toInt(),
                                   inputStringComponents[3].toInt(), inputStringComponents[4].toInt() ),
                  inputStringComponents[5] );
              colorRampItems.push_back( currentItem );
            }
            else
            {
              importError = true;
              badLines = badLines + QString::number( lineCounter ) + ":\t[" + inputLine + "]\n";
            }
          }
        }
      }
      lineCounter++;
    }
    populateColormapTreeWidget( colorRampItems );

    if ( importError )
    {
      QMessageBox::warning( this, tr( "Import Error" ), tr( "The following lines contained errors\n\n" ) + badLines );
    }
  }
  else if ( !fileName.isEmpty() )
  {
    QMessageBox::warning( this, tr( "Read access denied" ), tr( "Read access denied. Adjust the file permissions and try again.\n\n" ) );
  }
}
示例#12
0
/**
* This function fills parent with its children. To achieve this, it calls MOOmc functions.
* @arg depthMax : maximum depth filling should go (each time functions goes in children, grand children...
* Depth is increased by one.
* @arg curDepth : current depth.
* @arg direction : allows to drive looking function along a path. This is especially used
* to look for deep modelas without covering all items.
*/
void ModItemsTree::readFromOmc(ModItem* parent,int depthMax,QString direction,int curDepth)
{
    if(parent->_readMutex.tryLock() && _project->useOmc())
    {
        if((curDepth<=depthMax)&&!parent->childrenReaden())
        {
            ModItem* newElement;



            QString childrenDirection = direction.section(".",curDepth+1,curDepth+1);

            bool readPackages = (parent->getClassRestr()==Modelica::PACKAGE) || (parent->getClassRestr()==Modelica::GENERIC);
            bool readModels = (parent->getClassRestr()==Modelica::PACKAGE) || (parent->getClassRestr()==Modelica::GENERIC);
            bool readComponents = (parent->getClassRestr()==Modelica::MODEL) || (parent->getClassRestr()==Modelica::GENERIC) || (parent->getClassRestr()==Modelica::COMPONENT);
            bool readRecords = (parent->getClassRestr()==Modelica::PACKAGE) || (parent->getClassRestr()==Modelica::MODEL) ||(parent->getClassRestr()==Modelica::GENERIC)|| (parent->getClassRestr()==Modelica::COMPONENT);
            bool readClasses = readModels;

            QString fullParentName = parent->name(ModItem::FULL);
            QString parentClassName = parent->getModClassName();
            QString prefix;
            if(!fullParentName.isEmpty())
                prefix = fullParentName+".";

            // read packages
            if(readPackages)
            {
                QStringList packageNames = _moomc->getPackages(fullParentName);
                for(int i=0;i<packageNames.size();i++)
                {
                    newElement = new ModPackage(_moomc,parent,prefix+packageNames.at(i));
                    if(addChild(parent,newElement))
                        if((childrenDirection=="") || (childrenDirection==packageNames.at(i)))
                            readFromOMCWThread(newElement,depthMax,direction,curDepth+1);
                }
            }

            // read models
            if(readModels)
            {
                QStringList modelNames = _moomc->getModels(fullParentName);
                for(int i=0;i<modelNames.size();i++)
                {
                    newElement = new ModModel(_moomc,parent,prefix+modelNames.at(i));
                    if(addChild(parent,newElement))
                        if((childrenDirection=="") || (childrenDirection==modelNames.at(i)))
                            readFromOMCWThread(newElement,depthMax,direction,curDepth+1);
                }
            }

            // read records
            if(readRecords)
            {
                QStringList recordNames = _moomc->getRecords(fullParentName);
                for(int i=0;i<recordNames.size();i++)
                {
                    newElement = new ModRecord(_moomc,parent,prefix+recordNames.at(i));
                    if(addChild(parent,newElement))
                        if((childrenDirection=="") || (childrenDirection==recordNames.at(i)))
                            readFromOMCWThread(newElement,depthMax,direction,curDepth+1);
                }
            }

            // read classes
            if(readClasses)
            {
                QStringList classNames = _moomc->getClasses(fullParentName);
                for(int i=0;i<classNames.size();i++)
                {
                    newElement = new ModItem(_moomc,parent,prefix+classNames.at(i));
                    if(addChild(parent,newElement))
                        if((childrenDirection=="") || (childrenDirection==classNames.at(i)))
                            readFromOMCWThread(newElement,depthMax,direction,curDepth+1);
                }
            }

            //read components
            if(readComponents)
            {
                QStringList compNames;
                QStringList compClasses;
                _moomc->getContainedComponents(parentClassName,compNames,compClasses,true);
                for(int i=0;i<compNames.size();i++)
                {
                    newElement = new ModComponent(_moomc,parent,prefix+compNames.at(i),compClasses.at(i));
                    if(addChild(parent,newElement))
                        if((childrenDirection=="") || (childrenDirection==compClasses.at(i)))
                            readFromOMCWThread(newElement,depthMax,direction,curDepth+1);
                }
            }
            parent->setChildrenReaden(true);
            parent->emitModified();


        }
        parent->_readMutex.unlock();
    }
}
示例#13
0
void NewGroupInner::updateFilter(QString filter) {
	QStringList f;
	if (!filter.isEmpty()) {
		QStringList filterList = filter.split(cWordSplit(), QString::SkipEmptyParts);
		int l = filterList.size();

		f.reserve(l);
		for (int i = 0; i < l; ++i) {
			QString filterName = filterList[i].trimmed();
			if (filterName.isEmpty()) continue;
			f.push_back(filterName);
		}
		filter = f.join(' ');
	}
	if (_filter != filter) {
		int32 rh = (st::profileListPhotoSize + st::profileListPadding.height() * 2);
		_filter = filter;
		if (_filter.isEmpty()) {
			resize(width(), _contacts->list.count * rh);
			if (_contacts->list.count) {
				_sel = _contacts->list.begin;
			}
		} else {
			QStringList::const_iterator fb = f.cbegin(), fe = f.cend(), fi;

			_filtered.clear();
			if (!f.isEmpty()) {
				DialogsList *dialogsToFilter = 0;
				if (_contacts->list.count) {
					for (fi = fb; fi != fe; ++fi) {
						DialogsIndexed::DialogsIndex::iterator i = _contacts->index.find(fi->at(0));
						if (i == _contacts->index.cend()) {
							dialogsToFilter = 0;
							break;
						}
						if (!dialogsToFilter || dialogsToFilter->count > i.value()->count) {
							dialogsToFilter = i.value();
						}
					}
				}
				if (dialogsToFilter && dialogsToFilter->count) {
					_filtered.reserve(dialogsToFilter->count);
					for (DialogRow *i = dialogsToFilter->begin, *e = dialogsToFilter->end; i != e; i = i->next) {
						const PeerData::Names &names(i->history->peer->names);
						PeerData::Names::const_iterator nb = names.cbegin(), ne = names.cend(), ni;
						for (fi = fb; fi != fe; ++fi) {
							QString filterName(*fi);
							for (ni = nb; ni != ne; ++ni) {
								if (ni->startsWith(*fi)) {
									break;
								}
							}
							if (ni == ne) {
								break;
							}
						}
						if (fi == fe) {
							i->attached = 0;
							_filtered.push_back(i);
						}
					}
				}
			}
			_filteredSel = _filtered.isEmpty() ? -1 : 0;

			resize(width(), _filtered.size() * rh);
		}
		if (parentWidget()) parentWidget()->update();
		loadProfilePhotos(0);
	}
}
示例#14
0
QgsPropertyDefinition QgsAuxiliaryLayer::propertyDefinitionFromField( const QgsField &f )
{
  QgsPropertyDefinition def;
  const QStringList parts = f.name().split( '_' );

  if ( parts.size() <= 1 )
    return def;

  const QString origin = parts[0];
  const QString propertyName = parts[1];

  if ( origin.compare( "labeling", Qt::CaseInsensitive ) == 0 )
  {
    const QgsPropertiesDefinition props = QgsPalLayerSettings::propertyDefinitions();
    for ( const QgsPropertyDefinition &p : props.values() )
    {
      if ( p.name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
      {
        def = p;
        if ( parts.size() == 3 )
          def.setComment( parts[2] );
        break;
      }
    }
  }
  else if ( origin.compare( "symbol", Qt::CaseInsensitive ) == 0 )
  {
    const QgsPropertiesDefinition props = QgsSymbolLayer::propertyDefinitions();
    for ( const QgsPropertyDefinition &p : props.values() )
    {
      if ( p.name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
      {
        def = p;
        if ( parts.size() == 3 )
          def.setComment( parts[2] );
        break;
      }
    }
  }
  else if ( origin.compare( "diagram", Qt::CaseInsensitive ) == 0 )
  {
    const QgsPropertiesDefinition props = QgsDiagramLayerSettings::propertyDefinitions();
    for ( const QgsPropertyDefinition &p : props.values() )
    {
      if ( p.name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
      {
        def = p;
        if ( parts.size() == 3 )
          def.setComment( parts[2] );
        break;
      }
    }
  }
  else
  {
    def.setOrigin( origin );
    def.setName( propertyName );

    if ( parts.size() == 3 )
      def.setComment( parts[2] );
  }

  return def;
}
Playlist::Playlist(QWidget *parent) :
	QTableWidget(parent), track(-1)
{
	// Initialize values for the Header (label and horizontal resize mode)
	QStringList labels = (QStringList() << "#" << tr("Title") << tr("Album") << tr("Length") << tr("Artist") << tr("Rating") << tr("Year"));
	const QStringList untranslatedLabels = (QStringList() << "#" << "Title" << "Album" << "Length" << "Artist" << "Rating" << "Year");
	// Test: 0 = Fixed, n>0 = real ratio for each column
	const QList<int> ratios(QList<int>() << 0 << 5 << 4 << 1 << 3 << 0 << 0);

	this->setColumnCount(labels.size());
	this->setColumnHidden(5, true);
	this->setColumnHidden(6, true);
	this->setShowGrid(false);
	Settings *settings = Settings::getInstance();
	this->setStyleSheet(settings->styleSheet(this));
	this->verticalScrollBar()->setStyleSheet(settings->styleSheet(this->verticalScrollBar()));
	this->setAlternatingRowColors(settings->colorsAlternateBG());

	// Select only one row, not cell by cell
	this->setSelectionMode(QAbstractItemView::ExtendedSelection);
	this->setSelectionBehavior(QAbstractItemView::SelectRows);
	this->setItemDelegate(new NoFocusItemDelegate(this));

	/// test
	this->setAcceptDrops(true);

	verticalHeader()->setVisible(false);
	this->setHorizontalHeader(new QHeaderView(Qt::Horizontal, this));
	horizontalHeader()->setStyleSheet(settings->styleSheet(horizontalHeader()));
	horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
	horizontalHeader()->setHighlightSections(false);
	horizontalHeader()->setMovable(true);

	this->installEventFilter(horizontalHeader());

	// Context menu on header of columns
	QList<QAction*> actionColumns;
	columns = new QMenu(this);

	for (int i = 0; i < labels.size(); i++) {
		QString label = labels.at(i);
		QTableWidgetItem *item = new QTableWidgetItem(label);

		// Stores original text to switch between translations on the fly
		// Might evolve latter, start to be "unreadable"
		item->setData(Qt::UserRole+1, untranslatedLabels.at(i));
		item->setData(Qt::UserRole+2, ratios.at(i));
		this->setHorizontalHeaderItem(i, item);

		// Match actions with columns using index of labels
		QAction *actionColumn = new QAction(label, this);
		actionColumn->setData(i);
		actionColumn->setEnabled(actionColumn->text() != tr("Title"));
		actionColumn->setCheckable(true);
		actionColumn->setChecked(!isColumnHidden(i));
		actionColumns.append(actionColumn);

		// Then populate the context menu
		columns->addAction(actionColumn);
	}

	// Load columns state
	QByteArray state = settings->value("playlistColumnsState").toByteArray();
	if (!state.isEmpty()) {
		horizontalHeader()->restoreState(state);
		for (int i = 0; i < horizontalHeader()->count(); i++) {
			bool hidden = horizontalHeader()->isSectionHidden(i);
			setColumnHidden(i, hidden);
			columns->actions().at(i)->setChecked(!hidden);
		}
	}

	// Link this playlist with the Settings instance to change fonts at runtime
	connect(settings, SIGNAL(currentFontChanged()), this, SLOT(highlightCurrentTrack()));

	// Change track
	// no need to cast parent as a TabPlaylist instance
	connect(this, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), parent, SLOT(changeTrack(QTableWidgetItem*)));

	// Hide the selected column in context menu
	connect(horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showColumnsMenu(QPoint)));
	connect(columns, SIGNAL(triggered(QAction*)), this, SLOT(toggleSelectedColumn(QAction*)));
	connect(horizontalHeader(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(saveColumnsState(int,int,int)));
}
示例#16
0
int main(int argc, char *argv[])
{  
  QApplication::setApplicationName(LONG_NAME);
  QApplication::setApplicationVersion(VERSION);
  QApplication::setOrganizationName(ORG); 
  QApplication::setDesktopSettingsAware(true);
  QApplication app(argc, argv);   
  
  // make sure only one instance is running
  QLocalSocket* socket = new QLocalSocket();
  socket->connectToServer(SOCKET_NAME);
  bool b_connected = socket->waitForConnected(500);
  socket->abort();
  delete socket;  
  if (b_connected) { 
    qDebug() <<  QCoreApplication::translate("main.cpp", "Another running instance of CMST has been detected.  This instance is aborting");  
    return 1;
  }

  // setup the command line parser
  QCommandLineParser parser;
  parser.setApplicationDescription(QApplication::translate("main.cpp", "Connman System Tray.") );
  
  QCommandLineOption bypassState(QStringList() << "b" << "bypass-restore-state",
		QCoreApplication::translate("main.cpp", "Bypass restoring the window state if restoring window state is specified in the settings file.") );
  parser.addOption(bypassState);   
  
  QCommandLineOption bypassStartOptions(QStringList() << "B" << "bypass-start-options",
		QCoreApplication::translate("main.cpp", "Bypass restoring any start options in the settings file.") );
  parser.addOption(bypassStartOptions);  
  
  QCommandLineOption disableCounters(QStringList() << "c" << "disable-counters",
		QCoreApplication::translate("main.cpp", "[Experimental] Disable data counters.  May be used to minimize load on your system.") );
  parser.addOption(disableCounters);  
  
  QCommandLineOption disableTrayIcon(QStringList() << "d" << "disable-tray-icon",
		QCoreApplication::translate("main.cpp", "Disable the system tray icon.  May be needed for system trays not compliant with the Freedesktop.org system tray specification.") );
  parser.addOption(disableTrayIcon);  
 
  parser.addHelpOption();
  
  QCommandLineOption useIconTheme(QStringList() << "i" << "icon-theme",
		QCoreApplication::translate("main.cpp", "Use an icon theme from your system."),
		QCoreApplication::translate("main.cpp", "Icon Theme Name"),
		QString() );
  parser.addOption(useIconTheme); 
  
  QCommandLineOption logInputRequest(QStringList() << "l" << "log-input-request",
		QCoreApplication::translate("main.cpp", "Log the connman inputRequest for debugging purposes.") );
  parser.addOption(logInputRequest);

  QCommandLineOption startMinimized(QStringList() << "m" << "minimized",
		QCoreApplication::translate("main.cpp", "Start the GUI minimized in the system tray.") );
  parser.addOption(startMinimized);
     
  parser.addVersionOption();  
    
  QCommandLineOption waitTime(QStringList() << "w" << "wait-time",
		QCoreApplication::translate("main.cpp", "Specify the wait time in seconds before starting the system tray icon."),
		QCoreApplication::translate("main.cpp", "seconds"),
		"0");
  parser.addOption(waitTime); 

  QCommandLineOption counterUpdateKb (QStringList() << "counter-update-kb",
		QCoreApplication::translate("main.cpp", "[Experimental] The number of kb that have to be transmitted before the counter updates."),
		QCoreApplication::translate("main.cpp", "KB"),
		"1024" );
  parser.addOption(counterUpdateKb);

  QCommandLineOption counterUpdateRate (QStringList() << "counter-update-rate",
		QCoreApplication::translate("main.cpp", "[Experimental] The interval in seconds between counter updates."),
		QCoreApplication::translate("main.cpp", "seconds"),
		"10" );
  parser.addOption(counterUpdateRate);

	// Added on 2015.01.04 to work around QT5.4 bug with transparency not always working
  QCommandLineOption fakeTransparency(QStringList() << "fake-transparency",
		QCoreApplication::translate("main.cpp", "If tray icon fake transparency is required, specify the background color to use (format: 0xRRGGBB)"),
		QCoreApplication::translate("main.cpp", "RRGGBB"),
		"0x222222" );
  parser.addOption(fakeTransparency); 

  // Added on 2014.11.24 to work around a bug where QT5.3 won't show an icon in XFCE,  My fix may not work, but keep it in for now.  If this gets fixed in 
  // QT5.4 keep the command line option so users start up commands don't break, but make it a NOP. 
  QCommandLineOption useXFCE(QStringList() << "use-xfce",
		QCoreApplication::translate("main.cpp", "Use XFCE specific code.") );
  parser.addOption(useXFCE);   
  
  // Added on 2014.12.16 to work around a similar bug where QT5.3 won't show an icon in MATE.   
  QCommandLineOption useMATE(QStringList() << "use-mate",
		QCoreApplication::translate("main.cpp", "Use MATE DE specific code.") );
  parser.addOption(useMATE); 
  
  // Setup translations   
  QTranslator qtTranslator;
  qtTranslator.load("qt_" + QLocale::system().name(),
  QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  app.installTranslator(&qtTranslator);

  QTranslator cmstTranslator;
  if (cmstTranslator.load("cmst_" + QLocale::system().name(), ":/translations/translations" ) ) {  
		app.installTranslator(&cmstTranslator);	
	}
	// else use en_US as it contains Connman strings properized and some singular/plural strings
	else if (cmstTranslator.load("cmst_en_US", ":/translations/translations" ) ) {
		app.installTranslator(&cmstTranslator);	
	}
 	
  // Make sure all the command lines can be parsed 
  // using parse() instead of process() as process stops on an error if an option needs a value
  // and it is not specified, even if we provide a default.  We're supposed to catch errors if we
  // use parse(), but parse.errorText() returns an empty string on this.  Bag the error checking
  // for now.
  parser.parse(QCoreApplication::arguments() );   
  QStringList sl = parser.unknownOptionNames();
  if (sl.size() > 0 ) parser.showHelp(1);
  if (parser.isSet("help") ) parser.showHelp(1);
  if (parser.isSet("version") ) parser.showVersion();
                
  // signal handler             
  signal(SIGINT, signalhandler);                
             
  // Showing the dialog (or not) is controlled in the createSystemTrayIcon() function
  // called from the ControlBox constructor.  We don't show it from here.             
  ControlBox ctlbox(parser);
  return app.exec(); 
}
示例#17
0
void NetTree::customEvent(QEvent *event)
{
    if (event->type() == ThumbnailDLEvent::kEventType)
    {
        ThumbnailDLEvent *tde = (ThumbnailDLEvent *)event;

        if (!tde)
            return;

        ThumbnailData *data = tde->thumb;

        if (!data)
            return;

        QString title = data->title;
        QString file = data->url;
        uint pos = qVariantValue<uint>(data->data);

        if (file.isEmpty())
            return;

        if (m_type == DLG_TREE)
        {
            if (title == m_siteMap->GetCurrentNode()->GetText() &&
                m_thumbImage)
            {
                m_thumbImage->SetFilename(file);
                m_thumbImage->Load();
                m_thumbImage->Show();
            }
        }
        else
        {
            if (!((uint)m_siteButtonList->GetCount() >= pos))
            {
                delete data;
                return;
            }

            MythUIButtonListItem *item =
                      m_siteButtonList->GetItemAt(pos);

            if (item && item->GetText() == title)
            {
                item->SetImage(file);
            }
        }

        delete data;
    }
    else if (event->type() == kGrabberUpdateEventType)
    {
        doTreeRefresh();
    }
    else if ((MythEvent::Type)(event->type()) == MythEvent::MythEventMessage)
    {
        MythEvent *me = (MythEvent *)event;
        QStringList tokens = me->Message().split(" ", QString::SkipEmptyParts);

        if (tokens.isEmpty())
            return;

        if (tokens[0] == "DOWNLOAD_FILE")
        {
            QStringList args = me->ExtraDataList();
            if ((tokens.size() != 2) ||
                (args[1] != m_downloadFile))
                return;

            if (tokens[1] == "UPDATE")
            {
                QString message = tr("Downloading Video...\n"
                                     "(%1 of %2 MB)")
                                     .arg(QString::number(args[2].toInt() / 1024.0 / 1024.0, 'f', 2))
                                     .arg(QString::number(args[3].toInt() / 1024.0 / 1024.0, 'f', 2));
                m_progressDialog->SetMessage(message);
                m_progressDialog->SetTotal(args[3].toInt());
                m_progressDialog->SetProgress(args[2].toInt());
            }
            else if (tokens[1] == "FINISHED")
            {
                int fileSize  = args[2].toInt();
                int errorCode = args[4].toInt();

                if (m_progressDialog)
                    m_progressDialog->Close();

                QFileInfo file(m_downloadFile);
                if ((m_downloadFile.startsWith("myth://")))
                {
                    if ((errorCode == 0) &&
                        (fileSize > 0))
                    {
                        doPlayVideo(m_downloadFile);
                    }
                    else
                    {
                        ShowOkPopup(tr("Error downloading video to backend."));
                    }
                }
            }
        }
    }

}
示例#18
0
int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<QgsSnappingResult>& results, const QList<QgsPoint>& excludePoints )
{
  results.clear();

  if ( !mSnapper )
    return 5;

  //topological editing on?
  int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );

  //snapping on intersection on?
  int intersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 );

  if ( topologicalEditing == 0 )
  {
    if ( intersectionSnapping == 0 )
      mSnapper->setSnapMode( QgsSnapper::SnapWithOneResult );
    else
      mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances );
  }
  else if ( intersectionSnapping == 0 )
  {
    mSnapper->setSnapMode( QgsSnapper::SnapWithResultsForSamePosition );
  }
  else
  {
    mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances );
  }

  //read snapping settings from project
  bool snappingDefinedInProject, ok;
  QStringList layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &snappingDefinedInProject );
  QStringList enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok );
  QStringList toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok );
  QStringList toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok );
  QStringList snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok );

  if ( !( layerIdList.size() == enabledList.size() &&
          layerIdList.size() == toleranceList.size() &&
          layerIdList.size() == toleranceUnitList.size() &&
          layerIdList.size() == snapToList.size() ) )
  {
    // lists must have the same size, otherwise something is wrong
    return 1;
  }

  QList<QgsSnapper::SnapLayer> snapLayers;
  QgsSnapper::SnapLayer snapLayer;

  // Use snapping information from the project
  if ( snappingDefinedInProject )
  {
    // set layers, tolerances, snap to segment/vertex to QgsSnapper
    QStringList::const_iterator layerIt( layerIdList.constBegin() );
    QStringList::const_iterator tolIt( toleranceList.constBegin() );
    QStringList::const_iterator tolUnitIt( toleranceUnitList.constBegin() );
    QStringList::const_iterator snapIt( snapToList.constBegin() );
    QStringList::const_iterator enabledIt( enabledList.constBegin() );
    for ( ; layerIt != layerIdList.constEnd(); ++layerIt, ++tolIt, ++tolUnitIt, ++snapIt, ++enabledIt )
    {
      if ( *enabledIt != "enabled" )
      {
        // skip layer if snapping is not enabled
        continue;
      }

      //layer
      QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( QgsMapLayerRegistry::instance()->mapLayer( *layerIt ) );
      if ( !vlayer || !vlayer->hasGeometryType() )
        continue;

      snapLayer.mLayer = vlayer;

      //tolerance
      snapLayer.mTolerance = tolIt->toDouble();
      snapLayer.mUnitType = ( QgsTolerance::UnitType ) tolUnitIt->toInt();

      // segment or vertex
      if ( *snapIt == "to_vertex" )
      {
        snapLayer.mSnapTo = QgsSnapper::SnapToVertex;
      }
      else if ( *snapIt == "to_segment" )
      {
        snapLayer.mSnapTo = QgsSnapper::SnapToSegment;
      }
      else
      {
        // to vertex and segment
        snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment;
      }

      snapLayers.append( snapLayer );
    }
  }
  else
  {
    // nothing in project. Use default snapping tolerance to vertex of current layer
    QgsMapLayer* currentLayer = mMapCanvas->currentLayer();
    if ( !currentLayer )
      return 2;

    QgsVectorLayer* currentVectorLayer = qobject_cast<QgsVectorLayer *>( currentLayer );
    if ( !currentVectorLayer )
      return 3;

    snapLayer.mLayer = currentVectorLayer;

    //default snap mode
    QSettings settings;
    QString defaultSnapString = settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString();
    if ( defaultSnapString == "to segment" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToSegment;
    }
    else if ( defaultSnapString == "to vertex and segment" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment;
    }
    else if ( defaultSnapString == "to vertex" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToVertex;
    }
    else
    {
      return 0;
    }

    //default snapping tolerance (returned in map units)
    snapLayer.mTolerance = QgsTolerance::defaultTolerance( currentVectorLayer, mMapCanvas->mapSettings() );
    snapLayer.mUnitType = QgsTolerance::MapUnits;

    snapLayers.append( snapLayer );
  }

  mSnapper->setSnapLayers( snapLayers );

  if ( mSnapper->snapPoint( point, results, excludePoints ) != 0 )
    return 4;

  if ( intersectionSnapping != 1 )
    return 0;

  QList<QgsSnappingResult> segments;
  QList<QgsSnappingResult> points;
  for ( QList<QgsSnappingResult>::const_iterator it = results.constBegin();
        it != results.constEnd();
        ++it )
  {
    if ( it->snappedVertexNr == -1 )
    {
      QgsDebugMsg( "segment" );
      segments.push_back( *it );
    }
    else
    {
      QgsDebugMsg( "no segment" );
      points.push_back( *it );
    }
  }

  if ( segments.length() < 2 )
    return 0;

  QList<QgsSnappingResult> myResults;

  for ( QList<QgsSnappingResult>::const_iterator oSegIt = segments.constBegin();
        oSegIt != segments.constEnd();
        ++oSegIt )
  {
    QgsDebugMsg( QString::number( oSegIt->beforeVertexNr ) );

    QVector<QgsPoint> vertexPoints;
    vertexPoints.append( oSegIt->beforeVertex );
    vertexPoints.append( oSegIt->afterVertex );

    QgsGeometry* lineA = QgsGeometry::fromPolyline( vertexPoints );

    for ( QList<QgsSnappingResult>::iterator iSegIt = segments.begin();
          iSegIt != segments.end();
          ++iSegIt )
    {
      QVector<QgsPoint> vertexPoints;
      vertexPoints.append( iSegIt->beforeVertex );
      vertexPoints.append( iSegIt->afterVertex );
      QgsGeometry* lineB = QgsGeometry::fromPolyline( vertexPoints );

      QgsGeometry* intersectionPoint = lineA->intersection( lineB );
      if ( intersectionPoint->type()  == QGis::Point )
      {
        //We have to check the intersection point is inside the tolerance distance for both layers
        double toleranceA = 0;
        double toleranceB = 0;
        for ( int i = 0 ;i < snapLayers.size();++i )
        {
          if ( snapLayers[i].mLayer == oSegIt->layer )
          {
            toleranceA = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType );
          }
          if ( snapLayers[i].mLayer == iSegIt->layer )
          {
            toleranceB = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType );
          }
        }
        QgsGeometry* cursorPoint = QgsGeometry::fromPoint( point );
        double distance = intersectionPoint->distance( *cursorPoint );
        if ( distance < toleranceA && distance < toleranceB )
        {
          iSegIt->snappedVertex = intersectionPoint->asPoint();
          myResults.append( *iSegIt );
        }
      }
    }
  }

  if ( myResults.length() > 0 )
  {
    results.clear();
    results = myResults;
  }

  return 0;
}
示例#19
0
void ControlWidget::handleSatellite( const QByteArray &msg )
{
   QStringList src( Satellite::split( msg ) );

   if( src.size() > 0 )
   {
      if( src.at(0) == "P0Q" )
      {
         QStringList dest;

         /* convert from url to filename if necessary */
         for( int i = 1; i < src.size(); i++ )
         {
            QFileInfo qfi( src.at(i) );
            if( qfi.isFile() )
            {
               dest << qfi.absoluteFilePath();
            }
         }

         if( dest.size() > 0 )
         {
            emit requestAddToPlaylist( dest, false );
         }
      }

      else if( src.at(0) == "P0A" )
      {
         if( mConnected )
         {
            if( mPaused || !mKioskMode )
            {
               handlePause();
            }
         }
         else
         {
            initConnect();
         }
      }

      else if( src.at(0) == "P0N" )
      {
         handleSkipTrack();
      }

      else if( src.at(0) == "P0S" )
      {
         if( !mKioskMode )
         {
            initDisconnect();
         }
      }

      else if( src.at(0) == "P0R" )
      {
         if( mpSatellite && !mLastP0p.isEmpty() )
         {
            mpSatellite->send( mLastP0p );
         }
      }

      else if( src.at(0) == "P0C" )
      {
         bool favorite = false;
         bool unwanted = false;
         if( src.size() > 1 )
         {
            switch( src.at(1).toUInt() )
            {
               case 1:
                  favorite = true;
                  break;
               case 2:
                  unwanted = true;
                  break;
               default:
                  break;
            }
            mpPlaylist->setTrackInfoFavoriteUnwanted( favorite, unwanted );
         }
      }

      else if( src.at(0) == "P0T" )
      {
         if( src.size() > 1 )
         {
            emit requestTab( src.at(1) );
         }
      }

      else if( (src.at(0) == "k0u") ||
               (src.at(0) == "r0u") )
      {
         emit trackUpdate();
      }

      else if( src.at(0) == "u0p" )
      {
         if( Settings::value( Settings::PartymanStopOnUnderpassStart ) && !mKioskMode )
         {
            initDisconnect();
         }
      }
   }
}
示例#20
0
void QgsSvgCache::replaceElemParams( QDomElement& elem, const QColor& fill, const QColor& outline, double outlineWidth )
{
  if ( elem.isNull() )
  {
    return;
  }

  //go through attributes
  QDomNamedNodeMap attributes = elem.attributes();
  int nAttributes = attributes.count();
  for ( int i = 0; i < nAttributes; ++i )
  {
    QDomAttr attribute = attributes.item( i ).toAttr();
    //e.g. style="fill:param(fill);param(stroke)"
    if ( attribute.name().compare( "style", Qt::CaseInsensitive ) == 0 )
    {
      //entries separated by ';'
      QString newAttributeString;

      QStringList entryList = attribute.value().split( ';' );
      QStringList::const_iterator entryIt = entryList.constBegin();
      for ( ; entryIt != entryList.constEnd(); ++entryIt )
      {
        QStringList keyValueSplit = entryIt->split( ':' );
        if ( keyValueSplit.size() < 2 )
        {
          continue;
        }
        QString key = keyValueSplit.at( 0 );
        QString value = keyValueSplit.at( 1 );
        if ( value.startsWith( "param(fill" ) )
        {
          value = fill.name();
        }
        else if ( value.startsWith( "param(outline)" ) )
        {
          value = outline.name();
        }
        else if ( value.startsWith( "param(outline-width)" ) )
        {
          value = QString::number( outlineWidth );
        }

        if ( entryIt != entryList.constBegin() )
        {
          newAttributeString.append( ";" );
        }
        newAttributeString.append( key + ":" + value );
      }
      elem.setAttribute( attribute.name(), newAttributeString );
    }
    else
    {
      QString value = attribute.value();
      if ( value.startsWith( "param(fill)" ) )
      {
        elem.setAttribute( attribute.name(), fill.name() );
      }
      else if ( value.startsWith( "param(outline)" ) )
      {
        elem.setAttribute( attribute.name(), outline.name() );
      }
      else if ( value.startsWith( "param(outline-width)" ) )
      {
        elem.setAttribute( attribute.name(), QString::number( outlineWidth ) );
      }
    }
  }

  QDomNodeList childList = elem.childNodes();
  int nChildren = childList.count();
  for ( int i = 0; i < nChildren; ++i )
  {
    QDomElement childElem = childList.at( i ).toElement();
    replaceElemParams( childElem, fill, outline, outlineWidth );
  }
}
示例#21
0
// Constructor
NNotebookView::NNotebookView(QWidget *parent) :
    QTreeWidget(parent)
{
    stackStore.clear();
    dataStore.clear();
    this->setFont(global.getGuiFont(font()));

    filterPosition = -1;
    maxCount = 0;  // Highest count of any notebook.  Used in calculating column width
    // setup options
    this->setEditTriggers(QAbstractItemView::NoEditTriggers);
    this->setSelectionBehavior(QAbstractItemView::SelectRows);
    this->setSelectionMode(QAbstractItemView::SingleSelection);
    this->setRootIsDecorated(true);
    this->setSortingEnabled(false);
    this->header()->setVisible(false);
    this->setStyleSheet("QTreeView {border-image:none; image:none;} ");
    root = new NNotebookViewItem(0);
    root->setType(NNotebookViewItem::Stack);
    root->setData(NAME_POSITION, Qt::UserRole, "rootsynchronized");
    root->setData(NAME_POSITION, Qt::DisplayRole, tr("Notebooks"));
    QFont rootFont = root->font(NAME_POSITION);
    rootFont.setBold(true);
    root->setFont(NAME_POSITION, rootFont);

    root->setRootColor(false);

    this->setMinimumHeight(1);
    this->addTopLevelItem(root);
    this->rebuildNotebookTreeNeeded = true;
    this->loadData();
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    connect(this, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(calculateHeight()));
    connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem*)), this, SLOT(calculateHeight()));
    connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(buildSelection()));

    addAction = context.addAction(tr("Create New Notebook"));
    addAction->setShortcut(QKeySequence(Qt::Key_Insert));
    addAction->setShortcutContext(Qt::WidgetShortcut);

    addShortcut = new QShortcut(this);
    addShortcut->setKey(QKeySequence(Qt::Key_Insert));
    addShortcut->setContext(Qt::WidgetShortcut);

    context.addSeparator();
    deleteAction = context.addAction(tr("Delete"));
    deleteAction->setShortcut(QKeySequence(Qt::Key_Delete));

    deleteShortcut = new QShortcut(this);
    deleteShortcut->setKey(QKeySequence(Qt::Key_Delete));
    deleteShortcut->setContext(Qt::WidgetShortcut);

    // Start building the stack menu
    stackMenu = context.addMenu(tr("Add to stack"));
    QAction *newAction;
    NotebookTable table(global.db);
    QStringList stacks;
    table.getStacks(stacks);
    for (int i=0; i<stacks.size(); i++) {
        newAction = stackMenu->addAction(stacks[i]);
        connect(newAction, SIGNAL(triggered()), this, SLOT(moveToStackRequested()));
    }
    sortStackMenu();
    if (stacks.size() > 0) {
        stackMenu->addSeparator();
    }
    newStackAction = stackMenu->addAction(tr("New stack"));
    connect(newStackAction, SIGNAL(triggered()), this, SLOT(moveToNewStackRequested()));

    removeFromStackAction = context.addAction(tr("Remove from stack"));
    removeFromStackAction->setShortcutContext(Qt::WidgetShortcut);
    removeFromStackAction->setVisible(false);

    renameAction = context.addAction(tr("Rename"));
    renameAction->setShortcutContext(Qt::WidgetShortcut);

    //renameShortcut = new QShortcut(this);
    //renameShortcut->setKey(QKeySequence(Qt::Key_F2));
    //renameShortcut->setContext(Qt::WidgetShortcut);

    context.addSeparator();
    propertiesAction = context.addAction(tr("Properties"));

    connect(addAction, SIGNAL(triggered()), this, SLOT(addRequested()));
    connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteRequested()));
    connect(renameAction, SIGNAL(triggered()), this, SLOT(renameRequested()));
    connect(propertiesAction, SIGNAL(triggered()), this, SLOT(propertiesRequested()));

    connect(addShortcut, SIGNAL(activated()), this, SLOT(addRequested()));
    connect(deleteShortcut, SIGNAL(activated()), this, SLOT(deleteRequested()));
    //connect(renameShortcut, SIGNAL(activated()), this, SLOT(renameRequested()));
    connect(removeFromStackAction, SIGNAL(triggered()), this, SLOT(removeFromStackRequested()));

    this->setAcceptDrops(true);
    this->setItemDelegate(new NNotebookViewDelegate());
    root->setExpanded(true);
    this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
    this->setFrameShape(QFrame::NoFrame);


    //setStyle(new MyStyle("QTreeView"));
//    setStyle(new QCleanlooksStyle);
    //setStyleSheet("::branches {image: url(:right-arrow.png);}");

//    setStyleSheet("QTreeView::branch { image: url(:right-arrow.png); }");

    expandedImage = new QImage(":expandedIcon");
    collapsedImage = new QImage(":collapsedIcon");
}
示例#22
0
void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillParam, QColor& defaultFill, bool& hasOutlineParam, QColor& defaultOutline,
                                      bool& hasOutlineWidthParam, double& defaultOutlineWidth ) const
{
  if ( elem.isNull() )
  {
    return;
  }

  //we already have all the information, no need to go deeper
  if ( hasFillParam && hasOutlineParam && hasOutlineWidthParam )
  {
    return;
  }

  //check this elements attribute
  QDomNamedNodeMap attributes = elem.attributes();
  int nAttributes = attributes.count();

  QStringList valueSplit;
  for ( int i = 0; i < nAttributes; ++i )
  {
    QDomAttr attribute = attributes.item( i ).toAttr();
    if ( attribute.name().compare( "style", Qt::CaseInsensitive ) == 0 )
    {
      //entries separated by ';'
      QStringList entryList = attribute.value().split( ';' );
      QStringList::const_iterator entryIt = entryList.constBegin();
      for ( ; entryIt != entryList.constEnd(); ++entryIt )
      {
        QStringList keyValueSplit = entryIt->split( ':' );
        if ( keyValueSplit.size() < 2 )
        {
          continue;
        }
        QString key = keyValueSplit.at( 0 );
        QString value = keyValueSplit.at( 1 );
        valueSplit = value.split( " " );
        if ( !hasFillParam && value.startsWith( "param(fill)" ) )
        {
          hasFillParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultFill = QColor( valueSplit.at( 1 ) );
          }
        }
        else if ( !hasOutlineParam && value.startsWith( "param(outline)" ) )
        {
          hasOutlineParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultOutline = QColor( valueSplit.at( 1 ) );
          }
        }
        else if ( !hasOutlineWidthParam && value.startsWith( "param(outline-width)" ) )
        {
          hasOutlineWidthParam = true;
          if ( valueSplit.size() > 1 )
          {
            defaultOutlineWidth = valueSplit.at( 1 ).toDouble();
          }
        }
      }
    }
    else
    {
      QString value = attribute.value();
      valueSplit = value.split( " " );
      if ( !hasFillParam && value.startsWith( "param(fill)" ) )
      {
        hasFillParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultFill = QColor( valueSplit.at( 1 ) );
        }
      }
      else if ( !hasOutlineParam && value.startsWith( "param(outline)" ) )
      {
        hasOutlineParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultOutline = QColor( valueSplit.at( 1 ) );
        }
      }
      else if ( !hasOutlineWidthParam && value.startsWith( "param(outline-width)" ) )
      {
        hasOutlineWidthParam = true;
        if ( valueSplit.size() > 1 )
        {
          defaultOutlineWidth = valueSplit.at( 1 ).toDouble();
        }
      }
    }
  }

  //pass it further to child items
  QDomNodeList childList = elem.childNodes();
  int nChildren = childList.count();
  for ( int i = 0; i < nChildren; ++i )
  {
    QDomElement childElem = childList.at( i ).toElement();
    containsElemParams( childElem, hasFillParam, defaultFill, hasOutlineParam, defaultOutline, hasOutlineWidthParam, defaultOutlineWidth );
  }
}
示例#23
0
QImage Plotter::makeHistro()
{
  QImage img= QImage(width,height,QImage::Format_RGB32);
  img.fill(0xffffff);
  QPainter painter(&img);
  painter.setFont(QFont(painter.font().family(),_fs));

  float step_x=float(width/(_text_x.length()+1));
  float max = float(scriptEngine->evaluate("Math.max.apply( Math, results );").toNumber());
  float step_y=float(height)/max;

  float ident_right=step_x/2;
  float ident_left=ident_right;
  float ident_top=step_y+_fs*2;
  float ident_bottom=step_y+_fs*2;

  int dataCount = scriptEngine->evaluate("results.length").toInt32();
  step_x=(width-ident_left-ident_right)/float(dataCount);
  step_y=(height-ident_bottom-ident_top)/max;

  QVector<QRectF> rects;
  QStringList text_up;
  QList<QPointF> text_up_pos;
  QList<QPointF> text_down_pos;

  QFontMetrics metrics=QFontMetrics(painter.font());
  QString num;
  for(int i=0; i<dataCount; i++)
  {

    QScriptValue index = QScriptValue(i);
    scriptEngine->globalObject().setProperty("index",index);
    float curResult = (float)scriptEngine->evaluate("results[index]").toNumber();

    rects.append(QRectF(ident_left+i*step_x,height-(ident_bottom+curResult*step_y),step_x,curResult*step_y));
    num.setNum(curResult);
    text_up_pos.append(QPointF(ident_left+i*step_x+step_x/2-metrics.width(num)/2,height-(ident_bottom+curResult*step_y-_fs-_fs/2)));
    text_down_pos.append(QPointF(ident_left+i*step_x+step_x/2-metrics.width(_text_x[i])/2,height-ident_bottom+1.5*_fs));

    num.setNum(curResult);
    text_up.append(num);
  }

  QLine max_line;
  QString max_text=QString::fromUtf8("Максимум: ");
  QPointF max_text_pos;
  if(_maximum!=0)
  {
    if(_maximum<max)
      _maximum=max;
    max_line=QLine(ident_left,height-_maximum*step_y-ident_bottom,width-ident_right,height-_maximum*step_y-ident_bottom);
    num.setNum(_maximum);
    max_text.append(num);
    max_text_pos=QPointF(width/2-metrics.width(max_text)/2,height-_maximum*step_y-_fs/2-ident_bottom);
  }

  QPen pen=QPen(Qt::black,2);
  QBrush brush1=QBrush(Qt::lightGray);
  QBrush brush2=QBrush(Qt::lightGray);
  if(_difcol==true)
    brush2=QBrush(Qt::gray);

  painter.setPen(pen);
  painter.setBrush(brush1);

  QStringList sl = _text_x.split(";",QString::SkipEmptyParts,Qt::CaseSensitive);

  for(int i=0; i<rects.size(); i++)
  {
    if(_difcol==true)
    {
      if(i%2==0)//если чётное
        painter.setBrush(brush1);
      else if(i%2!=0)
        painter.setBrush(brush2);

      painter.drawRect(rects[i]);
    }
    if(i<sl.size())
      painter.drawText(text_down_pos[i],QString(sl[i]));

    painter.drawText(text_up_pos[i],QString(text_up[i]));
  }

  if(_difcol==false)
    painter.drawRects(rects);

  if(_maximum!=0)
  {
    painter.drawLine(max_line);
    painter.drawText(max_text_pos,max_text);
  }

  return img;
}
示例#24
0
QString Script::handleSetFixture(const QList<QStringList>& tokens, QList<Universe *> universes)
{
    qDebug() << Q_FUNC_INFO;

    if (tokens.size() > 4)
        return QString("Too many arguments");

    bool ok = false;
    quint32 id = 0;
    quint32 ch = 0;
    uchar value = 0;
    double time = 0;

    id = tokens[0][1].toUInt(&ok);
    if (ok == false)
        return QString("Invalid fixture (ID: %1)").arg(tokens[0][1]);

    for (int i = 1; i < tokens.size(); i++)
    {
        QStringList list = tokens[i];
        list[0] = list[0].toLower().trimmed();
        if (list.size() == 2)
        {
            ok = false;
            if (list[0] == "val" || list[0] == "value")
                value = uchar(list[1].toUInt(&ok));
            else if (list[0] == "ch" || list[0] == "channel")
                ch = list[1].toUInt(&ok);
            else if (list[0] == "time")
                time = list[1].toDouble(&ok);
            else
                return QString("Unrecognized keyword: %1").arg(list[0]);

            if (ok == false)
                return QString("Invalid value (%1) for keyword: %2").arg(list[1]).arg(list[0]);
        }
    }

    Doc* doc = qobject_cast<Doc*> (parent());
    Q_ASSERT(doc != NULL);

    Fixture* fxi = doc->fixture(id);
    if (fxi != NULL)
    {
        if (ch < fxi->channels())
        {
            int address = fxi->address() + ch;
            if (address < 512)
            {
                GenericFader* gf = fader();
                Q_ASSERT(gf != NULL);

                FadeChannel fc;
                fc.setFixture(doc, fxi->id());
                fc.setChannel(ch);
                fc.setTarget(value);
                fc.setFadeTime(time);

                // If the script has used the channel previously, it might still be in
                // the bowels of GenericFader so get the starting value from there.
                // Otherwise get it from universes (HTP channels are always 0 then).
                quint32 uni = fc.universe();
                if (gf->channels().contains(fc) == true)
                    fc.setStart(gf->channels()[fc].current());
                else
                    fc.setStart(universes[uni]->preGMValue(address));
                fc.setCurrent(fc.start());

                gf->add(fc);

                return QString();
            }
            else
            {
                return QString("Invalid address: %1").arg(address);
            }
        }
        else
        {
            return QString("Fixture (%1) has no channel number %2").arg(fxi->name()).arg(ch);
        }
    }
    else
    {
        return QString("No such fixture (ID: %1)").arg(id);
    }
}
示例#25
0
UIDnDDataObject::UIDnDDataObject(CSession &session,
                                 CDnDSource &dndSource,
                                 const QStringList &lstFormats,
                                 QWidget *pParent)
    : mSession(session),
      mDnDSource(dndSource),
      mpParent(pParent),
      mStatus(Uninitialized),
      mRefCount(1),
      mcFormats(0),
      mpFormatEtc(NULL),
      mpStgMedium(NULL),
      mpvData(NULL),
      mcbData(0)
{
    HRESULT hr;

    ULONG cMaxFormats = 16; /* Maximum number of registered formats. */
    ULONG cRegisteredFormats = 0;

    try
    {
        mpFormatEtc = new FORMATETC[cMaxFormats];
        RT_BZERO(mpFormatEtc, sizeof(FORMATETC) * cMaxFormats);
        mpStgMedium = new STGMEDIUM[cMaxFormats];
        RT_BZERO(mpStgMedium, sizeof(STGMEDIUM) * cMaxFormats);

        for (int i = 0;
             (   i < lstFormats.size()
              && i < cMaxFormats); i++)
        {
            const QString &strFormat = lstFormats.at(i);
            if (mlstFormats.contains(strFormat))
                continue;

            /* URI data ("text/uri-list"). */
            if (strFormat.contains("text/uri-list", Qt::CaseInsensitive))
            {
                RegisterFormat(&mpFormatEtc[cRegisteredFormats], CF_TEXT);
                mpStgMedium[cRegisteredFormats++].tymed = TYMED_HGLOBAL;
                RegisterFormat(&mpFormatEtc[cRegisteredFormats], CF_UNICODETEXT);
                mpStgMedium[cRegisteredFormats++].tymed = TYMED_HGLOBAL;
                RegisterFormat(&mpFormatEtc[cRegisteredFormats], CF_HDROP);
                mpStgMedium[cRegisteredFormats++].tymed = TYMED_HGLOBAL;

                mlstFormats << strFormat;
            }
            /* Plain text ("text/plain"). */
            else if (strFormat.contains("text/plain", Qt::CaseInsensitive))
            {
                RegisterFormat(&mpFormatEtc[cRegisteredFormats], CF_TEXT);
                mpStgMedium[cRegisteredFormats++].tymed = TYMED_HGLOBAL;
                RegisterFormat(&mpFormatEtc[cRegisteredFormats], CF_UNICODETEXT);
                mpStgMedium[cRegisteredFormats++].tymed = TYMED_HGLOBAL;

                mlstFormats << strFormat;
            }
        }

        LogFlowFunc(("Total registered native formats: %RU32 (for %d formats from guest)\n",
                     cRegisteredFormats, lstFormats.size()));
        hr = S_OK;
    }
    catch (std::bad_alloc &)
    {
        hr = E_OUTOFMEMORY;
    }

    if (SUCCEEDED(hr))
    {
        int rc2 = RTSemEventCreate(&mSemEvent);
        AssertRC(rc2);

        /*
         * Other (not so common) formats.
         */
#if 0
        /* IStream. */
        RegisterFormat(&mpFormatEtc[cFormats++],
                       RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR));
        RegisterFormat(&mpFormatEtc[cFormats++],
                       RegisterClipboardFormat(CFSTR_FILECONTENTS),
                       TYMED_ISTREAM, 0 /* lIndex */);

        /* Required for e.g. Windows Media Player. */
        RegisterFormat(&mpFormatEtc[cFormats++],
                       RegisterClipboardFormat(CFSTR_FILENAME));
        RegisterFormat(&mpFormatEtc[cFormats++],
                       RegisterClipboardFormat(CFSTR_FILENAMEW));
        RegisterFormat(&mpFormatEtc[cFormats++],
                       RegisterClipboardFormat(CFSTR_SHELLIDLIST));
        RegisterFormat(&mpFormatEtc[cFormats++],
                       RegisterClipboardFormat(CFSTR_SHELLIDLISTOFFSET));
#endif
        mcFormats = cRegisteredFormats;

        /* Put the object in the "dropped" state already. We don't need
         * to handle the other states here at the moment. */
        mStatus = Dropped;
    }

    LogFlowFunc(("hr=%Rhrc\n", hr));
}
boost::shared_ptr<PluginGroupNode>
GuiApplicationManagerPrivate::findPluginToolButtonInternal(const std::list<boost::shared_ptr<PluginGroupNode> >& children,
                                                           const boost::shared_ptr<PluginGroupNode>& parent,
                                                           const QStringList & grouping,
                                                           const QString & name,
                                                           const QStringList & groupingIcon,
                                                           const QString & iconPath,
                                                           int major,
                                                           int minor,
                                                           bool isUserCreatable)
{
    assert(grouping.size() > 0);
    assert( groupingIcon.size() == grouping.size() - 1 || groupingIcon.isEmpty() );

    for (std::list<boost::shared_ptr<PluginGroupNode> >::const_iterator it = children.begin(); it != children.end(); ++it) {
        if ( (*it)->getID() == grouping[0] ) {
            if (grouping.size() > 1) {
                QStringList newGrouping, newIconsGrouping;
                for (int i = 1; i < grouping.size(); ++i) {
                    newGrouping.push_back(grouping[i]);
                }
                for (int i = 1; i < groupingIcon.size(); ++i) {
                    newIconsGrouping.push_back(groupingIcon[i]);
                }

                return findPluginToolButtonInternal( (*it)->getChildren(), *it, newGrouping, name, newIconsGrouping, iconPath, major, minor, isUserCreatable );
            }
            if ( major == (*it)->getMajorVersion() ) {
                return *it;
            } else {
                (*it)->setNotHighestMajorVersion(true);
            }
        }
    }

    QString iconFilePath;
    if (grouping.size() > 1) {
        iconFilePath = groupingIcon.isEmpty() ? QString() : groupingIcon[0];
    } else {
        iconFilePath = iconPath;
    }
    boost::shared_ptr<PluginGroupNode> ret( new PluginGroupNode(grouping[0], grouping.size() == 1 ? name : grouping[0], iconFilePath, major, minor, isUserCreatable) );
    if (parent) {
        parent->tryAddChild(ret);
        ret->setParent(parent);
    } else {
        _topLevelToolButtons.push_back(ret);
    }

    if (grouping.size() > 1) {
        QStringList newGrouping, newIconsGrouping;
        for (int i = 1; i < grouping.size(); ++i) {
            newGrouping.push_back(grouping[i]);
        }
        for (int i = 1; i < groupingIcon.size(); ++i) {
            newIconsGrouping.push_back(groupingIcon[i]);
        }

        return findPluginToolButtonInternal(ret->getChildren(), ret, newGrouping, name, newIconsGrouping, iconPath, major, minor, isUserCreatable);
    }

    return ret;
} // GuiApplicationManagerPrivate::findPluginToolButtonInternal
示例#27
0
// Upload notes that belong to me
qint32 SyncRunner::uploadLinkedNotes(qint32 notebookLid) {
    QLOG_TRACE_IN();
    qint32 usn;
    qint32 maxUsn = 0;
    NoteTable noteTable(db);
    QList<qint32> lids, validLids, deletedLids;
    noteTable.getAllDirty(lids, notebookLid);

    // Split the list into deleted and updated notes
    for (int i = 0; i < lids.size(); i++) {
        if (noteTable.isDeleted(lids[i]))
            deletedLids.append(lids[i]);
        else
            validLids.append(lids[i]);
    }

    // Start deleting notes
    for (int i = 0; i < deletedLids.size(); i++) {
        QString guid = noteTable.getGuid(deletedLids[i]);
        noteTable.setDirty(lids[i], false);
        usn = comm->deleteLinkedNote(guid);
        if (usn > maxUsn) {
            maxUsn = usn;
            noteTable.setUpdateSequenceNumber(deletedLids[i], usn);
            noteTable.setDirty(deletedLids[i], false);
            if (!finalSync)
                emit(noteSynchronized(deletedLids[i], false));
        }
    }


    // Start deleting notes that were in the trash, but the trash was
    // emptied.
    NotebookTable bookTable(db);
    QString notebookGuid = "";
    bookTable.getGuid(notebookGuid, notebookLid);

    // Get all of the notes
    QStringList deleteQueueGuids;
    noteTable.getAllDeleteQueue(deleteQueueGuids, notebookGuid);


    // Do the actual deletes
    for (int i = 0; i < deleteQueueGuids.size(); i++) {
        QString guid = deleteQueueGuids[i];
        usn = comm->deleteLinkedNote(guid);
        if (usn > maxUsn) {
            maxUsn = usn;
        }
        noteTable.expungeFromDeleteQueue(guid);
    }


    // Start uploading notes
    for (int i = 0; i < validLids.size(); i++) {
        Note note;
        noteTable.get(note, validLids[i], true, true);
        qint32 oldUsn = note.updateSequenceNum;
        usn = comm->uploadLinkedNote(note);
        if (usn == 0) {
            this->communicationErrorHandler();
            error = true;
            QLOG_TRACE_OUT();
            return maxUsn;
        }
        if (usn > maxUsn) {
            maxUsn = usn;
            if (oldUsn == 0)
                noteTable.updateGuid(validLids[i], note.guid);
            noteTable.setUpdateSequenceNumber(validLids[i], usn);
            noteTable.setDirty(validLids[i], false);
            if (!finalSync)
                emit(noteSynchronized(validLids[i], false));
        } else {
            error = true;
        }
    }
    QLOG_TRACE_OUT();
    return maxUsn;
}
示例#28
0
void CumulativeConflator::conflate(const QStringList inputs, const QString output)
{
  assert(inputs.size() >= 3);

  //for NoInformationElementRemover
  if (ConfigOptions().getWriterCleanReviewTags())
  {
    throw HootException(
      "Multi-conflation must be run with " +
      ConfigOptions::getWriterCleanReviewTagsKey() + "=false");
  }

  //for TagMergerFactory
  if (ConfigOptions().getTagMergerDefault() != "hoot::ProvenanceAwareOverwriteTagMerger")
  {
    throw HootException(
      "Multi-conflation must be run with " + ConfigOptions::getTagMergerDefaultKey() +
      "=hoot::ProvenanceAwareOverwriteTagMerger");
  }

  OsmMapPtr cumulativeMap(new OsmMap());
  LOG_VARD(inputs.size());
  for (int i = 0; i < inputs.size(); i++)
  {
    OsmMapPtr reviewCache;
    if (i == 0)
    {
      OsmMapReaderFactory::read(
        cumulativeMap, inputs[i], ConfigOptions().getReaderConflateUseDataSourceIds1(),
        Status::Unknown1);

      //keep a source tag history on the data for provenance; append to any existing source values
      //(this shouldn't be added to any review relations)
      LOG_DEBUG("Setting source tags for map " << QString::number(i + 1) << "...");
      SetTagValueVisitor sourceTagVisitor(MetadataTags::HootSource(), QString::number(i + 1));
      cumulativeMap->visitRw(sourceTagVisitor);
    }
    else
    {
      if (i == 1)
      {
        LOG_INFO("Conflating " << inputs[i - 1] << " with " << inputs[i] << "...");
      }
      else
      {
        LOG_INFO("Conflating cumulative map with " << inputs[i] << "...");
      }

      //I'm not yet sure all the projecting going on here is the right way to go about this, but
      //the maps must be in the same projection for the appending to work.

      OsmMapPtr unknown2Map(new OsmMap());
      OsmMapReaderFactory::read(
        unknown2Map, inputs[i], ConfigOptions().getReaderConflateUseDataSourceIds2(),
        Status::Unknown2);
      MapProjector::projectToWgs84(unknown2Map);

      //Same as above, but do this before combining the cumulative map with the unknown2 map to
      //prevent incorrect tags from being added to the cumulative map.
      LOG_DEBUG("Setting source tags for map " << QString::number(i + 1) << "...");
      SetTagValueVisitor sourceTagVisitor(
        MetadataTags::HootSource(), QString::number(i + 1)/*, true*/);
      unknown2Map->visitRw(sourceTagVisitor);

      //now combine the two maps before conflation
      MapProjector::projectToWgs84(cumulativeMap);
      MapProjector::projectToWgs84(unknown2Map);
      cumulativeMap->append(unknown2Map);

      //load in cached reviews from previous conflations - I believe this is necessary, b/c the
      //UnifyingConflator is ignoring any incoming reviews by design (need to verify this).  It
      //could be argued that modifying it to optionally retain the reviews is a better design
      //than the caching going on here...
      if (reviewCache.get() && reviewCache->getElementCount() > 0)
      {
        LOG_DEBUG("Adding previous reviews...");
        const RelationMap& reviews = reviewCache->getRelations();
        for (RelationMap::const_iterator it = reviews.begin(); it != reviews.end(); ++it)
        {
          RelationPtr review = it->second;
          review->setId(cumulativeMap->createNextRelationId());
          cumulativeMap->addRelation(review);
        }
        LOG_DEBUG("Added " << reviews.size() << " cached reviews.");
      }

      NamedOp(ConfigOptions().getConflatePreOps()).apply(cumulativeMap);
      UnifyingConflator().apply(cumulativeMap);
      //going to apply this at the end of all conflation jobs, but maybe we'll find out later that
      //it needs to be done here instead (?)
      //NamedOp(ConfigOptions().getConflatePostOps()).apply(cumulativeMap);

      if (i < inputs.size() - 1)
      {
        //Up until just before the last conflate job, set the status tag back to 1 so that the
        //accumulated data will conflate with the next dataset.
        //there is a bug here that will affect river conflation in that somehow hoot:status=3
        //tags are being left in at some point which causes the SearchRadiusCalculator to skip the
        //features.
        LOG_DEBUG("Setting status tags for map " << QString::number(i + 1) << "...");
        SetTagValueVisitor statusTagVisitor(
          MetadataTags::HootStatus(), QString("%1").arg(Status(Status::Unknown1).getEnum()));
        cumulativeMap->visitRw(statusTagVisitor);
      }

      //copy the map and save the reviews
      LOG_DEBUG("Caching reviews...");
      reviewCache.reset(new OsmMap(cumulativeMap->getProjection()));
      KeepReviewsVisitor vis;
      reviewCache->visitRw(vis);
      LOG_DEBUG("Cached " << reviewCache->getElementCount() << " reviews.");
    }
  }

  NamedOp(ConfigOptions().getConflatePostOps()).apply(cumulativeMap);

  MapProjector::projectToWgs84(cumulativeMap);
  OsmMapWriterFactory::write(cumulativeMap, output);
}
示例#29
0
void MiningPage::readProcessOutput()
{
    QByteArray output;

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

    if (!outputString.isEmpty())
    {
        QStringList list = outputString.split("\n", QString::SkipEmptyParts);
        int i;
        for (i=0; i<list.size(); i++)
        {
            QString line = list.at(i);

            // Ignore protocol dump
            if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr"))
                continue;

            if (ui->debugCheckBox->isChecked())
            {
                ui->list->addItem(line.trimmed());
                ui->list->scrollToBottom();
            }

            if (line.contains("(yay!!!)"))
                reportToList("Share accepted", SHARE_SUCCESS, getTime(line));
            else if (line.contains("(booooo)"))
                reportToList("Share rejected", SHARE_FAIL, getTime(line));
            else if (line.contains("LONGPOLL detected new block"))
                reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line));
            else if (line.contains("Supported options:"))
                reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL);
            else if (line.contains("The requested URL returned error: 403"))
                reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL);
            else if (line.contains("HTTP request failed"))
                reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL);
            else if (line.contains("JSON-RPC call failed"))
                reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL);
            else if (line.contains("thread ") && line.contains("khash/s"))
            {
                QString threadIDstr = line.at(line.indexOf("thread ")+7);
                int threadID = threadIDstr.toInt();

                int threadSpeedindx = line.indexOf(",");
                QString threadSpeedstr = line.mid(threadSpeedindx);
                threadSpeedstr.chop(8);
                threadSpeedstr.remove(", ");
                threadSpeedstr.remove(" ");
                threadSpeedstr.remove('\n');
                double speed=0;
                speed = threadSpeedstr.toDouble();

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}
示例#30
0
/**
 * Try to resolve the specified class the current class depends on.
 * @param className  the name of the class
 */
UMLObject* CSharpImport::resolveClass(const QString& className)
{
    uDebug() << "trying to resolve " << className;
    // keep track if we are dealing with an array
    bool isArray = className.contains('[');
    // remove any [] so that the class itself can be resolved
    QString baseClassName = className;
    baseClassName.remove('[');
    baseClassName.remove(']');

    // java has a few implicit imports.  Most relevant for this is the
    // current package, which is in the same directory as the current file
    // being parsed
    QStringList file = m_currentFileName.split('/');
    // remove the filename.  This leaves the full path to the containing
    // dir which should also include the package hierarchy
    file.pop_back();

    // the file we're looking for might be in the same directory as the
    // current class
    QString myDir = file.join("/");
    QString myFile = myDir + '/' + baseClassName + ".cs";
    if (QFile::exists(myFile)) {
        spawnImport(myFile);
        if (isArray) {
            // we have imported the type. For arrays we want to return
            // the array type
            return Import_Utils::createUMLObject(UMLObject::ot_Class, className, m_scope[m_scopeIndex]);
        }
        return findObject(baseClassName, m_scope[m_scopeIndex]);
    }

    // the class we want is not in the same package as the one being imported.
    // use the imports to find the one we want.
    QStringList package = m_currentPackage.split('.');
    int dirsInPackageCount = package.size();

    for (int count = 0; count < dirsInPackageCount; ++count) {
        // pop off one by one the directories, until only the source root remains
        file.pop_back();
    }
    // this is now the root of any further source imports
    QString sourceRoot = file.join("/") + '/';

    for (QStringList::Iterator pathIt = m_imports.begin();
            pathIt != m_imports.end(); ++pathIt) {
        QString import = (*pathIt);
        QStringList split = import.split('.');
        split.pop_back(); // remove the * or the classname
        if (import.endsWith('*') || import.endsWith(baseClassName)) {
            // check if the file we want is in this imported package
            // convert the org.test type package into a filename
            QString aFile = sourceRoot + split.join("/") + '/' + baseClassName + ".cs";
            if (QFile::exists(aFile)) {
                spawnImport(aFile);
                // we need to set the package for the class that will be resolved
                // start at the root package
                UMLPackage *parent = m_scope[0];
                UMLPackage *current = NULL;

                for (QStringList::Iterator it = split.begin(); it != split.end(); ++it) {
                    QString name = (*it);
                    UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package,
                                    name, parent);
                    current = static_cast<UMLPackage*>(ns);
                    parent = current;
                } // for
                if (isArray) {
                    // we have imported the type. For arrays we want to return
                    // the array type
                    return Import_Utils::createUMLObject(UMLObject::ot_Class, className, current);
                }
                // now that we have the right package, the class should be findable
                return findObject(baseClassName, current);
            } // if file exists
        } // if import matches
    } //foreach import
    return NULL; // no match
}