Ejemplo n.º 1
0
//OKAY LETS GET REAL HERE
//for now lets just try to create a single patch
QList<LappedPatch*>* LappedUtils::generatePatches(GLMmodel* model, polyHull* polyhull)
{

    //*************REFERENCE PSEUDOCODE*************************************
    //PREPROCESSING:
    //Convert entire model into our format.  I know this is goofy but its only done once and makes it easier.

    //For each triangle:
    //make a PatchTri
    //populate vertices - make sure not a repeat by hashing
    //add this triangle to the vert ;)
    //populate edges - make sure not a repeat by hashing
    //add this triangle to the edge ;)


    //choose seed triangle, get center point
    //for now, tangent equals vo--->v1  (should be curvature!)
    //assign UVS to PatchTri s.t. centered at .5,.5 and tangent is aligned with texture //HOW???? NEED BITANGENT OR NO?  HOW TO DETERMINE SCALE?
    //enqueue edges of triangle

    //make our patchlist to return!

    //WHILE MESH IS NOT COVERED:

    //make visitedSets of edges, verts, tris
    //mark everything from seed as visited

    //while Q not empty
    //dequeue edge e
    //find other triangle in edge
    //if tri is not in patch
    //if e isects hull  //see struct polyHull::isectUV
    //if homeomorphic to a disc (new vert not in patch OR only 1 edge not in patch)
    //if new vert already in patch
    //just add triangle to patch!
    //enqueue new edges of triangle
    //and mark them as visited, as well as new tri itself
    //else need to add vert:
    //estimate parametrization of new vert like so:
    //for each triangle containing vert and an already-mapped edge
    //stick a similar triangle onto that edge, and see where the corresponding location of vert is
    //take average of those guys as UV for new vert
    //then add triangle like above: enq new edges, mark any new edges, vert, tri as visited
    //patch is done, delete visitedSets, continue to next patch

    //mesh is covered (or we stopped making patches for whatever reason

    //return patch list!

    //*****************OKAY LETS ACTUALLY IMPLEMENT IT******************************
    QList<LappedPatch*>* PatchList = new QList<LappedPatch*>();
    //PREPROCESSING
    GLMtriangle* glmtris = model->triangles;
    GLfloat* glmverts = model->vertices;
    QHash<GLuint,PatchVert*>* vertsMade = new QHash<GLuint,PatchVert*>();
    QHash<QPair<PatchVert*,PatchVert*>,PatchEdge*>* edgesMade = new QHash<QPair<PatchVert*,PatchVert*>,PatchEdge*>();
    PatchTri** trisMade = new PatchTri*[model->numtriangles];

    QList<PatchTri*>* trisInNOPatch = new QList<PatchTri*>();

    for(int i=0;i<model->numtriangles;i++)
    {
        PatchTri* pt = new PatchTri();
        trisInNOPatch->append(pt);
        trisMade[i] = pt;
        pt->GLMtri = &glmtris[i];
        pt->tangent.x = model->triCurvatures[i*3];
        pt->tangent.y = model->triCurvatures[i*3+1];
        pt->tangent.z = model->triCurvatures[i*3+2];
        pt->tangent.w = 1;

        //make/find PatchVerts for new triangle
        for(int vi=0;vi<3;vi++)
        {
            PatchVert* v;
            if(vertsMade->contains(pt->GLMtri->vindices[vi]))
            {
                v = vertsMade->value(pt->GLMtri->vindices[vi]);
                v->tris->append(pt);
            }
            else
            {
                v = new PatchVert();
                vertsMade->insert(pt->GLMtri->vindices[vi],v);
                v->tris = new QList<PatchTri*>();
                v->GLMidx = pt->GLMtri->vindices[vi];
                v->pos.x = glmverts[3* v->GLMidx];
                v->pos.y = glmverts[3* v->GLMidx+1];
                v->pos.z = glmverts[3* v->GLMidx+2];
                v->tris->append(pt);
                vertsMade->insert(v->GLMidx,v);
            }
            switch(vi)
            {
            case 0:
                pt->v0=v;
                break;
            case 1:
                pt->v1=v;
                break;
            case  2:
                pt->v2=v;
                break;
            }
        }

        QPair<PatchVert*,PatchVert*> e01, e12, e20;
        e01 = qMakePair(pt->v0,pt->v1);
        e12 = qMakePair(pt->v1,pt->v2);
        e20 = qMakePair(pt->v2,pt->v0);
        //should triangles have pointers to their edges?
        if(edgesMade->contains(e01))
        {
            PatchEdge* e = edgesMade->value(e01);
            e->addTri(pt);
            pt->e01 = e;
        }
        else
        {
            PatchEdge* e = new PatchEdge(pt->v0, pt->v1);
            edgesMade->insert(e01,e);
            edgesMade->insert(qMakePair(pt->v1,pt->v0),e);
            e->addTri(pt);
            pt->e01=e;
        }
        if(edgesMade->contains(e12))
        {
            PatchEdge* e = edgesMade->value(e12);
            e->addTri(pt);
            pt->e12=e;
        }
        else
        {
            PatchEdge* e = new PatchEdge(pt->v1, pt->v2);
            edgesMade->insert(e12,e);
            edgesMade->insert(qMakePair(pt->v2,pt->v1),e);
            e->addTri(pt);
            pt->e12=e;
        }
        if(edgesMade->contains(e20))
        {
            PatchEdge* e = edgesMade->value(e20);
            e->addTri(pt);
            pt->e20=e;
        }
        else
        {
            PatchEdge* e = new PatchEdge(pt->v2, pt->v0);
            edgesMade->insert(e20,e);
            edgesMade->insert(qMakePair(pt->v0,pt->v2),e);
            e->addTri(pt);
            pt->e20=e;
        }
    }//OK TRIANGLES MADE


    //WHILE MESH IS NOT COVERED******
    //for(int wtf=0; wtf<20; wtf++)//***
    int wtf;
    while(!trisInNOPatch->empty())// && wtf<150)
    {                           //***
        //WHILE MESH IS NOT COVERED******
        //cout<<"Patch "<< wtf<<endl;
        wtf++;


        //choose seed triangle, get center point
        //for now, tangent equals vo--->v1  (should be curvature!)
        //assign UVS to PatchTri s.t. centered at .5,.5 and tangent is aligned with texture //HOW???? NEED BITANGENT OR NO?  HOW TO DETERMINE SCALE?
        //enqueue edges of triangle

        //DONT DELETE THESE THINGS!
        //hash table of uvs for this specific patch!
        QHash<PatchVert*,vec2<float> >* UVs = new QHash<PatchVert*, vec2<float> >();
        //list of Tris for this specific patch!
        QList<PatchTri*>* PTris = new QList<PatchTri*>();
        //seed for this specific patch!
        //PatchTri* seed = trisMade[0];//rand()%model->numtriangles];
        PatchTri* seed = trisInNOPatch->at(0);
        //trisInNOPatch->removeFirst();


        vec2<float> seedUV0, seedUV1, seedUV2;
        assignSeedUV(seed, seedUV0, seedUV1, seedUV2);
        UVs->insert(seed->v0,seedUV0);
        UVs->insert(seed->v1,seedUV1);
        UVs->insert(seed->v2,seedUV2);

        QQueue<PatchEdge*>* edgeQ = new QQueue<PatchEdge*>();
        edgeQ->enqueue(seed->e01);
        edgeQ->enqueue(seed->e12);
        edgeQ->enqueue(seed->e20);

        //make visitedSets of edges, verts, tris
        //mark everything from seed as visited
        QSet<PatchVert*>* vertsInPatch = new QSet<PatchVert*>();
        QSet<PatchEdge*>* edgesInPatch = new QSet<PatchEdge*>();
        QSet<PatchTri*>* trisInPatch = new QSet<PatchTri*>();
        vertsInPatch->insert(seed->v0);
        vertsInPatch->insert(seed->v1);
        vertsInPatch->insert(seed->v2);
        edgesInPatch->insert(seed->e01);
        edgesInPatch->insert(seed->e12);
        edgesInPatch->insert(seed->e20);
        trisInPatch->insert(seed);
        trisInNOPatch->removeAll(seed);
        PTris->append(seed);
        //cout<<"PTris size init: "<<PTris->size()<<endl;

        //while Q not empty
        //dequeue edge e
        //find other triangle in edge
        //if tri is not in patch
        //if e isects hull  //see struct polyHull::isectUV
        //if homeomorphic to a disc (new vert not in patch OR only 1 edge not in patch)
        //if new vert already in patch
        //just add triangle to patch!
        //enqueue new edges of triangle
        //and mark them as visited, as well as new tri itself
        //else need to add vert:
        //estimate parametrization of new vert like so:
        //for each triangle containing vert and an already-mapped edge
        //stick a similar triangle onto that edge, and see where the corresponding location of vert is
        //take average of those guys as UV for new vert
        //then add triangle like above: enq new edges, mark any new edges, vert, tri as visited
        //patch is done, delete visitedSets, continue to next patch
        int fucktris = 0;
        while((!edgeQ->isEmpty()))// && fucktris < 3)
        {
            fucktris++;
            PatchEdge* e = edgeQ->dequeue();
            PatchTri* otherTri;
            if(trisInPatch->contains(e->t1))
            {
                if(e->ntris==2 && !trisInPatch->contains(e->t2))
                {
                    otherTri = e->t2;
                }
                else
                {
                    //cout<<"both tris already in patch or edge only has one tri"<<endl;
                    continue;
                }
            }
            else if(e->ntris>=1)
            {
                otherTri = e->t1;
            }
            else
            {
                // cout<<"edge somehow has no triangles"<<endl;
                continue;
            }

            //if e isects hull
            vec2<float> uv1 = UVs->value(e->v0);
            vec2<float> uv2 = UVs->value(e->v1);
            if(polyhull->isectHullUV(uv1.x,uv1.y,uv2.x,uv2.y))
            {
                PatchEdge* newEdge;//only relevant if theres only one
                PatchVert* newvert = otherTri->otherVert(e->v0, e->v1);
                //if homeomorphic to a disk
                bool newvertinpatch = vertsInPatch->contains(newvert);
                int numNewEdgesInPatch=0;
                if(!edgesInPatch->contains(otherTri->e01)){
                    numNewEdgesInPatch++;
                    newEdge=otherTri->e01;}
                if(!edgesInPatch->contains(otherTri->e12)){
                    numNewEdgesInPatch++;
                    newEdge=otherTri->e12;}
                if(!edgesInPatch->contains(otherTri->e20)){
                    numNewEdgesInPatch++;
                    newEdge=otherTri->e20;}
                if( !newvertinpatch || numNewEdgesInPatch==1)
                {
                    if(newvertinpatch)
                    {//just add the triangle/edges!
                        edgesInPatch->insert(newEdge);
                        trisInPatch->insert(otherTri);
                        //if(polyhull->fullyInside(otherTri, UVs))
                            trisInNOPatch->removeAll(otherTri);
                        PTris->append(otherTri);
                        edgeQ->enqueue(newEdge);
                    }
                    else
                    {//gotta add the new vertex
                        //estimate parametrization of new vert like so:
                        //for each triangle containing vert and an already-mapped edge
                        //stick a similar triangle onto that edge, and see where the corresponding location of vert is
                        //take average of those guys as UV for new vert
                        //then add triangle like above: enq new edges, mark any new edges, vert, tri as visited

                        vec2<float> sumUVs = vec2<float>(0,0);
                        int numUVs=0;
                        for(int ti=0; ti<newvert->tris->size(); ti++)
                        {
                            PatchTri* curtri = newvert->tris->at(ti);
                            PatchEdge* mappedE;
                            PatchVert *_A,*_B;//args to estimateUV
                            if(edgesInPatch->contains(curtri->e01))
                            {
                                assert(newvert == curtri->v2);
                                mappedE = curtri->e01;
                                _A = curtri->v0;
                                _B = curtri->v1;
                            }
                            else if(edgesInPatch->contains(curtri->e12))
                            {
                                assert(newvert == curtri->v0);
                                mappedE = curtri->e12;
                                _A = curtri->v1;
                                _B = curtri->v2;
                            }
                            else if(edgesInPatch->contains(curtri->e20))
                            {
                                assert(newvert == curtri->v1);
                                mappedE = curtri->e20;
                                _A = curtri->v2;
                                _B = curtri->v0;
                            }
                            else
                                continue;
                            numUVs++;
                            vec2<float> badguy = UVs->value( mappedE->otherTri(curtri)->otherVert(mappedE->v0,mappedE->v1));
                            vec2<float>* Ast = new vec2<float>(); Ast->x = UVs->value(_A).x; Ast->y = UVs->value(_A).y;
                            vec2<float>* Bst = new vec2<float>(); Bst->x = UVs->value(_B).x; Bst->y = UVs->value(_B).y;
                            sumUVs = sumUVs + estimateUV(_A,_B,newvert, Ast, Bst,&badguy);
                        }
                        //sumUVs is actually now the UVs we want
                        sumUVs = sumUVs / (numUVs);
                        //add all the crap
                        UVs->insert(newvert,sumUVs);
                        vertsInPatch->insert(newvert);
                        trisInPatch->insert(otherTri);
                        //if(polyhull->fullyInside(otherTri, UVs))
                            trisInNOPatch->removeAll(otherTri);
                        if(!edgesInPatch->contains(otherTri->e01))
                        {edgesInPatch->insert(otherTri->e01);
                            edgeQ->enqueue(otherTri->e01);}
                        if(!edgesInPatch->contains(otherTri->e12))
                        {edgesInPatch->insert(otherTri->e12);
                            edgeQ->enqueue(otherTri->e12);}
                        if(!edgesInPatch->contains(otherTri->e20))
                        {edgesInPatch->insert(otherTri->e20);
                            edgeQ->enqueue(otherTri->e20);}
                        PTris->append(otherTri);
                        /*
                        double size = 500;
                        QImage* testOut = new QImage((int)size,(int)size,QImage::Format_ARGB32);
                        testOut->fill(1);
                        QPainter painter(testOut);
                        painter.setPen(Qt::red);
                        painter.setBrush(Qt::red);
                        for (int tri=0;tri<PTris->size();tri++)
                        {
                            PatchTri* pt = PTris->at(tri);
                            painter.drawLine(UVs->value(pt->v0).x*size , UVs->value(pt->v0).y*size , UVs->value(pt->v1).x*size, UVs->value(pt->v1).y*size);
                            painter.drawLine(UVs->value(pt->v1).x*size , UVs->value(pt->v1).y*size , UVs->value(pt->v2).x*size , UVs->value(pt->v2).y*size);
                            painter.drawLine(UVs->value(pt->v0).x*size,UVs->value(pt->v0).y*size,UVs->value(pt->v2).x*size,UVs->value(pt->v2).y*size);
                        }
                        */

                    }
                }
            }//endif isectHull
            /*
            double size = 500;
            QImage* testOut = new QImage((int)size,(int)size,QImage::Format_ARGB32);
            testOut->fill(1);
            QPainter painter(testOut);
            painter.setPen(Qt::red);
            painter.setBrush(Qt::red);
            for (int tri=0;tri<PTris->size();tri++)
            {
                PatchTri* pt = PTris->at(tri);
                painter.setPen(getColorIfIntersect(UVs->value(pt->v0),UVs->value(pt->v1),polyhull));
                painter.drawLine(UVs->value(pt->v0).x*size , UVs->value(pt->v0).y*size , UVs->value(pt->v1).x*size, UVs->value(pt->v1).y*size);
                painter.setPen(getColorIfIntersect(UVs->value(pt->v1),UVs->value(pt->v2),polyhull));
                painter.drawLine(UVs->value(pt->v1).x*size , UVs->value(pt->v1).y*size , UVs->value(pt->v2).x*size , UVs->value(pt->v2).y*size);
                painter.setPen(getColorIfIntersect(UVs->value(pt->v0),UVs->value(pt->v2),polyhull));
                painter.drawLine(UVs->value(pt->v0).x*size, UVs->value(pt->v0).y*size,UVs->value(pt->v2).x*size,UVs->value(pt->v2).y*size);
                painter.setPen(Qt::blue);
                painter.drawLine((UVs->value(pt->v0).x+UVs->value(pt->v1).x)/2*size,(UVs->value(pt->v0).y+UVs->value(pt->v1).y)/2*size,UVs->value(pt->v2).x*size,UVs->value(pt->v2).y*size);
                painter.setPen(Qt::red);
            }
            int iii = 0;
            testOut->save("TESTTHIS.png");
            int iiiii = 0;*/

        }//endwhile Q!Empty

        //PTris, UVs, seed should be sufficient to define patch!
        LappedPatch* newPatch = new LappedPatch();
        newPatch->tris = PTris;
        /*for (int ptt=0;ptt<PTris->size();ptt++)
        {
            printPatchTri3d(newPatch->tris->at(ptt));
        }*/
        //cout<<"PTris size end: "<<PTris->size()<<endl;
        newPatch->seed = seed;
        newPatch->uvs = UVs;
        PatchList->append(newPatch);


        //delete temporary stupid stuff
        delete edgeQ;
        delete edgesInPatch;
        delete vertsInPatch;
        delete trisInPatch;


        //ENDWHILE MESH NOT COVERED*
    }                       //**
    //ENDWHILE MESH NOT COvERED*


    //stuff from beginning to delete
    delete trisInNOPatch;
    //should just delete redundant pointers
    delete[] trisMade;
    delete vertsMade;
    delete edgesMade;


    LappedOrient LO;
    for(int i=0; i<PatchList->size();i++)
    {
       // LO.orientTexture(PatchList->at(i));
    }

    return PatchList;
}
void AsemanQtTools::registerTypes(const char *uri, bool exportMode)
{
    static QSet<QByteArray> register_list;
    if(register_list.contains(uri) && !exportMode)
        return;
    qRegisterMetaType<AsemanMimeData*>("AsemanMimeData*");

    registerType<AsemanMimeData>(uri, 1, 0, "MimeData", exportMode);
    registerType<AsemanDragObject>(uri, 1, 0, "DragObject", exportMode);
    registerType<AsemanHashObject>(uri, 1,0, "HashObject", exportMode);
    registerType<AsemanListObject>(uri, 1,0, "ListObject", exportMode);
    registerType<AsemanDownloader>(uri, 1,0, "Downloader", exportMode);
    registerType<AsemanEncrypter>(uri, 1,0, "Encrypter", exportMode);
#ifndef DISABLE_KEYCHAIN
    registerType<AsemanKeychain>(uri, 1,0, "Keychain", exportMode);
#endif
#ifdef QT_WIDGETS_LIB
    registerType<AsemanSystemTray>(uri, 1,0, "SystemTray", exportMode);
#endif
    registerType<AsemanWindowDetails>(uri, 1,0, "WindowDetails", exportMode);
    registerType<AsemanQuickObject>(uri, 1,0, "AsemanObject", exportMode);
    registerType<AsemanImageColorAnalizor>(uri, 1,0, "ImageColorAnalizor", exportMode);
    registerType<AsemanNotification>(uri, 1,0, "Notification", exportMode);
    registerType<AsemanAutoStartManager>(uri, 1,0, "AutoStartManager", exportMode);
    registerType<AsemanSettings>(uri, 1,0, "Settings", exportMode);
    registerType<AsemanStoreManager>(uri, 1,0, "StoreManager", exportMode);
    registerType<AsemanQuickItemImageGrabber>(uri, 1,0, "ItemImageGrabber", exportMode);
    registerType<AsemanFileDownloaderQueueItem>(uri, 1,0, "FileDownloaderQueueItem", exportMode);
    registerType<AsemanFileDownloaderQueue>(uri, 1,0, "FileDownloaderQueue", exportMode);
    registerType<AsemanFontHandler>(uri, 1,0, "FontHandler", exportMode);
    registerType<AsemanApplicationItem>(uri, 1,0, "AsemanApplication", exportMode);
    registerType<AsemanQmlSmartComponent>(uri, 1,0, "SmartComponentCore", exportMode);
#ifdef DESKTOP_LINUX
    registerType<AsemanMimeApps>(uri, 1,0, "MimeApps", exportMode);
#endif
    registerType<AsemanWebPageGrabber>(uri, 1,0, "WebPageGrabber", exportMode);
    registerType<AsemanHostChecker>(uri, 1,0, "HostChecker", exportMode);
    registerType<AsemanNetworkManager>(uri, 1,0, "NetworkManager", exportMode);
    registerType<AsemanNetworkSleepManager>(uri, 1,0, "NetworkSleepManager", exportMode);
    registerType<AsemanTitleBarColorGrabber>(uri, 1,0, "TitleBarColorGrabber", exportMode);
    registerType<AsemanTaskbarButton>(uri, 1,0, "TaskbarButton", exportMode);
    registerType<AsemanMapDownloader>(uri, 1,0, "MapDownloader", exportMode);
    registerType<AsemanDragArea>(uri, 1,0, "MouseDragArea", exportMode);
    registerType<AsemanCalendarModel>(uri, 1,0, "CalendarModel", exportMode);
#if defined(Q_OS_LINUX) && defined(QT_DBUS_LIB)
    registerType<AsemanKdeWallet>(uri, 1,0, "KdeWallet", exportMode);
#endif

#ifdef ASEMAN_SENSORS
    registerType<AsemanSensors>(uri, 1,0, "AsemanSensors", exportMode);
#endif
#ifdef ASEMAN_MULTIMEDIA
    registerType<AsemanAudioRecorder>(uri, 1,0, "AudioRecorder", exportMode);
    registerType<AsemanAudioEncoderSettings>(uri, 1,0, "AudioEncoderSettings", exportMode);
#endif

    registerModel<AsemanMixedListModel>(uri, 1,0, "MixedListModel", exportMode);
    registerModel<AsemanCountriesModel>(uri, 1,0, "CountriesModel", exportMode);
    registerModel<AsemanFileSystemModel>(uri, 1,0, "FileSystemModel", exportMode);
    registerModel<AsemanStoreManagerModel>(uri, 1,0, "StoreManagerModel", exportMode);
    registerModel<AsemanContributorsModel>(uri, 1,0, "ContributorsModel", exportMode);

    registerSingletonType<AsemanDevices>(uri, 1, 0, "Devices", aseman_devices_singleton, exportMode);
    registerSingletonType<AsemanTextTools>(uri, 1, 0, "TextTools", aseman_text_tools_singleton, exportMode);
    registerSingletonType<AsemanTools>(uri, 1, 0, "Tools", aseman_tools_singleton, exportMode);
    registerSingletonType<AsemanDesktopTools>(uri, 1, 0, "Desktop", aseman_desktoptools_singleton, exportMode);
    registerSingletonType<AsemanCalendarConverter>(uri, 1, 0, "CalendarConv", aseman_calendarconv_singleton, exportMode);
    registerSingletonType<AsemanBackHandler>(uri, 1, 0, "BackHandler", aseman_backhandler_singleton, exportMode);
    registerSingletonType<AsemanApplication>(uri, 1, 0, "AsemanApp", aseman_app_singleton, exportMode);
    registerSingletonType<AsemanQtLogger>(uri, 1, 0, "Logger", aseman_logger_singleton, exportMode);
    registerSingletonType<AsemanQuickViewWrapper>(uri, 1, 0, "View", aseman_qview_singleton, exportMode);
#ifdef Q_OS_ANDROID
    registerSingletonType<AsemanJavaLayer>(uri, 1, 0, "JavaLayer", aseman_javalayer_singleton, exportMode);
#endif

    registerUncreatableType<QScreen>(uri, 1, 0, "Screen", "", exportMode);
    registerUncreatableType<AsemanDesktopTools>(uri, 1,0, "AsemanDesktopTools", "It's a singleton class", exportMode);
    registerUncreatableType<AsemanNetworkManagerItem>(uri, 1,0, "NetworkManagerItem", "It must create using NetworkManager component.", exportMode);

    register_list.insert(uri);
}
Ejemplo n.º 3
0
bool PorkSendPage::threeLine(int x0, int x1, int y0, int y1)
{
    int i;
    bool ret;

    //横向扫描
    for(i = 0; i < map_col; i++)
    {
         lines.clear();
        if(i == y0 || arr_map[x0][i] != EMPTY)
         continue;
        ret = oneHLine(x0,y0,i);
        if(ret)
        {
            ret = twoLine(x0,x1,i,y1,ret);
            if(ret)
            {
                QSet<QPoint> s;
                for(int i=0;i<lines.size();i++)
                {
                    QLine line=lines[i];
                  //  line.p1();
                    s.insert(line.p1());
                    s.insert(line.p2());
                }

                if(s.size()==5)
                {
                    printf("%d",s.size());
                    lines.removeAt(1);

                }

                return true;
            }
        }
    }
 lines.clear();
    //纵向扫描
    for(i = 0; i < map_row; i++)
    { lines.clear();
        if(i == x0 || arr_map[i][y0] != EMPTY)
         continue;
        ret = oneVLine(y0,x0,i);
        if(ret)
        {
            ret = twoLine(i,x1,y0,y1,ret);
            if(ret)
            {

                //  drawLine(i,y0,i,y1);
               //  drawLine(x0,y0,x1,y0);
                // drawLine(i,y1,x1,y1);

                return true;
            }
        }
    }

    return false;
}
Ejemplo n.º 4
0
/**
 * FASTQ format specification: http://maq.sourceforge.net/fastq.shtml
 */
static void load(IOAdapter* io, const U2DbiRef& dbiRef, const QVariantMap& hints, QList<GObject*>& objects, U2OpStatus& os,
                 int gapSize, int predictedSize, QString& writeLockReason, QMap<QString, QString>& skippedLines) {
    DbiOperationsBlock opBlock(dbiRef, os);
    CHECK_OP(os, );
    Q_UNUSED(opBlock);
    writeLockReason.clear();

    bool merge = gapSize!=-1;
    QByteArray sequence;
    QByteArray qualityScores;
    QStringList headers;
    QSet<QString> uniqueNames;

    QVector<U2Region> mergedMapping;
    QByteArray gapSequence((merge ? gapSize : 0), 0);
    sequence.reserve(predictedSize);
    qualityScores.reserve(predictedSize);

    // for lower case annotations
    GObjectReference sequenceRef;
    qint64 sequenceStart = 0;

    U2SequenceImporter seqImporter(hints, true);
    const QString folder = hints.value(DocumentFormat::DBI_FOLDER_HINT, U2ObjectDbi::ROOT_FOLDER).toString();
    int seqNumber = 0;
    int progressUpNum = 0;


    const int objectsCountLimit = hints.contains(DocumentReadingMode_MaxObjectsInDoc) ? hints[DocumentReadingMode_MaxObjectsInDoc].toInt() : -1;
    const bool settingsMakeUniqueName = !hints.value(DocumentReadingMode_DontMakeUniqueNames, false).toBool();
    while (!os.isCoR()) {
        U2OpStatus2Log warningOs;

        //read header
        QString sequenceName = readSequenceName(warningOs, io, '@');
        // check for eof while trying to read another FASTQ block
        if (io->isEof()) {
            if (io->hasError()) {
                os.setError(io->errorString());
            }
            break;
        }

        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            continue;
        }

        if(sequenceName.isEmpty()){
            sequenceName = "Sequence";
        }

        if ((merge == false) || (seqNumber == 0)) {
            QString objName = sequenceName;
            if (settingsMakeUniqueName) {
                objName = (merge) ? "Sequence" : TextUtils::variate(sequenceName, "_", uniqueNames);
                objName.squeeze();
                uniqueNames.insert(objName);
            }
            seqImporter.startSequence(warningOs, dbiRef, folder, objName, false);
            if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
                U2OpStatusImpl seqOs;
                seqImporter.finalizeSequenceAndValidate(seqOs);
                continue;
            }
        }

        //read sequence
        if (merge && sequence.length() > 0) {
            seqImporter.addDefaultSymbolsBlock(gapSize, warningOs);
            sequenceStart += sequence.length();
            sequenceStart+=gapSize;
            if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
                U2OpStatusImpl seqOs;
                seqImporter.finalizeSequenceAndValidate(seqOs);
                continue;
            }
        }

        sequence.clear();
        readSequence(warningOs, io, sequence);
        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            U2OpStatusImpl seqOs;
            seqImporter.finalizeSequenceAndValidate(seqOs);
            continue;
        }
        MemoryLocker lSequence(os, qCeil(sequence.size()/(1000*1000)));
        CHECK_OP_BREAK(os);
        Q_UNUSED(lSequence);

        seqImporter.addBlock(sequence.data(),sequence.length(), warningOs);
        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            U2OpStatusImpl seqOs;
            seqImporter.finalizeSequenceAndValidate(seqOs);
            continue;
        }

        QString qualSequenceName = readSequenceName(warningOs, io, '+');
        if (!qualSequenceName.isEmpty()) {
            if (sequenceName != qualSequenceName){
                warningOs.setError(U2::FastqFormat::tr("Sequence name differs from quality scores name: %1 and %2").arg(sequenceName).arg(qualSequenceName));
            }
            if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
                U2OpStatusImpl seqOs;
                seqImporter.finalizeSequenceAndValidate(seqOs);
                continue;
            }
        }

        // read qualities
        qualityScores.clear();
        readQuality(warningOs, io, qualityScores, sequence.size());
        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            U2OpStatusImpl seqOs;
            seqImporter.finalizeSequenceAndValidate(seqOs);
            continue;
        }

        if(sequence.length() != qualityScores.length()){
            warningOs.setError(U2::FastqFormat::tr("Bad quality scores: inconsistent size."));
        }
        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            U2OpStatusImpl seqOs;
            seqImporter.finalizeSequenceAndValidate(seqOs);
            continue;
        }


        seqNumber++;
        progressUpNum++;
        if (merge) {
            headers.append(sequenceName);
            mergedMapping.append(U2Region(sequenceStart, sequence.length() ));
        }
        else {
            if (objectsCountLimit > 0 && objects.size() >= objectsCountLimit) {
                os.setError(FastqFormat::tr("File \"%1\" contains too many sequences to be displayed. "
                    "However, you can process these data using instruments from the menu <i>Tools -> NGS data analysis</i> "
                    "or pipelines built with Workflow Designer.")
                    .arg(io->getURL().getURLString()));
                break;
            }

            U2Sequence u2seq = seqImporter.finalizeSequenceAndValidate(warningOs);
            if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
                continue;
            }
            sequenceRef = GObjectReference(io->getURL().getURLString(), u2seq.visualName, GObjectTypes::SEQUENCE, U2EntityRef(dbiRef, u2seq.id));

            U2SequenceObject* seqObj = new U2SequenceObject(u2seq.visualName, U2EntityRef(dbiRef, u2seq.id));
            CHECK_EXT_BREAK(seqObj != NULL, os.setError("U2SequenceObject is NULL"));
            seqObj->setQuality(DNAQuality(qualityScores));
            objects << seqObj;

            U1AnnotationUtils::addAnnotations(objects, seqImporter.getCaseAnnotations(), sequenceRef, NULL, hints);
        }
        if (PROGRESS_UPDATE_STEP == progressUpNum) {
            progressUpNum = 0;
            os.setProgress(io->getProgress());
        }
    }

    CHECK_OP_EXT(os, qDeleteAll(objects); objects.clear(), );
    bool emptyObjects = objects.isEmpty();
    CHECK_EXT(!emptyObjects || merge, os.setError(Document::tr("Document is empty.")), );
    SAFE_POINT(headers.size() == mergedMapping.size(), "headers <-> regions mapping failed!", );

    if (!merge) {
        return;
    }
    U2Sequence u2seq = seqImporter.finalizeSequenceAndValidate(os);
    CHECK_OP(os,);
    sequenceRef = GObjectReference(io->getURL().getURLString(), u2seq.visualName, GObjectTypes::SEQUENCE, U2EntityRef(dbiRef, u2seq.id));

    U1AnnotationUtils::addAnnotations(objects, seqImporter.getCaseAnnotations(), sequenceRef, NULL, hints);
    objects << new U2SequenceObject(u2seq.visualName, U2EntityRef(dbiRef, u2seq.id));
    objects << DocumentFormatUtils::addAnnotationsForMergedU2Sequence(sequenceRef, dbiRef, headers, mergedMapping, hints);
    if (headers.size() > 1) {
        writeLockReason = QObject::tr("Document sequences were merged");
    }
}
Ejemplo n.º 5
0
void QScriptHighlighter::highlightBlock(const QString &text)
{
    // states
    enum {
        StateStandard,
        StateCommentStart1,
        StateCCommentStart2,
        StateCppCommentStart2,
        StateCComment,
        StateCppComment,
        StateCCommentEnd1,
        StateCCommentEnd2,
        StateStringStart,
        StateString,
        StateStringEnd,
        StateString2Start,
        StateString2,
        StateString2End,
        StateNumber,
        StatePreProcessor,
        NumStates
    };
    // tokens
    enum {
        InputAlpha,
        InputNumber,
        InputAsterix,
        InputSlash,
        InputParen,
        InputSpace,
        InputHash,
        InputQuotation,
        InputApostrophe,
        InputSep,
        NumInputs
    };

    static const uchar table[NumStates][NumInputs] = {
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStandard
        { StateStandard,      StateNumber,   StateCCommentStart2, StateCppCommentStart2, StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCommentStart1
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentStart2
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // CppCommentStart2
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCComment
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // StateCppComment
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCCommentEnd2,     StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentEnd1
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCCommentEnd2
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateStringStart
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateString
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStringEnd
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2Start
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateString2End
        { StateNumber,        StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateNumber
        { StatePreProcessor,  StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard } // StatePreProcessor
    };

    QString buffer;
    buffer.reserve(text.length());
    QTextCharFormat emptyFormat;

    int state = StateStandard;
    const int previousState = previousBlockState();
    if (previousState != -1)
        state = previousState;

    if (text.isEmpty()) {
        setCurrentBlockState(previousState);
        return;
    }

    int input = -1;
    int i = 0;
    bool lastWasBackSlash = false;
    bool makeLastStandard = false;

    static const QSet<QChar> alphabeth = alphaChars();
    static const QString mathChars = QString::fromLatin1("xXeE");
    static const QString numbers = QString::fromLatin1("0123456789");
    bool questionMark = false;
    QChar lastChar;
    QString firstWord;
    forever {
        const QChar c = text.at(i);

        if (lastWasBackSlash) {
            input = InputSep;
        } else {
            switch (c.toLatin1()) {
                case '*':
                    input = InputAsterix;
                    break;
                case '/':
                    input = InputSlash;
                    break;
                case '(': case '[': case '{':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       )
                        //blockData->parentheses << Parenthesis(Parenthesis::Open, c, i);
                    break;
                case ')': case ']': case '}':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       ) {
                        //blockData->parentheses << Parenthesis(Parenthesis::Closed, c, i);
                    }
                    break;
                case '#':
                    input = InputHash;
                    break;
                case '"':
                    input = InputQuotation;
                    break;
                case '\'':
                    input = InputApostrophe;
                    break;
                case ' ':
                    input = InputSpace;
                    break;
                case '1': case '2': case '3': case '4': case '5':
                case '6': case '7': case '8': case '9': case '0':
                    if (alphabeth.contains(lastChar)
                        && (!mathChars.contains(lastChar) || !numbers.contains(text.at(i - 1)))) {
                        input = InputAlpha;
                    } else {
                        if (input == InputAlpha && numbers.contains(lastChar))
                            input = InputAlpha;
                        else
                            input = InputNumber;
                    }
                    break;
                case ':': {
                              input = InputAlpha;
                              QChar nextChar = QLatin1Char(' ');
                              if (i < text.length() - 1)
                                  nextChar = text.at(i + 1);
                              if (state == StateStandard && !questionMark &&
                                  lastChar != QLatin1Char(':') && nextChar != QLatin1Char(':')) {
                                  for (int j = 0; j < i; ++j) {
                                      if (format(j) == emptyFormat)
                                          setFormat(j, 1, m_labelFormat);
                                  }
                              }
                              break;
                          }
                default: {
                             if (!questionMark && c == QLatin1Char('?'))
                                 questionMark = true;
                             if (c.isLetter() || c == QLatin1Char('_'))
                                 input = InputAlpha;
                             else
                                 input = InputSep;
                         } break;
            }
        }

        lastWasBackSlash = !lastWasBackSlash && c == QLatin1Char('\\');

        if (input == InputAlpha)
            buffer += c;

        state = table[state][input];

        switch (state) {
            case StateStandard: {
                                    setFormat(i, 1, emptyFormat);
                                    if (makeLastStandard)
                                        setFormat(i - 1, 1, emptyFormat);
                                    makeLastStandard = false;
                                    if (!buffer.isEmpty() && input != InputAlpha ) {
                                        highlightKeyword(i, buffer);
                                        buffer.clear();
                                    }
                                } break;
            case StateCommentStart1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = true;
                                buffer.resize(0);
                                break;
            case StateCCommentStart2:
                                setFormat(i - 1, 2, m_commentFormat);
                                makeLastStandard = false;
                                buffer.resize(0);
                                break;
            case StateCppCommentStart2:
                                setFormat(i - 1, 2, m_commentFormat);
                                makeLastStandard = false;
                                buffer.resize(0);
                                break;
            case StateCComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCppComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCCommentEnd1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateCCommentEnd2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_commentFormat);
                                buffer.resize(0);
                                break;
            case StateStringStart:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_stringFormat);
                                buffer.resize(0);
                                break;
            case StateStringEnd:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString2Start:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateString2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_stringFormat);
                                buffer.resize(0);
                                break;
            case StateString2End:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.resize(0);
                                break;
            case StateNumber:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat( i, 1, m_numberFormat);
                                buffer.resize(0);
                                break;
            case StatePreProcessor:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, m_preProcessorFormat);
                                buffer.resize(0);
                                break;
        }

        lastChar = c;
        i++;
        if (i >= text.length())
            break;
    }

    highlightKeyword(text.length(), buffer);

    if (state == StateCComment
        || state == StateCCommentEnd1
        || state == StateCCommentStart2
       ) {
        state = StateCComment;
    } else if (state == StateString) {
        state = StateString;
    } else if (state == StateString2) {
        state =  StateString2;
    } else {
        state = StateStandard;
    }

    setCurrentBlockState(state);
}
Ejemplo n.º 6
0
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    int64_t nBalance = 0;
    std::vector<COutput> vCoins;
    wallet->AvailableCoins(vCoins, true, coinControl,false);

    for (auto const& out : vCoins)
        nBalance += out.tx->vout[out.i].nValue;

    if(total > nBalance)
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > nBalance)
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

	std::string txid = "";
	std::string messages = "";
	std::string hashBoinc = "";

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, int64_t> > vecSend;
		foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
            std::string smessage = MakeSafeMessage(FromQStringW(rcp.Message));
            messages += "<MESSAGE>" + smessage + "</MESSAGE>";

        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64_t nFeeRequired = 0;
		if (!msAttachmentGuid.empty())
		{
				LogPrintf("Adding attachment to tx %s",wtx.hashBoinc);
				wtx.hashBoinc += "<ATTACHMENT><TXID>" + wtx.GetHash().ToString() + "</TXID><ATTACHMENTGUID>" + msAttachmentGuid + "</ATTACHMENTGUID></ATTACHMENT>";
		}
		wtx.hashBoinc += messages;
		bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);

        if(!fCreated)
        {
            if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }

		std::string samt = FormatMoney(wtx.vout[0].nValue);
        if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
		txid = wtx.GetHash().GetHex();
		hashBoinc = wtx.hashBoinc;
    }
Ejemplo n.º 7
0
void PeerListModel::updatePeers(const google::protobuf::RepeatedPtrField<Protos::GUI::State::Peer>& peers, const QSet<Common::Hash>& peersDownloadingOurData)
{
   Common::SortedArray<Peer*> peersToRemove = this->orderedPeers;
   QList<Peer*> peersToAdd;

   for (int i = 0; i < peers.size(); i++)
   {
      const Common::Hash peerID(peers.Get(i).peer_id().hash());
      const QString& nick = Common::ProtoHelper::getStr(peers.Get(i), &Protos::GUI::State::Peer::nick);
      const QString& coreVersion = Common::ProtoHelper::getStr(peers.Get(i), &Protos::GUI::State::Peer::core_version);
      const quint64 sharingAmount(peers.Get(i).sharing_amount());
      const TransferInformation transferInformation { peers.Get(i).download_rate(), peers.Get(i).upload_rate(),  peersDownloadingOurData.contains(peerID) };
      const QHostAddress ip =
         peers.Get(i).has_ip() ?
            Common::ProtoHelper::getIP(peers.Get(i).ip()) :
            QHostAddress();

      Peer* peer = this->indexedPeers[peerID];
      int j = this->orderedPeers.indexOf(peer);
      if (j != -1)
      {
         peersToRemove.remove(peer);
         if (peer->nick != nick)
         {
            if (this->currentSortType == Protos::GUI::Settings::BY_NICK)
            {
               this->beginRemoveRows(QModelIndex(), j, j);
               this->orderedPeers.remove(peer);
               this->endRemoveRows();
               peer->nick = nick;
               peersToAdd << peer;
            }
            else
            {
               peer->nick = nick;
               emit dataChanged(this->createIndex(j, 1), this->createIndex(j, 1));
            }
         }
         if (peer->sharingAmount != sharingAmount)
         {
            if (this->currentSortType == Protos::GUI::Settings::BY_SHARING_AMOUNT)
            {
               this->beginRemoveRows(QModelIndex(), j, j);
               this->orderedPeers.remove(peer);
               this->endRemoveRows();
               peer->sharingAmount = sharingAmount;
               peersToAdd << peer;
            }
            else
            {
               peer->sharingAmount = sharingAmount;
               emit dataChanged(this->createIndex(j, 1), this->createIndex(j, 1));
            }
         }
         if (peer->transferInformation != transferInformation)
         {
            peer->transferInformation = transferInformation;
            emit dataChanged(this->createIndex(j, 0), this->createIndex(j, 0));
         }

         peer->ip = ip;
         peer->coreVersion = coreVersion;
      }
      else
      {
         peersToAdd << new Peer(peerID, nick, coreVersion, sharingAmount, ip, transferInformation);
      }
   }

   QList<Common::Hash> peerIDsRemoved;
   for (Common::SortedArray<Peer*>::Iterator i(peersToRemove); i.hasNext();)
   {
      Peer* const peer = i.next();
      peerIDsRemoved << peer->peerID;
      int j = this->orderedPeers.indexOf(peer);
      if (j != -1)
      {
         this->beginRemoveRows(QModelIndex(), j, j);
         this->indexedPeers.remove(peer->peerID);
         this->orderedPeers.remove(peer);
         delete peer;
         this->endRemoveRows();
      }
   }

   if (!peerIDsRemoved.isEmpty())
      emit peersRemoved(peerIDsRemoved);

   for (QListIterator<Peer*> i(peersToAdd); i.hasNext();)
   {
      Peer* const peer = i.next();
      int pos = this->orderedPeers.insert(peer);
      this->beginInsertRows(QModelIndex(), pos, pos);
      this->indexedPeers.insert(peer->peerID, peer);
      this->endInsertRows();
   }
}
Ejemplo n.º 8
0
void SourcesModel::slotMatchesChanged(const QList<Plasma::QueryMatch>& l)
{
    beginResetModel();
    m_matches.clear();
    m_size = 0;
    m_types.clear();
    m_duplicates.clear();

    QList<Plasma::QueryMatch> list(l);
    qSort(list);

    for (auto it = list.crbegin(), end = list.crend(); it != end; ++it) {
        slotMatchAdded(*it);
    }

    // Sort the result types. We give the results which contain the query
    // text in the user visible string a higher preference than the ones
    // that do not
    // The rest are given the same preference as given by the runners.
    const QString simplifiedQuery = m_queryString.simplified();
    const auto words = simplifiedQuery.splitRef(QLatin1Char(' '), QString::SkipEmptyParts);

    QSet<QString> higherTypes;
    foreach (const QString &type, m_types) {
        const TypeData td = m_matches.value(type);

        for (const Plasma::QueryMatch &match : td.shown) {
            const QString text = match.text().simplified();
            bool containsAll = true;

            for (const auto &word : words) {
                if (!text.contains(word, Qt::CaseInsensitive)) {
                    containsAll = false;
                    break;
                }
            }

            // Maybe we should be giving it a higher type based on the number of matched
            // words in the text?
            if (containsAll) {
                higherTypes << match.matchCategory();
            }
        }
    }

    auto sortFunc = [&](const QString& l, const QString& r) {
        bool lHigher = higherTypes.contains(l);
        bool rHigher = higherTypes.contains(r);

        if (lHigher == rHigher) {
            return false;
        }
        else {
            return lHigher;
        }
    };
    qStableSort(m_types.begin(), m_types.end(), sortFunc);

    m_modelPopulated = true;
    endResetModel();
}
Ejemplo n.º 9
0
void MaintainingReader<TokenLookupClass, LookupKey>::validateElement(const LookupKey elementName) const
{
    Q_ASSERT(tokenType() == QXmlStreamReader::StartElement);

    if(m_elementDescriptions.contains(elementName))
    {
        // QHash::value breaks in Metrowerks Compiler
        const ElementDescription<TokenLookupClass, LookupKey> &desc = *m_elementDescriptions.find(elementName);
        const int attCount = m_currentAttributes.count();

        QSet<typename TokenLookupClass::NodeName> encounteredXSLTAtts;

        for(int i = 0; i < attCount; ++i)
        {
            const QXmlStreamAttribute &attr = m_currentAttributes.at(i);
            if(attr.namespaceUri().isEmpty())
            {
                const typename TokenLookupClass::NodeName attrName(TokenLookupClass::toToken(attr.name()));
                encounteredXSLTAtts.insert(attrName);

                if(!desc.requiredAttributes.contains(attrName) &&
                   !desc.optionalAttributes.contains(attrName) &&
                   !m_standardAttributes.contains(attrName) &&
                   !isAnyAttributeAllowed())
                {
                    QString translationString;

                    QList<typename TokenLookupClass::NodeName> all(desc.requiredAttributes.toList() + desc.optionalAttributes.toList());
                    const int totalCount = all.count();
                    QStringList allowed;

                    for(int i = 0; i < totalCount; ++i)
                        allowed.append(QPatternist::formatKeyword(TokenLookupClass::toString(all.at(i))));

                    /* Note, we can't run toString() on attrName, because we're in this branch,
                     * the token lookup doesn't have the string(!).*/
                    const QString stringedName(attr.name().toString());

                    if(totalCount == 0)
                    {
                        translationString = QtXmlPatterns::tr("Attribute %1 cannot appear on the element %2. Only the standard attributes can appear.")
                                            .arg(formatKeyword(stringedName),
                                                 formatKeyword(name()));
                    }
                    else if(totalCount == 1)
                    {
                        translationString = QtXmlPatterns::tr("Attribute %1 cannot appear on the element %2. Only %3 is allowed, and the standard attributes.")
                                            .arg(formatKeyword(stringedName),
                                                 formatKeyword(name()),
                                                 allowed.first());
                    }
                    else if(totalCount == 1)
                    {
                        /* Note, allowed has already had formatKeyword() applied. */
                        translationString = QtXmlPatterns::tr("Attribute %1 cannot appear on the element %2. Allowed is %3, %4, and the standard attributes.")
                                            .arg(formatKeyword(stringedName),
                                                 formatKeyword(name()),
                                                 allowed.first(),
                                                 allowed.last());
                    }
                    else
                    {
                        /* Note, allowed has already had formatKeyword() applied. */
                        translationString = QtXmlPatterns::tr("Attribute %1 cannot appear on the element %2. Allowed is %3, and the standard attributes.")
                                            .arg(formatKeyword(stringedName),
                                                 formatKeyword(name()),
                                                 allowed.join(QLatin1String(", ")));
                    }

                    m_context->error(translationString,
                                     ReportContext::XTSE0090,
                                     currentLocation());
                }
            }
            else if(attr.namespaceUri() == namespaceUri())
            {
                m_context->error(QtXmlPatterns::tr("XSL-T attributes on XSL-T elements must be in the null namespace, not in the XSL-T namespace which %1 is.")
                                                  .arg(formatKeyword(attr.name())),
                                 ReportContext::XTSE0090,
                                 currentLocation());
            }
            /* Else, attributes in other namespaces are allowed, continue. */
        }

        const QSet<typename TokenLookupClass::NodeName> requiredButMissing(QSet<typename TokenLookupClass::NodeName>(desc.requiredAttributes).subtract(encounteredXSLTAtts));

        if(!requiredButMissing.isEmpty())
        {
            error(QtXmlPatterns::tr("The attribute %1 must appear on element %2.")
                             .arg(QPatternist::formatKeyword(TokenLookupClass::toString(*requiredButMissing.constBegin())),
                                  formatKeyword(name())),
                  ReportContext::XTSE0010);
        }
    }
    else
    {
        error(QtXmlPatterns::tr("The element with local name %1 does not exist in XSL-T.").arg(formatKeyword(name())),
              ReportContext::XTSE0010);
    }
}
Ejemplo n.º 10
0
bool Nfa::runNfaP(QString string)
{
  /* Create the partition of states */
  QList<QSet<Node*>*>* part = partition();

  /* Allocate threads depending on size partitioning */
  pthread_t* threads = (pthread_t*)malloc(part->size()*sizeof(pthread_t));
  /* Allocate params for each thread */
  NfaParams* params = (NfaParams*)malloc(part->size()*sizeof(NfaParams));
  /* Initial state set will be stored here later in the code */
  QSet<Node*>* initialStateSet = NULL;
  /* Loop counter */
  int i;

  /*
   *  IMPORTANT: An assumption is being made here that the very last set 
   *  in the list contains ONLY the inital state
   *
   */
  for(i = 0; i < part->size(); i++)
  {
    params[i].nfa = this;
    params[i].str = &string;
    /* If the set is the initial state, mark it as such */
    if (i == part->size() - 1) 
    {
      initialStateSet = part->at(i);
      params[i].isInitial = true;
    }
    else
    {
      params[i].isInitial = false;
    }
    /* Assign the params being sent to the thread the list it will be working on */
    params[i].nodes = part->at(i);
    /* Send off the thread! */
    pthread_create(&threads[i], NULL, &traverseP, &params[i]);
  }

  /* Reap the threads */
  for (i = 0; i < part->size(); i++) 
  {
    int* ptr;
    pthread_join(threads[i], (void**)&ptr);
  }

  bool intersects = false;

  /* Again, we're assuming the last list is the inital state so we aren't checking it */
  /* If there's any intersection between the initial set and the final sets then it was a valid string */
  for(i = 0; i < part->size() - 1; i++)
  {
    if(initialStateSet->intersect(*part->at(i)).size() > 0)
      intersects = true;
  }

  free(threads);
  free(params);

  return intersects;
}
Ejemplo n.º 11
0
bool Utils::Misc::isPreviewable(const QString &extension)
{
    static QSet<QString> multimedia_extensions;
    if (multimedia_extensions.empty()) {
        multimedia_extensions.insert("3GP");
        multimedia_extensions.insert("AAC");
        multimedia_extensions.insert("AC3");
        multimedia_extensions.insert("AIF");
        multimedia_extensions.insert("AIFC");
        multimedia_extensions.insert("AIFF");
        multimedia_extensions.insert("ASF");
        multimedia_extensions.insert("AU");
        multimedia_extensions.insert("AVI");
        multimedia_extensions.insert("FLAC");
        multimedia_extensions.insert("FLV");
        multimedia_extensions.insert("M3U");
        multimedia_extensions.insert("M4A");
        multimedia_extensions.insert("M4P");
        multimedia_extensions.insert("M4V");
        multimedia_extensions.insert("MID");
        multimedia_extensions.insert("MKV");
        multimedia_extensions.insert("MOV");
        multimedia_extensions.insert("MP2");
        multimedia_extensions.insert("MP3");
        multimedia_extensions.insert("MP4");
        multimedia_extensions.insert("MPC");
        multimedia_extensions.insert("MPE");
        multimedia_extensions.insert("MPEG");
        multimedia_extensions.insert("MPG");
        multimedia_extensions.insert("MPP");
        multimedia_extensions.insert("OGG");
        multimedia_extensions.insert("OGM");
        multimedia_extensions.insert("OGV");
        multimedia_extensions.insert("QT");
        multimedia_extensions.insert("RA");
        multimedia_extensions.insert("RAM");
        multimedia_extensions.insert("RM");
        multimedia_extensions.insert("RMV");
        multimedia_extensions.insert("RMVB");
        multimedia_extensions.insert("SWA");
        multimedia_extensions.insert("SWF");
        multimedia_extensions.insert("VOB");
        multimedia_extensions.insert("WAV");
        multimedia_extensions.insert("WMA");
        multimedia_extensions.insert("WMV");
    }

    if (extension.isEmpty())
        return false;

    return multimedia_extensions.contains(extension.toUpper());
}
Ejemplo n.º 12
0
QSet<Node*>* Nfa::traverse(QSet<Node*>* node, QString* str, int direction)
{
    QSet<Node*>* q = node; //node->rawStates(direction);

    /* 
     * We want the rest of the functions to perform only considering the
     * Possibility of FORWARDS/BACKWARDS, not -1
     */
    int trav_direction = (direction == -1 || direction == FORWARDS ? FORWARDS : BACKWARDS);

    // Epsilon closure
    QSetIterator<Node*> k(*q);
    while (k.hasNext())
    {
        Node* node = k.next();
        q->unite(*node->rawStates(trav_direction));
    }

    /*
     * Setup variables that loop will use
     */
    int incr = 1;
    int limit = str->size();
    int i = 0;
    if(direction != -1)
    {
      if(direction == FORWARDS)
      {
        limit = (str->size() % 2 == 0 ? str->size() / 2 + 1 : str->size() / 2 );
        if(VERBOSE)
          printf("FORWARDS: i: %d, limit: %d\n", i, limit);//(direction == FORWARDS ? "Forwards" : "Backwards"));
      }
      /* Backwards */
      else
      {
        limit = str->size() / 2 + 1;
        incr = -1;
        i = str->size() - 1;
        if(VERBOSE)
          printf("BACKWARDS: i: %d, limit: %d, string length: %d\n", i, limit, str->size());//(direction == FORWARDS ? "Forwards" : "Backwards"));
      }
    }

    //printf("Outside: i: %d, limit: %d\n", i, limit);//(direction == FORWARDS ? "Forwards" : "Backwards"));

    QSet<Node*>* newSet = new QSet<Node*>();
    /* You want to loop backwards sometimes, so the comparison you do depends on that */
    for (; ( trav_direction == FORWARDS ? i < limit : i >= limit ); i += incr)
    {
    //printf("i: %d, limit: %d\n", i, limit);//(direction == FORWARDS ? "Forwards" : "Backwards"));
        newSet->clear();
        QSetIterator<Node*> j(*q);
        while (j.hasNext())
        {
            Node* node = j.next();
            QString subStr(str->at(i));
            newSet->unite(*node->traverseOn(subStr, trav_direction));
        }

        // Make q eqaul newSet.
        q->clear();
        q->unite(*newSet); // Done this way for mem. management.

        // Epsilon closure.
        QSetIterator<Node*> k(*q);
        while (k.hasNext())
        {
            Node* node = k.next();
            q->unite(*node->rawStates(trav_direction));
        }

        // Break out early if the q set ends up empty.
        if (q->count() == 0)
        {
            return q;
        }
    }
    return q;
}
Ejemplo n.º 13
0
void LogsDialog::exportToGoogleEarth()
{
  // filter data points
  QList<QStringList> dataPoints = filterGePoints(csvlog);
  int n = dataPoints.count(); // number of points to export
  if (n==0) return;

  int latcol=0, longcol=0, altcol=0, speedcol=0;
  QSet<int> nondataCols;
  for (int i=1; i<dataPoints.at(0).count(); i++) {
    // Long,Lat,Course,GPS Speed,GPS Alt
    if (dataPoints.at(0).at(i).contains("Long")) {
      longcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("Lat")) {
      latcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("GPS Alt") || dataPoints.at(0).at(i).contains("GAlt")) {
      altcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("GPS Speed")) {
      speedcol = i;
      nondataCols << i;
    }
  }

  if (longcol==0 || latcol==0) {
    return;
  }

  QString geIconFilename = generateProcessUniqueTempFileName("track0.png");
  if (QFile::exists(geIconFilename)) {
    QFile::remove(geIconFilename);
  }
  QFile::copy(":/images/track0.png", geIconFilename);

  QString geFilename = generateProcessUniqueTempFileName("flight.kml");
  if (QFile::exists(geFilename)) {
    QFile::remove(geFilename);
  }
  QFile geFile(geFilename);
  if (!geFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
    QMessageBox::warning(this, tr("Error"),
        tr("Cannot write file %1:\n%2.")
        .arg(geFilename)
        .arg(geFile.errorString()));
    return;
  }

  QTextStream outputStream(&geFile);

  // file header
  outputStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\">\n";
  outputStream << "\t<Document>\n\t\t<name>" << logFilename << "</name>\n";
  outputStream << "\t\t<Style id=\"multiTrack_n\">\n\t\t\t<IconStyle>\n\t\t\t\t<Icon>\n\t\t\t\t\t<href>file://" << geIconFilename << "</href>\n\t\t\t\t</Icon>\n\t\t\t</IconStyle>\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>6</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<Style id=\"multiTrack_h\">\n\t\t\t<IconStyle>\n\t\t\t\t<scale>0</scale>\n\t\t\t\t<Icon>\n\t\t\t\t\t<href>file://" << geIconFilename << "</href>\n\t\t\t\t</Icon>\n\t\t\t</IconStyle>\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>8</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<StyleMap id=\"multiTrack\">\n\t\t\t<Pair>\n\t\t\t\t<key>normal</key>\n\t\t\t\t<styleUrl>#multiTrack_n</styleUrl>\n\t\t\t</Pair>\n\t\t\t<Pair>\n\t\t\t\t<key>highlight</key>\n\t\t\t\t<styleUrl>#multiTrack_h</styleUrl>\n\t\t\t</Pair>\n\t\t</StyleMap>\n";
  outputStream << "\t\t<Style id=\"lineStyle\">\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>6</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<Schema id=\"schema\">\n";
  outputStream << "\t\t\t<gx:SimpleArrayField name=\"GPSSpeed\" type=\"float\">\n\t\t\t\t<displayName>GPS Speed</displayName>\n\t\t\t</gx:SimpleArrayField>\n";
  
  // declare additional fields
  for (int i=0; i<dataPoints.at(0).count()-2; i++) {
    if (ui->FieldsTW->item(0,i)->isSelected() && !nondataCols.contains(i+2)) {
      QString origName = dataPoints.at(0).at(i+2);
      QString safeName = origName;
      safeName.replace(" ","_");
      outputStream << "\t\t\t<gx:SimpleArrayField name=\""<< safeName <<"\" ";
      outputStream << "type=\"string\"";   // additional fields have fixed type: string
      outputStream << ">\n\t\t\t\t<displayName>" << origName << "</displayName>\n\t\t\t</gx:SimpleArrayField>\n";
    }
  }

  QString planeName;
  if (logFilename.indexOf("-")>0) {
    planeName=logFilename.left(logFilename.indexOf("-"));
  } else {
    planeName=logFilename;
  }

  outputStream << "\t\t</Schema>\n";
  outputStream << "\t\t<Folder>\n\t\t\t<name>Log Data</name>\n\t\t\t<Placemark>\n\t\t\t\t<name>" << planeName << "</name>";
  outputStream << "\n\t\t\t\t<styleUrl>#multiTrack</styleUrl>";
  outputStream << "\n\t\t\t\t<gx:Track>\n";
  outputStream << "\n\t\t\t\t\t<altitudeMode>absolute</altitudeMode>\n";

  // time data points
  for (int i=1; i<n; i++) {
    QString tstamp=dataPoints.at(i).at(0)+QString("T")+dataPoints.at(i).at(1)+QString("Z");
    outputStream << "\t\t\t\t\t<when>"<< tstamp <<"</when>\n";
  }

  // coordinate data points
  for (int i=1; i<n; i++) {
    QString latitude = dataPoints.at(i).at(latcol).trimmed();
    QString longitude = dataPoints.at(i).at(longcol).trimmed();
    int altitude = altcol ? dataPoints.at(i).at(altcol).toFloat() : 0;
    latitude.sprintf("%3.8f", toDecimalCoordinate(latitude));
    longitude.sprintf("%3.8f", toDecimalCoordinate(longitude));
    outputStream << "\t\t\t\t\t<gx:coord>" << longitude << " " << latitude << " " <<  altitude << " </gx:coord>\n" ;
  }

  // additional data for data points
  outputStream << "\t\t\t\t\t<ExtendedData>\n\t\t\t\t\t\t<SchemaData schemaUrl=\"#schema\">\n";

  if (speedcol) {
    // gps speed data points
    outputStream << "\t\t\t\t\t\t\t<gx:SimpleArrayData name=\"GPSSpeed\">\n";
    for (int i=1; i<n; i++) {
      outputStream << "\t\t\t\t\t\t\t\t<gx:value>"<< dataPoints.at(i).at(speedcol) <<"</gx:value>\n";
    }
    outputStream << "\t\t\t\t\t\t\t</gx:SimpleArrayData>\n";
  }

  // add values for additional fields
  for (int i=0; i<dataPoints.at(0).count()-2; i++) {
    if (ui->FieldsTW->item(0,i)->isSelected() && !nondataCols.contains(i+2)) {
      QString safeName = dataPoints.at(0).at(i+2);;
      safeName.replace(" ","_");
      outputStream << "\t\t\t\t\t\t\t<gx:SimpleArrayData name=\""<< safeName <<"\">\n";
      for (int j=1; j<n; j++) {
        outputStream << "\t\t\t\t\t\t\t\t<gx:value>"<< dataPoints.at(j).at(i+2) <<"</gx:value>\n";
      }
      outputStream << "\t\t\t\t\t\t\t</gx:SimpleArrayData>\n";
    }
  }

  outputStream << "\t\t\t\t\t\t</SchemaData>\n\t\t\t\t\t</ExtendedData>\n\t\t\t\t</gx:Track>\n\t\t\t</Placemark>\n\t\t</Folder>\n\t</Document>\n</kml>";
  geFile.close();

  QString gePath = g.gePath();
  QStringList parameters;
#ifdef __APPLE__
  parameters << "-a";
  parameters << gePath;
  gePath = "/usr/bin/open";
#endif
  parameters << geFilename;
  QProcess *process = new QProcess(this);
  process->start(gePath, parameters);
}
Ejemplo n.º 14
0
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl)
{
    qint64 total = 0;
    QList<SendCoinsRecipient> recipients = transaction.getRecipients();
    std::vector<std::pair<CScript, int64_t> > vecSend;

    if(recipients.empty())
    {
        return OK;
    }

    if(isAnonymizeOnlyUnlocked())
    {
        return AnonymizeOnlyUnlocked;
    }

    QSet<QString> setAddress; // Used to detect duplicates
    int nAddresses = 0;

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if (rcp.paymentRequest.IsInitialized())
        {   // PaymentRequest...
            int64_t subtotal = 0;
            const payments::PaymentDetails& details = rcp.paymentRequest.getDetails();
            for (int i = 0; i < details.outputs_size(); i++)
            {
                const payments::Output& out = details.outputs(i);
                if (out.amount() <= 0) continue;
                subtotal += out.amount();
                const unsigned char* scriptStr = (const unsigned char*)out.script().data();
                CScript scriptPubKey(scriptStr, scriptStr+out.script().size());
                vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, out.amount()));
            }
            if (subtotal <= 0)
            {
                return InvalidAmount;
            }
            total += subtotal;
        }
        else
        {   // User-entered unpay address / amount:
            if(!validateAddress(rcp.address))
            {
                return InvalidAddress;
            }
            if(rcp.amount <= 0)
            {
                return InvalidAmount;
            }
            setAddress.insert(rcp.address);
            ++nAddresses;

            CScript scriptPubKey;
            scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, rcp.amount));

            total += rcp.amount;
        }
    }
    if(setAddress.size() != nAddresses)
    {
        return DuplicateAddress;
    }

    qint64 nBalance = getBalance(coinControl);

    if(total > nBalance)
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > nBalance)
    {
        transaction.setTransactionFee(nTransactionFee);
        return SendCoinsReturn(AmountWithFeeExceedsBalance);
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        transaction.newPossibleKeyChange(wallet);
        int64_t nFeeRequired = 0;
        std::string strFailReason;

        CWalletTx *newTx = transaction.getTransaction();
        CReserveKey *keyChange = transaction.getPossibleKeyChange();


        if(recipients[0].useInstantX && total > GetSporkValue(SPORK_5_MAX_VALUE)*COIN){
            emit message(tr("Send Coins"), tr("InstantX doesn't support sending values that high yet. Transactions are currently limited to %n UNP.", "", GetSporkValue(SPORK_5_MAX_VALUE)),
                         CClientUIInterface::MSG_ERROR);
            return TransactionCreationFailed;
        }

        bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, strFailReason, coinControl, recipients[0].inputType, recipients[0].useInstantX);
        transaction.setTransactionFee(nFeeRequired);

        if(!fCreated)
        {
            if((total + nFeeRequired) > nBalance)
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance);
            }
            emit message(tr("Send Coins"), QString::fromStdString(strFailReason),
                         CClientUIInterface::MSG_ERROR);
            return TransactionCreationFailed;
        }
    }

    return SendCoinsReturn(OK);
}
Ejemplo n.º 15
0
QDomDocument QgsWFSServer::describeFeatureType()
{
  QgsDebugMsg( "Entering." );
  QDomDocument doc;
  //xsd:schema
  QDomElement schemaElement = doc.createElement( "schema"/*xsd:schema*/ );
  schemaElement.setAttribute( "xmlns", "http://www.w3.org/2001/XMLSchema" );
  schemaElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" );
  schemaElement.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" );
  schemaElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" );
  schemaElement.setAttribute( "xmlns:qgs", "http://www.qgis.org/gml" );
  schemaElement.setAttribute( "targetNamespace", "http://www.qgis.org/gml" );
  doc.appendChild( schemaElement );

  //xsd:import
  QDomElement importElement = doc.createElement( "import"/*xsd:import*/ );
  importElement.setAttribute( "namespace", "http://www.opengis.net/gml" );
  importElement.setAttribute( "schemaLocation", "http://schemas.opengis.net/gml/2.1.2/feature.xsd" );
  schemaElement.appendChild( importElement );

  //read TYPENAME
  QString typeName;
  QMap<QString, QString>::const_iterator type_name_it = mParameterMap.find( "TYPENAME" );
  if ( type_name_it != mParameterMap.end() )
  {
    typeName = type_name_it.value();
  }
  else
  {
    return doc;
  }

  QStringList wfsLayersId = mConfigParser->wfsLayers();
  QMap< QString, QMap< int, QString > > aliasInfo = mConfigParser->layerAliasInfo();
  QMap< QString, QSet<QString> > hiddenAttributes = mConfigParser->hiddenAttributes();

  QList<QgsMapLayer*> layerList;
  QgsMapLayer* currentLayer = 0;

  layerList = mConfigParser->mapLayerFromStyle( typeName, "" );
  currentLayer = layerList.at( 0 );

  QgsVectorLayer* layer = dynamic_cast<QgsVectorLayer*>( currentLayer );
  if ( layer && wfsLayersId.contains( layer->id() ) )
  {
    //is there alias info for this vector layer?
    QMap< int, QString > layerAliasInfo;
    QMap< QString, QMap< int, QString > >::const_iterator aliasIt = aliasInfo.find( currentLayer->id() );
    if ( aliasIt != aliasInfo.constEnd() )
    {
      layerAliasInfo = aliasIt.value();
    }

    //hidden attributes for this layer
    QSet<QString> layerHiddenAttributes;
    QMap< QString, QSet<QString> >::const_iterator hiddenIt = hiddenAttributes.find( currentLayer->id() );
    if ( hiddenIt != hiddenAttributes.constEnd() )
    {
      layerHiddenAttributes = hiddenIt.value();
    }

    //do a select with searchRect and go through all the features
    QgsVectorDataProvider* provider = layer->dataProvider();
    if ( !provider )
    {
      return doc;
    }

    typeName = typeName.replace( QString( " " ), QString( "_" ) );

    //xsd:element
    QDomElement elementElem = doc.createElement( "element"/*xsd:element*/ );
    elementElem.setAttribute( "name", typeName );
    elementElem.setAttribute( "type", "qgs:" + typeName + "Type" );
    elementElem.setAttribute( "substitutionGroup", "gml:_Feature" );
    schemaElement.appendChild( elementElem );

    //xsd:complexType
    QDomElement complexTypeElem = doc.createElement( "complexType"/*xsd:complexType*/ );
    complexTypeElem.setAttribute( "name", typeName + "Type" );
    schemaElement.appendChild( complexTypeElem );

    //xsd:complexType
    QDomElement complexContentElem = doc.createElement( "complexContent"/*xsd:complexContent*/ );
    complexTypeElem.appendChild( complexContentElem );

    //xsd:extension
    QDomElement extensionElem = doc.createElement( "extension"/*xsd:extension*/ );
    extensionElem.setAttribute( "base", "gml:AbstractFeatureType" );
    complexContentElem.appendChild( extensionElem );

    //xsd:sequence
    QDomElement sequenceElem = doc.createElement( "sequence"/*xsd:sequence*/ );
    extensionElem.appendChild( sequenceElem );

    //xsd:element
    QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ );
    geomElem.setAttribute( "name", "geometry" );
    geomElem.setAttribute( "type", "gml:GeometryPropertyType" );
    geomElem.setAttribute( "minOccurs", "0" );
    geomElem.setAttribute( "maxOccurs", "1" );
    sequenceElem.appendChild( geomElem );

    const QgsFieldMap& fields = provider->fields();
    for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
    {

      QString attributeName = it.value().name();
      //skip attribute if it has edit type 'hidden'
      if ( layerHiddenAttributes.contains( attributeName ) )
      {
        continue;
      }

      //xsd:element
      QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ );
      geomElem.setAttribute( "name", attributeName );
      if ( it.value().type() == 2 )
        geomElem.setAttribute( "type", "integer" );
      else if ( it.value().type() == 6 )
        geomElem.setAttribute( "type", "double" );
      else
        geomElem.setAttribute( "type", "string" );

      sequenceElem.appendChild( geomElem );

      //check if the attribute name should be replaced with an alias
      QMap<int, QString>::const_iterator aliasIt = layerAliasInfo.find( it.key() );
      if ( aliasIt != layerAliasInfo.constEnd() )
      {
        geomElem.setAttribute( "alias", aliasIt.value() );
      }

    }
  }

  return doc;
}
Ejemplo n.º 16
0
void ResourceTopLevelNode::update()
{
    QList<ProjectExplorer::FolderNode *> newFolderList;
    QMap<QPair<QString, QString>, QList<ProjectExplorer::FileNode *> > filesToAdd;

    ResourceFile file(filePath().toString());
    if (file.load() == Core::IDocument::OpenResult::Success) {
        QSet<QPair<QString, QString > > prefixes;

        int prfxcount = file.prefixCount();
        for (int i = 0; i < prfxcount; ++i) {
            const QString &prefix = file.prefix(i);
            const QString &lang = file.lang(i);
            // ensure that we don't duplicate prefixes
            if (!prefixes.contains(qMakePair(prefix, lang))) {
                ProjectExplorer::FolderNode *fn = new ResourceFolderNode(file.prefix(i), file.lang(i), this);
                newFolderList << fn;

                prefixes.insert(qMakePair(prefix, lang));
            }

            QSet<QString> fileNames;
            int filecount = file.fileCount(i);
            for (int j = 0; j < filecount; ++j) {
                const QString &fileName = file.file(i, j);
                QString alias = file.alias(i, j);
                if (alias.isEmpty())
                    alias = filePath().toFileInfo().absoluteDir().relativeFilePath(fileName);
                if (fileNames.contains(fileName)) {
                    // The file name is duplicated, skip it
                    // Note: this is wrong, but the qrceditor doesn't allow it either
                    // only aliases need to be unique
                } else {
                    QString prefixWithSlash = prefix;
                    if (!prefixWithSlash.endsWith(QLatin1Char('/')))
                        prefixWithSlash.append(QLatin1Char('/'));
                    const QString qrcPath = QDir::cleanPath(prefixWithSlash + alias);
                    fileNames.insert(fileName);
                    filesToAdd[qMakePair(prefix, lang)]
                            << new ResourceFileNode(Utils::FileName::fromString(fileName),
                                                    qrcPath, this);
                }

            }
        }
    }

    QList<ProjectExplorer::FolderNode *> oldFolderList = subFolderNodes();
    QList<ProjectExplorer::FolderNode *> foldersToAdd;
    QList<ProjectExplorer::FolderNode *> foldersToRemove;

    std::sort(oldFolderList.begin(), oldFolderList.end(), sortByPrefixAndLang);
    std::sort(newFolderList.begin(), newFolderList.end(), sortByPrefixAndLang);

    ProjectExplorer::compareSortedLists(oldFolderList, newFolderList, foldersToRemove, foldersToAdd, sortByPrefixAndLang);

    removeFolderNodes(foldersToRemove);
    addFolderNodes(foldersToAdd);

    // delete nodes that weren't added
    qDeleteAll(ProjectExplorer::subtractSortedList(newFolderList, foldersToAdd, sortByPrefixAndLang));

    foreach (FolderNode *fn, subFolderNodes()) {
        ResourceFolderNode *rn = static_cast<ResourceFolderNode *>(fn);
        rn->updateFiles(filesToAdd.value(qMakePair(rn->prefix(), rn->lang())));
    }
Ejemplo n.º 17
0
void MapController::botMove()
{
    int index;
    QSet<int> continuedMove;
    //continue the move
    index=0;
    while(index<botList.size())
    {
        if(botList.at(index).inMove)
        {
            if(!botMoveStepSlot(&botList[index]))
            {
                delete botList.at(index).mapObject;
                botList.removeAt(index);
                index--;
            }
            continuedMove << index;
        }
        index++;
    }
    //start move
    index=0;
    while(index<botList.size())
    {
        if(!botList.at(index).inMove && !continuedMove.contains(index))
        {
            QList<CatchChallenger::Direction> directions_allowed;
            if(CatchChallenger::MoveOnTheMap::canGoTo(CatchChallenger::Direction_move_at_left,all_map[botList.at(index).map]->logicalMap,botList.at(index).x,botList.at(index).y,true))
                directions_allowed << CatchChallenger::Direction_move_at_left;
            if(CatchChallenger::MoveOnTheMap::canGoTo(CatchChallenger::Direction_move_at_right,all_map[botList.at(index).map]->logicalMap,botList.at(index).x,botList.at(index).y,true))
                directions_allowed << CatchChallenger::Direction_move_at_right;
            if(CatchChallenger::MoveOnTheMap::canGoTo(CatchChallenger::Direction_move_at_top,all_map[botList.at(index).map]->logicalMap,botList.at(index).x,botList.at(index).y,true))
                directions_allowed << CatchChallenger::Direction_move_at_top;
            if(CatchChallenger::MoveOnTheMap::canGoTo(CatchChallenger::Direction_move_at_bottom,all_map[botList.at(index).map]->logicalMap,botList.at(index).x,botList.at(index).y,true))
                directions_allowed << CatchChallenger::Direction_move_at_bottom;
            if(directions_allowed.size()>0)
            {
                int random = rand()%directions_allowed.size();
                CatchChallenger::Direction final_direction=directions_allowed.at(random);

                botList[index].direction=final_direction;
                botList[index].inMove=true;
                botList[index].moveStep=1;
                switch(final_direction)
                {
                    case CatchChallenger::Direction_move_at_left:
                        botMoveStepSlot(&botList[index]);
                    break;
                    case CatchChallenger::Direction_move_at_right:
                        botMoveStepSlot(&botList[index]);
                    break;
                    case CatchChallenger::Direction_move_at_top:
                        botMoveStepSlot(&botList[index]);
                    break;
                    case CatchChallenger::Direction_move_at_bottom:
                        botMoveStepSlot(&botList[index]);
                    break;
                    default:
                    qDebug() << QStringLiteral("transformLookToMove(): wrong direction");
                    return;
                }
            }
        }
        index++;
    }
}
Ejemplo n.º 18
0
 int State::nextFree(const QSet<int>& lst, int id) const
 {
   while (lst.contains(id)) ++id;
   return id;
 }
Ejemplo n.º 19
0
QList<ConversionPipeTrunk> soundkonverter_codec_mplayer::codecTable()
{
    QList<ConversionPipeTrunk> table;

    /// decode
    fromCodecs += "wav";
    fromCodecs += "ogg vorbis";
    fromCodecs += "mp3";
    fromCodecs += "flac";
    fromCodecs += "wma";
    fromCodecs += "aac";
    fromCodecs += "ac3";
    fromCodecs += "m4a/alac";
    fromCodecs += "mp2";
    fromCodecs += "als";
    fromCodecs += "amr nb";
    fromCodecs += "amr wb";
    fromCodecs += "ape";
    fromCodecs += "speex";
    fromCodecs += "m4a/aac";
    fromCodecs += "mp1";
    fromCodecs += "musepack";
    fromCodecs += "shorten";
    fromCodecs += "tta";
    fromCodecs += "wavpack";
    fromCodecs += "ra";
    fromCodecs += "sad";
    /// containers
    fromCodecs += "3gp";
    fromCodecs += "rm";
    /// video
    fromCodecs += "avi";
    fromCodecs += "mkv";
    fromCodecs += "webm";
    fromCodecs += "ogv";
    fromCodecs += "mpeg";
    fromCodecs += "mov";
    fromCodecs += "mp4";
    fromCodecs += "flv";
    fromCodecs += "wmv";
    fromCodecs += "rv";

    /// encode
    toCodecs += "wav";

    for( int i=0; i<fromCodecs.count(); i++ )
    {
        for( int j=0; j<toCodecs.count(); j++ )
        {
            if( fromCodecs.at(i) == "wav" && toCodecs.at(j) == "wav" )
                continue;

            ConversionPipeTrunk newTrunk;
            newTrunk.codecFrom = fromCodecs.at(i);
            newTrunk.codecTo = toCodecs.at(j);
            newTrunk.rating = 80;
            newTrunk.enabled = ( binaries["mplayer"] != "" );
            newTrunk.problemInfo = standardMessage( "decode_codec,backend", fromCodecs.at(i), "mplayer" ) + "\n" + standardMessage( "install_patented_backend", "mplayer" );
            newTrunk.data.hasInternalReplayGain = false;
            table.append( newTrunk );
        }
    }

    QSet<QString> codecs;
    codecs += QSet<QString>::fromList(fromCodecs);
    codecs += QSet<QString>::fromList(toCodecs);
    allCodecs = codecs.toList();

    return table;
}
Ejemplo n.º 20
0
/*!
  Applies the given \a command to the given \a backend.
*/
QScriptDebuggerResponse QScriptDebuggerCommandExecutor::execute(
    QScriptDebuggerBackend *backend,
    const QScriptDebuggerCommand &command)
{
    QScriptDebuggerResponse response;
    switch (command.type()) {
    case QScriptDebuggerCommand::None:
        break;

    case QScriptDebuggerCommand::Interrupt:
        backend->interruptEvaluation();
        break;

    case QScriptDebuggerCommand::Continue:
        if (backend->engine()->isEvaluating()) {
            backend->continueEvalution();
            response.setAsync(true);
        }
        break;

    case QScriptDebuggerCommand::StepInto: {
        QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount);
        int count = attr.isValid() ? attr.toInt() : 1;
        backend->stepInto(count);
        response.setAsync(true);
    }
    break;

    case QScriptDebuggerCommand::StepOver: {
        QVariant attr = command.attribute(QScriptDebuggerCommand::StepCount);
        int count = attr.isValid() ? attr.toInt() : 1;
        backend->stepOver(count);
        response.setAsync(true);
    }
    break;

    case QScriptDebuggerCommand::StepOut:
        backend->stepOut();
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::RunToLocation:
        backend->runToLocation(command.fileName(), command.lineNumber());
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::RunToLocationByID:
        backend->runToLocation(command.scriptId(), command.lineNumber());
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::ForceReturn: {
        int contextIndex = command.contextIndex();
        QScriptDebuggerValue value = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realValue = value.toScriptValue(engine);
        backend->returnToCaller(contextIndex, realValue);
        response.setAsync(true);
    }
    break;

    case QScriptDebuggerCommand::Resume:
        backend->resume();
        response.setAsync(true);
        break;

    case QScriptDebuggerCommand::SetBreakpoint: {
        QScriptBreakpointData data = command.breakpointData();
        if (!data.isValid())
            data = QScriptBreakpointData(command.fileName(), command.lineNumber());
        int id = backend->setBreakpoint(data);
        response.setResult(id);
    }
    break;

    case QScriptDebuggerCommand::DeleteBreakpoint: {
        int id = command.breakpointId();
        if (!backend->deleteBreakpoint(id))
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }
    break;

    case QScriptDebuggerCommand::DeleteAllBreakpoints:
        backend->deleteAllBreakpoints();
        break;

    case QScriptDebuggerCommand::GetBreakpoints: {
        QScriptBreakpointMap bps = backend->breakpoints();
        if (!bps.isEmpty())
            response.setResult(bps);
    }
    break;

    case QScriptDebuggerCommand::GetBreakpointData: {
        int id = command.breakpointId();
        QScriptBreakpointData data = backend->breakpointData(id);
        if (data.isValid())
            response.setResult(data);
        else
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }
    break;

    case QScriptDebuggerCommand::SetBreakpointData: {
        int id = command.breakpointId();
        QScriptBreakpointData data = command.breakpointData();
        if (!backend->setBreakpointData(id, data))
            response.setError(QScriptDebuggerResponse::InvalidBreakpointID);
    }
    break;

    case QScriptDebuggerCommand::GetScripts: {
        QScriptScriptMap scripts = backend->scripts();
        if (!scripts.isEmpty())
            response.setResult(scripts);
    }
    break;

    case QScriptDebuggerCommand::GetScriptData: {
        qint64 id = command.scriptId();
        QScriptScriptData data = backend->scriptData(id);
        if (data.isValid())
            response.setResult(data);
        else
            response.setError(QScriptDebuggerResponse::InvalidScriptID);
    }
    break;

    case QScriptDebuggerCommand::ScriptsCheckpoint:
        backend->scriptsCheckpoint();
        response.setResult(QVariant::fromValue(backend->scriptsDelta()));
        break;

    case QScriptDebuggerCommand::GetScriptsDelta:
        response.setResult(QVariant::fromValue(backend->scriptsDelta()));
        break;

    case QScriptDebuggerCommand::ResolveScript:
        response.setResult(backend->resolveScript(command.fileName()));
        break;

    case QScriptDebuggerCommand::GetBacktrace:
        response.setResult(backend->backtrace());
        break;

    case QScriptDebuggerCommand::GetContextCount:
        response.setResult(backend->contextCount());
        break;

    case QScriptDebuggerCommand::GetContextState: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(static_cast<int>(ctx->state()));
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }
    break;

    case QScriptDebuggerCommand::GetContextID: {
        int idx = command.contextIndex();
        if ((idx >= 0) && (idx < backend->contextCount()))
            response.setResult(backend->contextIds()[idx]);
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }
    break;

    case QScriptDebuggerCommand::GetContextInfo: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(QScriptContextInfo(ctx));
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }
    break;

    case QScriptDebuggerCommand::GetThisObject: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(ctx->thisObject());
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }
    break;

    case QScriptDebuggerCommand::GetActivationObject: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx)
            response.setResult(ctx->activationObject());
        else
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
    }
    break;

    case QScriptDebuggerCommand::GetScopeChain: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        if (ctx) {
            QScriptDebuggerValueList dest;
            QScriptValueList src = ctx->scopeChain();
            for (int i = 0; i < src.size(); ++i)
                dest.append(src.at(i));
            response.setResult(dest);
        } else {
            response.setError(QScriptDebuggerResponse::InvalidContextIndex);
        }
    }
    break;

    case QScriptDebuggerCommand::ContextsCheckpoint: {
        response.setResult(QVariant::fromValue(backend->contextsCheckpoint()));
    }
    break;

    case QScriptDebuggerCommand::GetPropertyExpressionValue: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        int lineNumber = command.lineNumber();
        QVariant attr = command.attribute(QScriptDebuggerCommand::UserAttribute);
        QStringList path = attr.toStringList();
        if (!ctx || path.isEmpty())
            break;
        QScriptContextInfo ctxInfo(ctx);
        if (ctx->callee().isValid()
                && ((lineNumber < ctxInfo.functionStartLineNumber())
                    || (lineNumber > ctxInfo.functionEndLineNumber()))) {
            break;
        }
        QScriptValueList objects;
        int pathIndex = 0;
        if (path.at(0) == QLatin1String("this")) {
            objects.append(ctx->thisObject());
            ++pathIndex;
        } else {
            objects << ctx->scopeChain();
        }
        for (int i = 0; i < objects.size(); ++i) {
            QScriptValue val = objects.at(i);
            for (int j = pathIndex; val.isValid() && (j < path.size()); ++j) {
                val = val.property(path.at(j));
            }
            if (val.isValid()) {
                bool hadException = (ctx->state() == QScriptContext::ExceptionState);
                QString str = val.toString();
                if (!hadException && backend->engine()->hasUncaughtException())
                    backend->engine()->clearExceptions();
                response.setResult(str);
                break;
            }
        }
    }
    break;

    case QScriptDebuggerCommand::GetCompletions: {
        QScriptContext *ctx = backend->context(command.contextIndex());
        QVariant attr = command.attribute(QScriptDebuggerCommand::UserAttribute);
        QStringList path = attr.toStringList();
        if (!ctx || path.isEmpty())
            break;
        QScriptValueList objects;
        QString prefix = path.last();
        QSet<QString> matches;
        if (path.size() > 1) {
            const QString &topLevelIdent = path.at(0);
            QScriptValue obj;
            if (topLevelIdent == QLatin1String("this")) {
                obj = ctx->thisObject();
            } else {
                QScriptValueList scopeChain;
                scopeChain = ctx->scopeChain();
                for (int i = 0; i < scopeChain.size(); ++i) {
                    QScriptValue oo = scopeChain.at(i).property(topLevelIdent);
                    if (oo.isObject()) {
                        obj = oo;
                        break;
                    }
                }
            }
            for (int i = 1; obj.isObject() && (i < path.size()-1); ++i)
                obj = obj.property(path.at(i));
            if (obj.isValid())
                objects.append(obj);
        } else {
            objects << ctx->scopeChain();
            QStringList keywords;
            keywords.append(QString::fromLatin1("this"));
            keywords.append(QString::fromLatin1("true"));
            keywords.append(QString::fromLatin1("false"));
            keywords.append(QString::fromLatin1("null"));
            for (int i = 0; i < keywords.size(); ++i) {
                const QString &kwd = keywords.at(i);
                if (isPrefixOf(prefix, kwd))
                    matches.insert(kwd);
            }
        }

        for (int i = 0; i < objects.size(); ++i) {
            QScriptValue obj = objects.at(i);
            while (obj.isObject()) {
                QScriptValueIterator it(obj);
                while (it.hasNext()) {
                    it.next();
                    QString propertyName = it.name();
                    if (isPrefixOf(prefix, propertyName))
                        matches.insert(propertyName);
                }
                obj = obj.prototype();
            }
        }
        QStringList matchesList = matches.toList();
        qStableSort(matchesList);
        response.setResult(matchesList);
    }
    break;

    case QScriptDebuggerCommand::NewScriptObjectSnapshot: {
        int id = backend->newScriptObjectSnapshot();
        response.setResult(id);
    }
    break;

    case QScriptDebuggerCommand::ScriptObjectSnapshotCapture: {
        int id = command.snapshotId();
        QScriptObjectSnapshot *snap = backend->scriptObjectSnapshot(id);
        Q_ASSERT(snap != 0);
        QScriptDebuggerValue object = command.scriptValue();
        Q_ASSERT(object.type() == QScriptDebuggerValue::ObjectValue);
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        Q_ASSERT(realObject.isObject());
        QScriptObjectSnapshot::Delta delta = snap->capture(realObject);
        QScriptDebuggerObjectSnapshotDelta result;
        result.removedProperties = delta.removedProperties;
        bool didIgnoreExceptions = backend->ignoreExceptions();
        backend->setIgnoreExceptions(true);
        for (int i = 0; i < delta.changedProperties.size(); ++i) {
            const QScriptValueProperty &src = delta.changedProperties.at(i);
            bool hadException = engine->hasUncaughtException();
            QString str = src.value().toString();
            if (!hadException && engine->hasUncaughtException())
                engine->clearExceptions();
            QScriptDebuggerValueProperty dest(src.name(), src.value(), str, src.flags());
            result.changedProperties.append(dest);
        }
        for (int j = 0; j < delta.addedProperties.size(); ++j) {
            const QScriptValueProperty &src = delta.addedProperties.at(j);
            bool hadException = engine->hasUncaughtException();
            QString str = src.value().toString();
            if (!hadException && engine->hasUncaughtException())
                engine->clearExceptions();
            QScriptDebuggerValueProperty dest(src.name(), src.value(), str, src.flags());
            result.addedProperties.append(dest);
        }
        backend->setIgnoreExceptions(didIgnoreExceptions);
        response.setResult(QVariant::fromValue(result));
    }
    break;

    case QScriptDebuggerCommand::DeleteScriptObjectSnapshot: {
        int id = command.snapshotId();
        backend->deleteScriptObjectSnapshot(id);
    }
    break;

    case QScriptDebuggerCommand::NewScriptValueIterator: {
        QScriptDebuggerValue object = command.scriptValue();
        Q_ASSERT(object.type() == QScriptDebuggerValue::ObjectValue);
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        Q_ASSERT(realObject.isObject());
        int id = backend->newScriptValueIterator(realObject);
        response.setResult(id);
    }
    break;

    case QScriptDebuggerCommand::GetPropertiesByIterator: {
        int id = command.iteratorId();
        int count = 1000;
        QScriptValueIterator *it = backend->scriptValueIterator(id);
        Q_ASSERT(it != 0);
        QScriptDebuggerValuePropertyList props;
        for (int i = 0; (i < count) && it->hasNext(); ++i) {
            it->next();
            QString name = it->name();
            QScriptValue value = it->value();
            QString valueAsString = value.toString();
            QScriptValue::PropertyFlags flags = it->flags();
            QScriptDebuggerValueProperty prp(name, value, valueAsString, flags);
            props.append(prp);
        }
        response.setResult(props);
    }
    break;

    case QScriptDebuggerCommand::DeleteScriptValueIterator: {
        int id = command.iteratorId();
        backend->deleteScriptValueIterator(id);
    }
    break;

    case QScriptDebuggerCommand::Evaluate: {
        int contextIndex = command.contextIndex();
        QString program = command.program();
        QString fileName = command.fileName();
        int lineNumber = command.lineNumber();
        backend->evaluate(contextIndex, program, fileName, lineNumber);
        response.setAsync(true);
    }
    break;

    case QScriptDebuggerCommand::ScriptValueToString: {
        QScriptDebuggerValue value = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realValue = value.toScriptValue(engine);
        response.setResult(realValue.toString());
    }
    break;

    case QScriptDebuggerCommand::SetScriptValueProperty: {
        QScriptDebuggerValue object = command.scriptValue();
        QScriptEngine *engine = backend->engine();
        QScriptValue realObject = object.toScriptValue(engine);
        QScriptDebuggerValue value = command.subordinateScriptValue();
        QScriptValue realValue = value.toScriptValue(engine);
        QString name = command.name();
        realObject.setProperty(name, realValue);
    }
    break;

    case QScriptDebuggerCommand::ClearExceptions:
        backend->engine()->clearExceptions();
        break;

    case QScriptDebuggerCommand::UserCommand:
    case QScriptDebuggerCommand::MaxUserCommand:
        break;
    }
    return response;
}
Ejemplo n.º 21
0
bool BanPair::isBanned(const QString &general){
    return AllBanSet.contains(general);
}
static int convertTo_QSet_0101QAbstractState(PyObject *sipPy,void **sipCppPtrV,int *sipIsErr,PyObject *sipTransferObj)
{
    QSet<QAbstractState *> **sipCppPtr = reinterpret_cast<QSet<QAbstractState *> **>(sipCppPtrV);

#line 456 "/home/tsheasha/GUC/Bachelors/android-python27/python-build/PyQt-x11-gpl-4.8/sip/QtCore/qset.sip"
    PyObject *it = PyObject_GetIter(sipPy), *itm;

    // Check the type if that is all that is required.
    if (sipIsErr == NULL)
    {
        if (it == NULL)
            return 0;

        while ((itm = PyIter_Next(it)) != NULL)
        {
            int ok = sipCanConvertToType(itm, sipType_QAbstractState, 0);

            Py_DECREF(itm);

            if (!ok)
            {
                Py_DECREF(it);
                return 0;
            }
        }

        Py_DECREF(it);
        return 1;
    }

    if (it == NULL)
    {
        *sipIsErr = 1;
        return 0;
    }

    QSet<QAbstractState *> *qs = new QSet<QAbstractState *>;

    while ((itm = PyIter_Next(it)) != NULL)
    {
        QAbstractState *t = reinterpret_cast<QAbstractState *>(sipConvertToType(itm, sipType_QAbstractState, sipTransferObj, 0, 0, sipIsErr));

        Py_DECREF(itm);

        if (*sipIsErr)
        {
            delete qs;
            Py_DECREF(it);
            return 0;
        }

        qs->insert(t);
    }

    Py_DECREF(it);

    *sipCppPtr = qs;

    return sipGetState(sipTransferObj);
#line 138 "sipQtCoreQSet0101QAbstractState.cpp"
}
Ejemplo n.º 23
0
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, int nRefHeight)
{
    mpq total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    if ( nRefHeight < 0 )
        nRefHeight = nBestHeight;

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    if(total > getBalance(nRefHeight))
    {
        return AmountExceedsBalance;
    }

    mpq qBalReq = total + nTransactionFee;
    if(qBalReq > getBalance(nRefHeight))
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, mpq> > vecSend;
        foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetDestination(CVertiCoinAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        mpq nFeeRequired = 0;
        bool fCreated = wallet->CreateTransaction(vecSend, nRefHeight, wtx, keyChange, nFeeRequired);

        if(!fCreated)
        {
            if(qBalReq > wallet->GetBalance(nRefHeight))
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
        if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
    }
Ejemplo n.º 24
0
bool QTextOdfWriter::writeAll()
{
    if (m_createArchive)
        m_strategy = new QZipStreamStrategy(m_device);
    else
        m_strategy = new QXmlStreamStrategy(m_device);

    if (!m_device->isWritable() && ! m_device->open(QIODevice::WriteOnly)) {
        qWarning() << "QTextOdfWriter::writeAll: the device can not be opened for writing";
        return false;
    }
    QXmlStreamWriter writer(m_strategy->contentStream);
#ifndef QT_NO_TEXTCODEC
    if (m_codec)
        writer.setCodec(m_codec);
#endif
    // prettyfy
    writer.setAutoFormatting(true);
    writer.setAutoFormattingIndent(2);

    writer.writeNamespace(officeNS, QString::fromLatin1("office"));
    writer.writeNamespace(textNS, QString::fromLatin1("text"));
    writer.writeNamespace(styleNS, QString::fromLatin1("style"));
    writer.writeNamespace(foNS, QString::fromLatin1("fo"));
    writer.writeNamespace(tableNS, QString::fromLatin1("table"));
    writer.writeNamespace(drawNS, QString::fromLatin1("draw"));
    writer.writeNamespace(xlinkNS, QString::fromLatin1("xlink"));
    writer.writeNamespace(svgNS, QString::fromLatin1("svg"));
    writer.writeStartDocument();
    writer.writeStartElement(officeNS, QString::fromLatin1("document-content"));
    writer.writeAttribute(officeNS, QString::fromLatin1("version"), QString::fromLatin1("1.2"));

    // add fragments. (for character formats)
    QTextDocumentPrivate::FragmentIterator fragIt = m_document->docHandle()->begin();
    QSet<int> formats;
    while (fragIt != m_document->docHandle()->end()) {
        const QTextFragmentData * const frag = fragIt.value();
        formats << frag->format;
        ++fragIt;
    }

    // add blocks (for blockFormats)
    QTextDocumentPrivate::BlockMap &blocks = m_document->docHandle()->blockMap();
    QTextDocumentPrivate::BlockMap::Iterator blockIt = blocks.begin();
    while (blockIt != blocks.end()) {
        const QTextBlockData * const block = blockIt.value();
        formats << block->format;
        ++blockIt;
    }

    // add objects for lists, frames and tables
    QVector<QTextFormat> allFormats = m_document->allFormats();
    QList<int> copy = formats.toList();
    for (QList<int>::Iterator iter = copy.begin(); iter != copy.end(); ++iter) {
        QTextObject *object = m_document->objectForFormat(allFormats[*iter]);
        if (object)
            formats << object->formatIndex();
    }

    writeFormats(writer, formats);

    writer.writeStartElement(officeNS, QString::fromLatin1("body"));
    writer.writeStartElement(officeNS, QString::fromLatin1("text"));
    QTextFrame *rootFrame = m_document->rootFrame();
    writeFrame(writer, rootFrame);
    writer.writeEndElement(); // text
    writer.writeEndElement(); // body
    writer.writeEndElement(); // document-content
    writer.writeEndDocument();
    delete m_strategy;
    m_strategy = 0;

    return true;
}
Ejemplo n.º 25
0
QT_BEGIN_NAMESPACE

static const QSet<QString> &qscriptKeywords() {
    static QSet<QString> keywords;
    if (keywords.empty()) {
        keywords.insert(QLatin1String("Infinity"));
        keywords.insert(QLatin1String("NaN"));
        keywords.insert(QLatin1String("abstract"));
        keywords.insert(QLatin1String("boolean"));
        keywords.insert(QLatin1String("break"));
        keywords.insert(QLatin1String("byte"));
        keywords.insert(QLatin1String("case"));
        keywords.insert(QLatin1String("catch"));
        keywords.insert(QLatin1String("char"));
        keywords.insert(QLatin1String("class"));
        keywords.insert(QLatin1String("const"));
        keywords.insert(QLatin1String("constructor"));
        keywords.insert(QLatin1String("continue"));
        keywords.insert(QLatin1String("debugger"));
        keywords.insert(QLatin1String("default"));
        keywords.insert(QLatin1String("delete"));
        keywords.insert(QLatin1String("do"));
        keywords.insert(QLatin1String("double"));
        keywords.insert(QLatin1String("else"));
        keywords.insert(QLatin1String("enum"));
        keywords.insert(QLatin1String("export"));
        keywords.insert(QLatin1String("extends"));
        keywords.insert(QLatin1String("false"));
        keywords.insert(QLatin1String("final"));
        keywords.insert(QLatin1String("finally"));
        keywords.insert(QLatin1String("float"));
        keywords.insert(QLatin1String("for"));
        keywords.insert(QLatin1String("function"));
        keywords.insert(QLatin1String("goto"));
        keywords.insert(QLatin1String("if"));
        keywords.insert(QLatin1String("implements"));
        keywords.insert(QLatin1String("import"));
        keywords.insert(QLatin1String("in"));
        keywords.insert(QLatin1String("instanceof"));
        keywords.insert(QLatin1String("int"));
        keywords.insert(QLatin1String("interface"));
        keywords.insert(QLatin1String("long"));
        keywords.insert(QLatin1String("native"));
        keywords.insert(QLatin1String("new"));
        keywords.insert(QLatin1String("package"));
        keywords.insert(QLatin1String("private"));
        keywords.insert(QLatin1String("protected"));
        keywords.insert(QLatin1String("public"));
        keywords.insert(QLatin1String("return"));
        keywords.insert(QLatin1String("short"));
        keywords.insert(QLatin1String("static"));
        keywords.insert(QLatin1String("super"));
        keywords.insert(QLatin1String("switch"));
        keywords.insert(QLatin1String("synchronized"));
        keywords.insert(QLatin1String("this"));
        keywords.insert(QLatin1String("throw"));
        keywords.insert(QLatin1String("throws"));
        keywords.insert(QLatin1String("transient"));
        keywords.insert(QLatin1String("true"));
        keywords.insert(QLatin1String("try"));
        keywords.insert(QLatin1String("typeof"));
        keywords.insert(QLatin1String("undefined"));
        keywords.insert(QLatin1String("var"));
        keywords.insert(QLatin1String("void"));
        keywords.insert(QLatin1String("volatile"));
        keywords.insert(QLatin1String("while"));
        keywords.insert(QLatin1String("with"));    // end
    }
    return keywords;
}
Ejemplo n.º 26
0
QStringList QgsStyle::findSymbols( StyleEntity type, const QString& qword )
{
  if ( !mCurrentDB )
  {
    QgsDebugMsg( "Sorry! Cannot open database to search" );
    return QStringList();
  }

  // first find symbols with matching name
  QString item = ( type == SymbolEntity ) ? "symbol" : "colorramp";
  char *query = sqlite3_mprintf( "SELECT name FROM %q WHERE name LIKE '%%%q%%'",
                                 item.toUtf8().constData(), qword.toUtf8().constData() );

  sqlite3_stmt *ppStmt;
  int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr );

  QSet< QString > symbols;
  while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    symbols << QString::fromUtf8( reinterpret_cast< const char * >( sqlite3_column_text( ppStmt, 0 ) ) );
  }

  sqlite3_finalize( ppStmt );

  // next add symbols with matching tags
  query = sqlite3_mprintf( "SELECT id FROM tag WHERE name LIKE '%%%q%%'", qword.toUtf8().constData() );
  nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );

  QStringList tagids;
  while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    tagids << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) );
  }

  sqlite3_finalize( ppStmt );


  QString dummy = tagids.join( QStringLiteral( ", " ) );

  if ( type == SymbolEntity )
  {
    query = sqlite3_mprintf( "SELECT symbol_id FROM tagmap WHERE tag_id IN (%q)",
                             dummy.toUtf8().constData() );
  }
  else
  {
    query = sqlite3_mprintf( "SELECT colorramp_id FROM ctagmap WHERE tag_id IN (%q)",
                             dummy.toUtf8().constData() );
  }
  nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );

  QStringList symbolids;
  while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    symbolids << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) );
  }

  sqlite3_finalize( ppStmt );


  dummy = symbolids.join( QStringLiteral( ", " ) );
  query = sqlite3_mprintf( "SELECT name FROM %q  WHERE id IN (%q)",
                           item.toUtf8().constData(), dummy.toUtf8().constData() );
  nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );
  while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    symbols << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) );
  }

  sqlite3_finalize( ppStmt );

  return symbols.toList();
}
Ejemplo n.º 27
0
QScriptObjectSnapshot::Delta QScriptObjectSnapshot::capture(const QScriptValue &object)
{
    Delta result;
    QMap<QString, QScriptValueProperty> currProps;
    QHash<QString, int> propertyNameToIndex;
    {
        int i = 0;
        QScriptValueIterator it(object);
        while (it.hasNext()) {
            it.next();
            QScriptValueProperty prop(it.name(), it.value(), it.flags());
            currProps.insert(it.name(), prop);
            propertyNameToIndex.insert(it.name(), i);
            ++i;
        }
        if (object.prototype().isValid()) {
            QString __proto__ = QString::fromLatin1("__proto__");
            QScriptValueProperty protoProp(
                __proto__, object.prototype(),
                QScriptValue::Undeletable | QScriptValue::ReadOnly);
            currProps.insert(__proto__, protoProp);
            propertyNameToIndex.insert(__proto__, i);
            ++i;
        }
    }

    QSet<QString> prevSet;
    for (int i = 0; i < m_properties.size(); ++i)
        prevSet.insert(m_properties.at(i).name());
    QSet<QString> currSet = currProps.keys().toSet();
    QSet<QString> removedProperties = prevSet - currSet;
    QSet<QString> addedProperties = currSet - prevSet;
    QSet<QString> maybeChangedProperties = currSet & prevSet;

    {
        QMap<int, QScriptValueProperty> am;
        QSet<QString>::const_iterator it;
        for (it = addedProperties.constBegin(); it != addedProperties.constEnd(); ++it) {
            int idx = propertyNameToIndex[*it];
            am[idx] = currProps[*it];
        }
        result.addedProperties = am.values();
    }

    {
        QSet<QString>::const_iterator it;
        for (it = maybeChangedProperties.constBegin(); it != maybeChangedProperties.constEnd(); ++it) {
            const QScriptValueProperty &p1 = currProps[*it];
            const QScriptValueProperty &p2 = findProperty(*it);
            if (!_q_equal(p1.value(), p2.value())
                || (p1.flags() != p2.flags())) {
                result.changedProperties.append(p1);
            }
        }
    }

    result.removedProperties = removedProperties.toList();

    m_properties = currProps.values();

    return result;
}
Ejemplo n.º 28
0
int addTestContact(const QString &name, const QString &remoteUid, const QString &localUid)
{
    QString contactUri = QString("<testcontact:%1>").arg(contactNumber++);

    QContact contact;

    QContactSyncTarget syncTarget;
    syncTarget.setSyncTarget(QLatin1String("commhistory-tests"));
    if (!contact.saveDetail(&syncTarget)) {
        qWarning() << "Unable to add sync target to contact:" << contactUri;
        return -1;
    }

    if (!localUid.isEmpty() && localUid.indexOf("/ring/tel/") == -1) {
        // Create a metadata detail to link the contact with the account
        QContactOriginMetadata metadata;
        metadata.setGroupId(localUid);
        metadata.setId(remoteUid);
        metadata.setEnabled(true);
        if (!contact.saveDetail(&metadata)) {
            qWarning() << "Unable to add metadata to contact:" << contactUri;
            return false;
        }
    }

    QString normal = CommHistory::normalizePhoneNumber(remoteUid);
    if (normal.isEmpty()) {
        QContactOnlineAccount qcoa;
        qcoa.setValue(QContactOnlineAccount__FieldAccountPath, localUid);
        qcoa.setAccountUri(remoteUid);
        if (!contact.saveDetail(&qcoa)) {
            qWarning() << "Unable to add online account to contact:" << contactUri;
            return -1;
        }
    } else {
        QContactPhoneNumber phoneNumberDetail;
        phoneNumberDetail.setNumber(remoteUid);
        if (!contact.saveDetail(&phoneNumberDetail)) {
            qWarning() << "Unable to add phone number to contact:" << contactUri;
            return -1;
        }
    }

    QContactName nameDetail;
    nameDetail.setLastName(name);
    if (!contact.saveDetail(&nameDetail)) {
        qWarning() << "Unable to add name to contact:" << contactUri;
        return -1;
    }

    if (!manager()->saveContact(&contact)) {
        qWarning() << "Unable to store contact:" << contactUri;
        return -1;
    }

    // We should return the aggregated instance of this contact
    QContactRelationshipFilter filter;
    filter.setRelatedContactRole(QContactRelationship::Second);

    filter.setRelatedContact(contact);
    filter.setRelationshipType(QContactRelationship::Aggregates());

    foreach (const QContactId &id, manager()->contactIds(filter)) {
        qDebug() << "********** contact id" << id;
        addedContactIds.insert(id);
        return internalContactId(id);
    }
Ejemplo n.º 29
0
Archivo: Song.cpp Proyecto: LMMS/lmms
void Song::processAutomations(const TrackList &tracklist, MidiTime timeStart, fpp_t)
{
	AutomatedValueMap values;

	QSet<const AutomatableModel*> recordedModels;

	TrackContainer* container = this;
	int tcoNum = -1;

	switch (m_playMode)
	{
	case Mode_PlaySong:
		break;
	case Mode_PlayBB:
	{
		Q_ASSERT(tracklist.size() == 1);
		Q_ASSERT(tracklist.at(0)->type() == Track::BBTrack);
		auto bbTrack = dynamic_cast<BBTrack*>(tracklist.at(0));
		auto bbContainer = Engine::getBBTrackContainer();
		container = bbContainer;
		tcoNum = bbTrack->index();
	}
		break;
	default:
		return;
	}

	values = container->automatedValuesAt(timeStart, tcoNum);
	TrackList tracks = container->tracks();

	Track::tcoVector tcos;
	for (Track* track : tracks)
	{
		if (track->type() == Track::AutomationTrack) {
			track->getTCOsInRange(tcos, 0, timeStart);
		}
	}

	// Process recording
	for (TrackContentObject* tco : tcos)
	{
		auto p = dynamic_cast<AutomationPattern *>(tco);
		MidiTime relTime = timeStart - p->startPosition();
		if (p->isRecording() && relTime >= 0 && relTime < p->length())
		{
			const AutomatableModel* recordedModel = p->firstObject();
			p->recordValue(relTime, recordedModel->value<float>());

			recordedModels << recordedModel;
		}
	}

	// Apply values
	for (auto it = values.begin(); it != values.end(); it++)
	{
		if (! recordedModels.contains(it.key()))
		{
			it.key()->setAutomatedValue(it.value());
		}
	}
}
Ejemplo n.º 30
0
polyHull* LappedUtils::getPolyHull(QImage* blob,int iterations)
{
    QImage img = *blob;
    int w = img.width();
    int h = img.height();

    uchar* imgdata = img.bits();

    QQueue<vert2d*>* vQu = new QQueue<vert2d*>();
    QList<vert2d*>* vLi = new QList<vert2d*>();//just for debugging/drawing
    QList<edge2d*>* eLi = new QList<edge2d*>();
    QHash<QPair<vert2d*,vert2d*>,edge2d*>* edgesMade = new QHash<QPair<vert2d*,vert2d*>,edge2d*>();
    QHash<QPair<int,int>,vert2d*>* vertsMade = new QHash<QPair<int,int>,vert2d*>();

    vert2d* vseed;
    for(int x=1;x<w-1;x++)
    {bool br=false;
        for(int y=1;y<h-1;y++)
        {
            if(imgdata[4*(y*w+x)]<255 && (imgdata[4*((y+1)*w+x)]==255 || imgdata[4*((y-1)*w+x)]==255 || imgdata[4*(y*w+(x+1))]==255 || imgdata[4*(y*w+(x-1))]==255))
            {
                vseed = new vert2d(x,y);
                vQu->append(vseed);
                vLi->append(vseed);
                vertsMade->insert(qMakePair(x,y),vseed);
                br=true;
                break;
            }
        }if(br)break;
    }

    while(!vQu->empty())
    {
        vert2d* v = vQu->dequeue();
        //cout<<"dequeued ("<<v->x<<","<<v->y<<")"<<endl;
        for(int x2=v->x-1;x2<=v->x+1;x2++)
        {
            for(int y2=v->y-1;y2<=v->y+1;y2++)
            {
                if(x2==v->x && y2==v->y){continue;}
                if(imgdata[4*(y2*w+x2)]<255 && (imgdata[4*((y2+1)*w+x2)]==255 || imgdata[4*((y2-1)*w+x2)]==255 || imgdata[4*(y2*w+(x2+1))]==255 || imgdata[4*(y2*w+(x2-1))]==255))
                {
                    vert2d* v2;
                    if(!vertsMade->contains(qMakePair(x2,y2)))
                    {
                        v2 = new vert2d(x2,y2);
                        vQu->append(v2);
                        vLi->append(v2);
                        vertsMade->insert(qMakePair(x2,y2),v2);
                    }
                    else
                    {
                        v2 = vertsMade->value(qMakePair(x2,y2));
                    }
                    if(!edgesMade->contains(qMakePair(v,v2)))
                    {
                        edge2d* e = new edge2d(v,v2);
                        edgesMade->insert(qMakePair(v,v2),e);
                        edgesMade->insert(qMakePair(v2,v),e);
                        eLi->append(e); //cout<<"157- "; printEdge(e);
                        v->addEdge(e);
                        v2->addEdge(e);
                    }
                }
            }
        }
    }


    //first, remove all collinear points
    vert2d* vs;
    vert2d* ve;
    vert2d* vnew;

    vs=vseed;
    //cout<<"vs: ";vs->print();

    if(vs->e1->v1==vs)
        ve = (vs->e1)->v2;
    else
        ve = (vs->e1)->v1;
    //cout<<"ve: ";ve->print();

    vnew=ve->otherAdjVert(vs);
    //cout<<"new: ";vnew->print();

    do
    {
        while(ccw(vs,ve,vnew)==0)
        {
            edge2d* e = new edge2d(vs,vnew);
            edgesMade->insert(qMakePair(vs,vnew),e);
            edgesMade->insert(qMakePair(vnew,vs),e);
            eLi->append(e); //cout<<"192- "; printEdge(e);

            edge2d* e1 = edgesMade->value(qMakePair(vs,ve));
            //cout<<"e1: ";printEdge(e1);
            edge2d* e2 = edgesMade->value(qMakePair(ve,vnew));
            //cout<<"e2: ";printEdge(e2);

            vert2d* temp = vnew->otherAdjVert(ve);

            vs->replaceEdge(e1,e);
            vnew->replaceEdge(e2,e);

            //remove e1,e2 from edgesMade and delete
            //cout<<"removing e1:"<<endl;printEdge(e1);
            edgesMade->remove(qMakePair(e1->v1,e1->v2));
            edgesMade->remove(qMakePair(e1->v2,e1->v1));
            edgesMade->remove(qMakePair(e2->v1,e2->v2));
            edgesMade->remove(qMakePair(e2->v2,e2->v1));
            eLi->removeAll(e1);
            eLi->removeAll(e2);
            delete e1;
            delete e2;

            //remove ve from vLi, vertsMade and delete
            vLi->removeAll(ve);
            vertsMade->remove(qMakePair(ve->x,ve->y));
            delete ve;


            ve=vnew;
            vnew = temp;
        }
        vs = ve;
        ve = vnew;
        vnew = ve->otherAdjVert(vs);
    }while(vs!=vseed);

    //get the leftmost vert2d
    assert(vertsMade->contains(qMakePair(vseed->x,vseed->y)));
    vert2d* pve1;
    vert2d* pve2;

    //at this point vs--->ve should be in the CLOCKWISE direction
    //one simplification pass:

    //get four points to work on, and next one to start from
    //if one of the points other than the first was vseed, set done flag
    //arrange pointers, etc for our four points

    for(int i=0;i<iterations;i++)
    {
        // cout<<"beginning. edgecount: "<<eLi->size()<<endl;

        if(vseed->e1->v1 == vseed)
            pve1=vseed->e1->v2;
        else
            pve1=vseed->e1->v1;
        pve2 = vseed->otherAdjVert(pve1);

        vs=vseed;
        if(pve1->y<pve2->y)
            ve=pve1;
        else if(pve1->y>pve2->y)
            ve=pve2;
        else
            cout<<"that thing that you said would never happen happened"<<endl;

        vert2d* A = vseed;
        vert2d* B = ve;
        vert2d* C = B->otherAdjVert(A);
        vert2d* D = C->otherAdjVert(B);
        vert2d* nextA = D->otherAdjVert(C);


        bool passDoneFlag=false;
        while(!passDoneFlag)
        {
            //we have our four points A-->B-->C-->D
            if(ccw(A,B,C)==1)
            {//angle1 convex
                if(ccw(B,C,D)==1)
                {//both angles convex /'''\
                    //ultimately remove B and C, first project AB and CD to intersection
                    int isecx, isecy;
                    if(B->x==A->x)
                    {
                        int mCD = (D->y - C->y)/(D->x - C->x);
                        int bCD = C->y - mCD*C->x;
                        isecx = B->x;
                        isecy = mCD*B->x+bCD;
                    }
                    else if(D->x==C->x)
                    {
                        int mAB = (B->y - A->y)/(B->x - A->x);
                        int bAB = A->y - mAB*A->x;
                        isecx = D->x;
                        isecy = mAB*D->x+bAB;
                    }
                    else
                    {
                        int mAB = (B->y - A->y)/(B->x - A->x);
                        int mCD = (D->y - C->y)/(D->x - C->x);
                        int bAB = A->y - mAB*A->x;
                        int bCD = C->y - mCD*C->x;
                        if(mAB-mCD==0)
                        {//not sure when this stupid case happens
                            isecx =-100;
                            isecy =-100;
                        }
                        else
                        {
                            isecx = (bCD - bAB)/(mAB - mCD);
                            isecy = mAB * isecx + bAB;
                        }
                    }

                    if(isecx>1 && isecx<img.width()-1 && isecy>1 && isecy<img.width()-1)
                    {
                        vert2d* VN = new vert2d(isecx,isecy);
                        vertsMade->insert(qMakePair(isecx,isecy),VN);
                        vLi->append(VN);

                        edge2d* eAVN = new edge2d(A,VN);
                        edgesMade->insert(qMakePair(A,VN),eAVN);
                        edgesMade->insert(qMakePair(VN,A),eAVN);
                        eLi->append(eAVN);// cout<<"317- "; printEdge(eAVN);
                        edge2d* eVND = new edge2d(VN,D);
                        edgesMade->insert(qMakePair(D,VN),eVND);
                        edgesMade->insert(qMakePair(VN,D),eVND);
                        eLi->append(eVND); //cout<<"321- "; printEdge(eVND);

                        VN->addEdge(eAVN);
                        VN->addEdge(eVND);

                        edge2d* AB = edgesMade->value(qMakePair(A,B));
                        edge2d* CD = edgesMade->value(qMakePair(C,D));
                        A->replaceEdge(AB,eAVN);
                        D->replaceEdge(CD,eVND);

                        edgesMade->remove(qMakePair(A,B));
                        edgesMade->remove(qMakePair(B,A));
                        edgesMade->remove(qMakePair(C,D));
                        edgesMade->remove(qMakePair(D,C));
                        eLi->removeAll(AB);
                        eLi->removeAll(CD);
                        vLi->removeAll(B);
                        vLi->removeAll(C);
                        vertsMade->remove(qMakePair(B->x,B->y));
                        vertsMade->remove(qMakePair(C->x,C->y));
                        delete AB;
                        delete CD;
                        delete B;
                        delete C;
                    }



                }
                else
                {// convex-concave  /\/
                    //remove C
                    edge2d* e = new edge2d(B,D);
                    edgesMade->insert(qMakePair(B,D),e);
                    edgesMade->insert(qMakePair(D,B),e);
                    eLi->append(e); //cout<<"356- "; printEdge(e);
                    edge2d* oldBe = edgesMade->value(qMakePair(B,C));
                    edge2d* oldDe = edgesMade->value(qMakePair(C,D));
                    B->replaceEdge(oldBe,e);
                    D->replaceEdge(oldDe,e);
                    edgesMade->remove(qMakePair(B,C));
                    edgesMade->remove(qMakePair(C,B));
                    edgesMade->remove(qMakePair(C,D));
                    edgesMade->remove(qMakePair(D,C));
                    eLi->removeAll(oldBe);
                    eLi->removeAll(oldDe);
                    delete oldBe;
                    delete oldDe;
                    vLi->removeAll(C);
                    vertsMade->remove(qMakePair(C->x,C->y));
                    delete C;
                }

            }
            else if(ccw(A,B,C)==-1)
            {
                if(ccw(B,C,D)==0)
                {
                    edge2d* e = new edge2d(B,D);
                    edgesMade->insert(qMakePair(B,D),e);
                    edgesMade->insert(qMakePair(D,B),e);
                    eLi->append(e); //cout<<"382- "; printEdge(e);
                    edge2d* oldBe = edgesMade->value(qMakePair(B,C));
                    edge2d* oldDe = edgesMade->value(qMakePair(C,D));
                    B->replaceEdge(oldBe,e);
                    D->replaceEdge(oldDe,e);
                    edgesMade->remove(qMakePair(B,C));
                    edgesMade->remove(qMakePair(C,B));
                    edgesMade->remove(qMakePair(C,D));
                    edgesMade->remove(qMakePair(D,C));
                    eLi->removeAll(oldBe);
                    eLi->removeAll(oldDe);
                    delete oldBe;
                    delete oldDe;
                    vLi->removeAll(C);
                    vertsMade->remove(qMakePair(C->x,C->y));
                    delete C;
                }

                else//if(isecx>1 && isecx<img.width()-1 && isecy>1 && isecy<img.width()-1)
                {
                    //concave-convex \/\  OR
                    //both angles concave \__/
                    //either way: remove B
                    edge2d* e = new edge2d(A,C);
                    edgesMade->insert(qMakePair(A,C),e);
                    edgesMade->insert(qMakePair(C,A),e);
                    eLi->append(e);// cout<<"407- "; printEdge(e);
                    edge2d* oldAe = edgesMade->value(qMakePair(A,B));
                    edge2d* oldCe = edgesMade->value(qMakePair(B,C));
                    A->replaceEdge(oldAe,e);
                    C->replaceEdge(oldCe,e);
                    edgesMade->remove(qMakePair(A,B));
                    edgesMade->remove(qMakePair(B,A));
                    edgesMade->remove(qMakePair(B,C));
                    edgesMade->remove(qMakePair(C,B));
                    eLi->removeAll(oldAe);
                    eLi->removeAll(oldCe);
                    delete oldAe;
                    delete oldCe;
                    vLi->removeAll(B);
                    vertsMade->remove(qMakePair(B->x,B->y));
                    delete B;
                }
            }
            else
            {//a,b,c straight.  remove b
                edge2d* e = new edge2d(A,C);
                edgesMade->insert(qMakePair(A,C),e);
                edgesMade->insert(qMakePair(C,A),e);
                eLi->append(e); //cout<<"430- "; printEdge(e);
                edge2d* oldAe = edgesMade->value(qMakePair(A,B));
                edge2d* oldCe = edgesMade->value(qMakePair(B,C));
                A->replaceEdge(oldAe,e);
                C->replaceEdge(oldCe,e);
                edgesMade->remove(qMakePair(A,B));
                edgesMade->remove(qMakePair(B,A));
                edgesMade->remove(qMakePair(B,C));
                edgesMade->remove(qMakePair(C,B));
                eLi->removeAll(oldAe);
                eLi->removeAll(oldCe);
                delete oldAe;
                delete oldCe;
                vLi->removeAll(B);
                vertsMade->remove(qMakePair(B->x,B->y));
                delete B;
            }
            //advance!
            //cout<<"advancing"<<endl;
            A = nextA;
            B = nextA->otherAdjVert(D);
            C = B->otherAdjVert(A);
            D = C->otherAdjVert(B);
            nextA = D->otherAdjVert(C);
            //cout<<"done advancing"<<endl;
            if(A==vseed || B==vseed || C==vseed || D==vseed)
            {
                passDoneFlag=true;
            }
        }
    }


    delete eLi;
    eLi = new QList<edge2d*>();

    QSet<edge2d*>* visitedE = new QSet<edge2d*>();
    for(int i=0; i<vLi->size(); i++)
    {
        vert2d* vv = vLi->at(i);
        if(!visitedE->contains(vv->e1))
        {
            eLi->append(vv->e1);
            visitedE->insert(vv->e1);
        }
        if(!visitedE->contains(vv->e2))
        {
            eLi->append(vv->e2);
            visitedE->insert(vv->e2);
        }
    }




    polyHull* pHull = new polyHull(vLi,eLi);

    //pHull->print();

    pHull->imgh = h;
    pHull->imgw = w;


    //segfault??????
    delete edgesMade;
    delete vertsMade;
    delete vQu;
    delete visitedE;


    return pHull;
}