示例#1
0
//! [region start]
QRegion MyDecoration::region(const QWidget *widget, const QRect &insideRect,
                             int decorationRegion)
{
    //! [region start]
    //! [calculate the positions of buttons based on the window flags used]
    QHash<DecorationRegion, int> buttons;
    Qt::WindowFlags flags = widget->windowFlags();
    int dx = -buttonMargin - buttonWidth;

    foreach (Qt::WindowType button, buttonHints) {
        if (flags & button) {
            int x = (buttons.size() + 1) * dx;
            buttons[buttonHintMap[button]] = x;
        }
    }
    //! [calculate the positions of buttons based on the window flags used]

    //! [calculate the extent of the title]
    int titleRightMargin = buttons.size() * dx;

    QRect outsideRect(insideRect.left() - border,
                      insideRect.top() - titleHeight - border,
                      insideRect.width() + 2 * border,
                      insideRect.height() + titleHeight + 2 * border);
    //! [calculate the extent of the title]

    //! [check for all regions]
    QRegion region;

    if (decorationRegion == All) {
        region += QRegion(outsideRect) - QRegion(insideRect);
        return region;
    }
    //! [check for all regions]

    //! [compose a region based on the decorations specified]
    if (decorationRegion & Title) {
        QRect rect = outsideRect.adjusted(border, border, -border, 0);
        rect.setHeight(titleHeight);

        // Adjust the width to accommodate buttons.
        rect.setWidth(qMax(0, rect.width() + titleRightMargin));
        region += rect;
    }
    if (decorationRegion & Top) {
        QRect rect = outsideRect.adjusted(border, 0, -border, 0);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & Left) {
        QRect rect = outsideRect.adjusted(0, border, 0, -border);
        rect.setWidth(border);
        region += rect;
    }
    if (decorationRegion & Right) {
        QRect rect = outsideRect.adjusted(0, border, 0, -border);
        rect.setLeft(rect.right() + 1 - border);
        region += rect;
    }
    if (decorationRegion & Bottom) {
        QRect rect = outsideRect.adjusted(border, 0, -border, 0);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    if (decorationRegion & TopLeft) {
        QRect rect = outsideRect;
        rect.setWidth(border);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & TopRight) {
        QRect rect = outsideRect;
        rect.setLeft(rect.right() + 1 - border);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & BottomLeft) {
        QRect rect = outsideRect;
        rect.setWidth(border);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    if (decorationRegion & BottomRight) {
        QRect rect = outsideRect;
        rect.setLeft(rect.right() + 1 - border);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    //! [compose a region based on the decorations specified]

    //! [add a region for each button only if it is present]
    foreach (QDecoration::DecorationRegion testRegion, stateRegions) {
        if (decorationRegion & testRegion and buttons.contains(testRegion)) {
            // Inside the title rectangle
            QRect rect = outsideRect.adjusted(border, border, -border, 0);
            rect.setHeight(titleHeight);

            dx = buttons[testRegion];
            rect.setLeft(rect.right() + 1 + dx);
            rect.setWidth(buttonWidth + buttonMargin);
            region += rect;
        }
    }
    //! [add a region for each button only if it is present]

    //! [region end]
    return region;
}
示例#2
0
static void removeAction(int idx)
{
	actionsDict.remove(idx);
}
void dumpColors(const QHash<QPair<QString, int>, QColor> &colors) {
    foreach (const QColor &color, colors.values()) {
        const QPair<QString, int> key = colors.key(color);
        qDebug() << key << color;
    }
}
示例#4
0
void dump(std::ostream &output, const OsmAnd::Verifier::Configuration& cfg)
#endif
{
    OsmAnd::ObfsCollection obfsCollection;
    for(const auto& obfsDir : cfg.obfDirs)
        obfsCollection.addDirectory(obfsDir);
    for(const auto& obfFile : cfg.obfFiles)
        obfsCollection.addFile(obfFile);
    const auto dataInterface = obfsCollection.obtainDataInterface();

    const auto obfFiles = obfsCollection.getObfFiles();
    output << "Will work with these files:" << std::endl;
    for(const auto& obfFile : obfFiles)
        output << "\t" << qPrintable(obfFile->filePath) << std::endl;

    if(cfg.action == OsmAnd::Verifier::Configuration::Action::UniqueMapObjectIds)
    {
        const OsmAnd::AreaI entireWorld(0, 0, std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max());

        unsigned int lastReportedCount = 0;
        unsigned int totalDuplicatesCount = 0;

        for(int zoomLevel = OsmAnd::MinZoomLevel; zoomLevel <= OsmAnd::MaxZoomLevel; zoomLevel++)
        {
            output << "Processing " << zoomLevel << " zoom level..." << std::endl;

            QList< std::shared_ptr<const OsmAnd::Model::MapObject> > duplicateMapObjects;
            QHash<uint64_t, unsigned int> mapObjectIds;
            const auto idsCollector = [&mapObjectIds, &lastReportedCount, &output, &totalDuplicatesCount](
                const std::shared_ptr<const OsmAnd::ObfMapSectionInfo>& section,
                const uint64_t mapObjectId,
                const OsmAnd::AreaI& bbox,
                const OsmAnd::ZoomLevel firstZoomLevel,
                const OsmAnd::ZoomLevel lasttZoomLevel) -> bool
            {
                const auto itId = mapObjectIds.find(mapObjectId);
                if(itId != mapObjectIds.end())
                {
                    // Increment duplicates counter
                    itId.value()++;
                    totalDuplicatesCount++;

                    return true;
                }

                // Insert new entry
                mapObjectIds.insert(mapObjectId, 0);

                if(mapObjectIds.size() - lastReportedCount == 10000)
                {
                    output << "\t... processed 10k map objects, found " << totalDuplicatesCount << " duplicate(s) so far ... " << std::endl;
                    lastReportedCount = mapObjectIds.size();
                }

                return false;
            };

            dataInterface->loadMapObjects(&duplicateMapObjects, nullptr, entireWorld, static_cast<OsmAnd::ZoomLevel>(zoomLevel), nullptr, idsCollector, nullptr);

            output << "\tProcessed " << mapObjectIds.size() << " map objects.";
            if(!mapObjectIds.isEmpty())
                output << " Found " << totalDuplicatesCount << " duplicate(s) :";
            output << std::endl;
            for(auto itEntry = mapObjectIds.cbegin(); itEntry != mapObjectIds.cend(); ++itEntry)
            {
                const auto mapObjectId = itEntry.key();
                const auto duplicatesCount = itEntry.value();
                if(duplicatesCount == 0)
                    continue;

                output << "\tMapObject ";
                if(static_cast<int64_t>(mapObjectId) < 0)
                {
                    int64_t originalId = -static_cast<int64_t>(static_cast<uint64_t>(-static_cast<int64_t>(mapObjectId)) & 0xFFFFFFFF);
                    output << originalId;
                }
                else
                {
                    output << mapObjectId;
                }
                output << " has " << duplicatesCount << " duplicate(s)." << std::endl;
            }
        }

        output << "Totally " << totalDuplicatesCount << " duplicate(s) across all zoom levels" << std::endl;
    }
}
示例#5
0
static int addActionToDict(QAction *pAction)
{
	actionsDict.insert(iIdentifier,pAction);
	iIdentifier++;
	return (iIdentifier-1);
}
示例#6
0
void ObjFileLoader::loadMaterials(const QString& file, QHash<QString, material>& materials)
{
    QFile f(file);
    if(!f.open(QIODevice::ReadOnly))
        return;

    QTextStream str(&f);
    material mtl;
    QString name;
    for(QString line = str.readLine(); !line.isNull(); line = str.readLine())
    {
        if(line.startsWith('#'))
            continue;

        QStringList parts = line.split(' ');
        if(parts.size() < 2)
            continue;

        int type = getMtlType(parts[0]);
        if(type == -1)
            continue;

        switch(type)
        {
            case 0: // newmtl
                if(!name.isNull())
                    materials.insert(name, mtl);

                mtl = material();
                name = parts.back();
                if(name.isNull())
                    name = "";
                break;
            case 1: // Ka
                for(int i = 1; i < 4 && i < parts.size(); ++i)
                    mtl.Ka[i-1] = parts[i].toFloat();
                break;
            case 2: // Kd
                for(int i = 1; i < 4 && i < parts.size(); ++i)
                    mtl.Kd[i-1] = parts[i].toFloat();
                break;
            case 3: // Ks
                for(int i = 1; i < 4 && i < parts.size(); ++i)
                    mtl.Ks[i-1] = parts[i].toFloat();
                break;
            case 4: // Ns
                // Wavefront has range 0 to 1000, opengl has 0 to 128
                mtl.Ns = parts.back().toFloat()*0.128;
                break;
            case 5: // d
            case 6: // Tr
                mtl.d = parts.back().toFloat();
                break;
            case 7: // illum
                mtl.illum = parts.back().toInt();
                break;
        }
    }

    if(!name.isNull())
        materials.insert(name, mtl);
}
void PelicanServerClientTest::test_response()
{
    try {
    TestServiceAdapter serviceAdapter;
    TestStreamAdapter streamAdapter;
    ConfigNode configNode;
    configNode.setFromString(
            "<testconfig>"
            "   <server host=\"127.0.0.1\"/>"
            "</testconfig>"
    );
    QString stream1("stream1");
    QString version1("v1");
    QString service1("service1");
    QString serviceVersion1("sv1");
    DataSpec reqStream1;
    reqStream1.addStreamData(stream1);
    QByteArray data1("data1");
    {
        // Use Case
        // receive a StreamData response (single stream, no service data)
        boost::shared_ptr<ServerResponse> res( new StreamDataResponse );
        static_cast<StreamDataResponse*>(res.get())->setStreamData( new StreamData(stream1,version1, data1.size()) );

        // set up the adapters and client
        QList<DataSpec> lreq;
        lreq.append(reqStream1);
        DataTypes dt;
        dt.setAdapter(stream1,&streamAdapter);
        dt.addData(lreq);
        PelicanServerClient client(configNode, dt, 0);

        // set up the memory for receiving data
        TestDataBlob db;
        QHash<QString, DataBlob*> dataHash;
        dataHash.insert(stream1, &db);

        SocketTester st;
        QTcpSocket& sock = st.send(data1);
        QHash<QString, DataBlob*> vhash = client._response( sock , res, dataHash );
        CPPUNIT_ASSERT( vhash == dataHash );
        CPPUNIT_ASSERT_EQUAL( version1.toStdString(), vhash[stream1]->version().toStdString() );
        CPPUNIT_ASSERT_EQUAL( std::string( data1.data() ) , std::string( static_cast<TestDataBlob*>(vhash[stream1])->data() ) );
    }
    QByteArray data2("data2");
    {
        // Use Case
        // ServiceData response - single service data
        boost::shared_ptr<ServerResponse> res( new ServiceDataResponse );
        static_cast<ServiceDataResponse*>(res.get())->addData( new DataChunk(service1,serviceVersion1, data2.size()) );

        // set up the memory for receiving data
        TestDataBlob db;
        QHash<QString, DataBlob*> dataHash;
        dataHash.insert(service1, &db);

        // set up the adapters and client
        DataSpec req;
        req.addStreamData(service1);
        QList<DataSpec> lreq;
        lreq.append(req);
        DataTypes dt;
        dt.setAdapter(service1,&serviceAdapter);
        dt.addData(lreq);
        PelicanServerClient client(configNode, dt, 0);

        SocketTester st;
        QTcpSocket& sock = st.send(data2);
        QHash<QString, DataBlob*> vhash = client._response( sock , res, dataHash );
        CPPUNIT_ASSERT( vhash == dataHash );
        CPPUNIT_ASSERT_EQUAL( serviceVersion1.toStdString(), vhash[service1]->version().toStdString() );
        CPPUNIT_ASSERT_EQUAL( std::string( data2.data() ) , std::string( static_cast<TestDataBlob*>(vhash[service1])->data() ) );
    }
    QString service2("service2");
    {
        // Use Case
        // ServiceData response - multiple service data
        boost::shared_ptr<ServerResponse> res( new ServiceDataResponse );
        static_cast<ServiceDataResponse*>(res.get())->addData( new DataChunk(service1,version1, data1.size()) );
        static_cast<ServiceDataResponse*>(res.get())->addData( new DataChunk(service2,serviceVersion1, data2.size()) );

        // set up the memory for receiving data
        TestDataBlob db;
        TestDataBlob db2;
        QHash<QString, DataBlob*> dataHash;
        dataHash.insert(service1, &db);
        dataHash.insert(service2, &db2);

        // set up the adapters and client
        DataSpec req;
        req.addStreamData(service1);
        QList<DataSpec> lreq;
        lreq.append(req);
        DataTypes dt;
        dt.setAdapter(service1,&serviceAdapter);
        dt.setAdapter(service2,&serviceAdapter);
        dt.addData(lreq);
        PelicanServerClient client(configNode, dt, 0);

        SocketTester st;
        QTcpSocket& sock = st.send( data1 + data2 );
        QHash<QString, DataBlob*> vhash = client._response( sock , res, dataHash );
        CPPUNIT_ASSERT( vhash == dataHash );
        CPPUNIT_ASSERT_EQUAL( version1.toStdString(), vhash[service1]->version().toStdString() );
        CPPUNIT_ASSERT_EQUAL( serviceVersion1.toStdString(), vhash[service2]->version().toStdString() );
        CPPUNIT_ASSERT_EQUAL( std::string( data1.data() ) , std::string( static_cast<TestDataBlob*>(vhash[service1])->data() ) );
        CPPUNIT_ASSERT_EQUAL( std::string( data2.data() ) , std::string( static_cast<TestDataBlob*>(vhash[service2])->data() ) );
    }

//    {
//        // Use Case
//        // receive a StreamData response with associated service data (single stream, single service data)
//        // no existing service data exists
//        boost::shared_ptr<ServerResponse> res( new StreamDataResponse );
//        StreamData* sd = new StreamData(stream1,version1, data1.size());
//        sd->addAssociatedData(boost::shared_ptr<Data>(new Data(service1,serviceVersion1, data2.size()) ) );
//        static_cast<StreamDataResponse*>(res.get())->setStreamData( sd );
//
//        // set up the adapters and client
//        DataSpec req;
//        req.addStreamData(stream1);
//        req.addServiceData(service1);
//        QList<DataSpec> lreq;
//        lreq.append(req);
//        DataTypes dt;
//        dt.setAdapter(stream1,&streamAdapter);
//        dt.setAdapter(service1,&serviceAdapter);
//        dt.addData(lreq);
//        PelicanServerClient client(configNode, dt, 0);
//
//        // set up the memory for receiving data
//        TestDataBlob db;
//        TestDataBlob db2;
//        QHash<QString, DataBlob*> dataHash;
//        dataHash.insert(stream1, &db);
//        dataHash.insert(service1, &db2);
//
//        SocketTester st;
//        QTcpSocket& sock = st.send(data1);
//        try {
//            QHash<QString, DataBlob*> vhash = client._response( sock , res, dataHash );
//        } catch (const QString& e) {
//            CPPUNIT_FAIL(e.toStdString());
//        }
//        CPPUNIT_ASSERT( vhash == dataHash );
//        CPPUNIT_ASSERT_EQUAL( version1.toStdString(), vhash[stream1]->version().toStdString() );
//        CPPUNIT_ASSERT_EQUAL( serviceVersion1.toStdString(), vhash[service1]->version().toStdString() );
//        CPPUNIT_ASSERT_EQUAL( std::string( data1.data() ) , std::string( static_cast<TestDataBlob*>( vhash[stream1])->data() ) );
//        CPPUNIT_ASSERT_EQUAL( std::string( data2.data() ) , std::string( static_cast<TestDataBlob*>( vhash[service1])->data() ) );
//    }

        } catch ( const QString& e ) {
                CPPUNIT_FAIL( e.toStdString() );
        }
}
/* KStorageControllerType <= QString: */
template<> KStorageControllerType fromString<KStorageControllerType>(const QString &strType)
{
    QHash<QString, KStorageControllerType> list;
    list.insert(QApplication::translate("VBoxGlobal", "Lsilogic", "StorageControllerType"),     KStorageControllerType_LsiLogic);
    list.insert(QApplication::translate("VBoxGlobal", "BusLogic", "StorageControllerType"),     KStorageControllerType_BusLogic);
    list.insert(QApplication::translate("VBoxGlobal", "AHCI", "StorageControllerType"),         KStorageControllerType_IntelAhci);
    list.insert(QApplication::translate("VBoxGlobal", "PIIX3", "StorageControllerType"),        KStorageControllerType_PIIX3);
    list.insert(QApplication::translate("VBoxGlobal", "PIIX4", "StorageControllerType"),        KStorageControllerType_PIIX4);
    list.insert(QApplication::translate("VBoxGlobal", "ICH6", "StorageControllerType"),         KStorageControllerType_ICH6);
    list.insert(QApplication::translate("VBoxGlobal", "I82078", "StorageControllerType"),       KStorageControllerType_I82078);
    list.insert(QApplication::translate("VBoxGlobal", "LsiLogic SAS", "StorageControllerType"), KStorageControllerType_LsiLogicSas);
    list.insert(QApplication::translate("VBoxGlobal", "USB", "StorageControllerType"),          KStorageControllerType_USB);
    list.insert(QApplication::translate("VBoxGlobal", "NVMe", "StorageControllerType"),         KStorageControllerType_NVMe);
    if (!list.contains(strType))
    {
        AssertMsgFailed(("No value for '%s'", strType.toUtf8().constData()));
    }
    return list.value(strType, KStorageControllerType_Null);
}
static void initializeClassesIconsIndex()
{
    Q_ASSERT(s_numberToKey.isEmpty());
    Q_ASSERT(s_keyToNumber.isEmpty());
    s_numberToKey[0] = QLatin1String(":/gammaray/icons/ui/classes/QQuickBorderImage/default.png");
    s_keyToNumber[s_numberToKey[0]] = 0;
    s_numberToKey[1] = QLatin1String(":/gammaray/icons/ui/classes/QQuickFlickable/default.png");
    s_keyToNumber[s_numberToKey[1]] = 1;
    s_numberToKey[2] = QLatin1String(":/gammaray/icons/ui/classes/QQuickFlipable/default.png");
    s_keyToNumber[s_numberToKey[2]] = 2;
    s_numberToKey[3] = QLatin1String(":/gammaray/icons/ui/classes/QQuickFocusScope/default.png");
    s_keyToNumber[s_numberToKey[3]] = 3;
    s_numberToKey[4] = QLatin1String(":/gammaray/icons/ui/classes/QQuickGridView/default.png");
    s_keyToNumber[s_numberToKey[4]] = 4;
    s_numberToKey[5] = QLatin1String(":/gammaray/icons/ui/classes/QQuickImage/default.png");
    s_keyToNumber[s_numberToKey[5]] = 5;
    s_numberToKey[6] = QLatin1String(":/gammaray/icons/ui/classes/QQuickItem/default.png");
    s_keyToNumber[s_numberToKey[6]] = 6;
    s_numberToKey[7] = QLatin1String(":/gammaray/icons/ui/classes/QQuickListView/default.png");
    s_keyToNumber[s_numberToKey[7]] = 7;
    s_numberToKey[8] = QLatin1String(":/gammaray/icons/ui/classes/QQuickMouseArea/default.png");
    s_keyToNumber[s_numberToKey[8]] = 8;
    s_numberToKey[9] = QLatin1String(":/gammaray/icons/ui/classes/QQuickPathView/default.png");
    s_keyToNumber[s_numberToKey[9]] = 9;
    s_numberToKey[10] = QLatin1String(":/gammaray/icons/ui/classes/QQuickRectangle/default.png");
    s_keyToNumber[s_numberToKey[10]] = 10;
    s_numberToKey[11] = QLatin1String(":/gammaray/icons/ui/classes/QQuickTextEdit/default.png");
    s_keyToNumber[s_numberToKey[11]] = 11;
    s_numberToKey[12] = QLatin1String(":/gammaray/icons/ui/classes/QQuickText/default.png");
    s_keyToNumber[s_numberToKey[12]] = 12;
    s_numberToKey[13] = QLatin1String(":/gammaray/icons/ui/classes/QQuickTextInput/default.png");
    s_keyToNumber[s_numberToKey[13]] = 13;
    s_numberToKey[14] = QLatin1String(":/gammaray/icons/ui/classes/QQuickWebView/default.png");
    s_keyToNumber[s_numberToKey[14]] = 14;
    s_numberToKey[15] = QLatin1String(":/gammaray/icons/ui/classes/QDateTimeEdit/default.png");
    s_keyToNumber[s_numberToKey[15]] = 15;
    s_numberToKey[16] = QLatin1String(":/gammaray/icons/ui/classes/QTextEdit/default.png");
    s_keyToNumber[s_numberToKey[16]] = 16;
    s_numberToKey[17] = QLatin1String(":/gammaray/icons/ui/classes/QCalendarWidget/default.png");
    s_keyToNumber[s_numberToKey[17]] = 17;
    s_numberToKey[18] = QLatin1String(":/gammaray/icons/ui/classes/QProgressBar/default.png");
    s_keyToNumber[s_numberToKey[18]] = 18;
    s_numberToKey[19] = QLatin1String(":/gammaray/icons/ui/classes/QAbstractScrollArea/default.png");
    s_keyToNumber[s_numberToKey[19]] = 19;
    s_numberToKey[20] = QLatin1String(":/gammaray/icons/ui/classes/QLineEdit/default.png");
    s_keyToNumber[s_numberToKey[20]] = 20;
    s_numberToKey[21] = QLatin1String(":/gammaray/icons/ui/classes/QDockWidget/default.png");
    s_keyToNumber[s_numberToKey[21]] = 21;
    s_numberToKey[22] = QLatin1String(":/gammaray/icons/ui/classes/QScrollBar/default.png");
    s_keyToNumber[s_numberToKey[22]] = 22;
    s_numberToKey[23] = QLatin1String(":/gammaray/icons/ui/classes/QComboBox/default.png");
    s_keyToNumber[s_numberToKey[23]] = 23;
    s_numberToKey[24] = QLatin1String(":/gammaray/icons/ui/classes/QCommandLinkButton/default.png");
    s_keyToNumber[s_numberToKey[24]] = 24;
    s_numberToKey[25] = QLatin1String(":/gammaray/icons/ui/classes/QWizard/default.png");
    s_keyToNumber[s_numberToKey[25]] = 25;
    s_numberToKey[26] = QLatin1String(":/gammaray/icons/ui/classes/QWidget/default.png");
    s_keyToNumber[s_numberToKey[26]] = 26;
    s_numberToKey[27] = QLatin1String(":/gammaray/icons/ui/classes/QSpinBox/default.png");
    s_keyToNumber[s_numberToKey[27]] = 27;
    s_numberToKey[28] = QLatin1String(":/gammaray/icons/ui/classes/QScrollBar/orientation=Horizontal.png");
    s_keyToNumber[s_numberToKey[28]] = 28;
    s_numberToKey[29] = QLatin1String(":/gammaray/icons/ui/classes/QCheckBox/default.png");
    s_keyToNumber[s_numberToKey[29]] = 29;
    s_numberToKey[30] = QLatin1String(":/gammaray/icons/ui/classes/QTabWidget/default.png");
    s_keyToNumber[s_numberToKey[30]] = 30;
    s_numberToKey[31] = QLatin1String(":/gammaray/icons/ui/classes/QDateEdit/default.png");
    s_keyToNumber[s_numberToKey[31]] = 31;
    s_numberToKey[32] = QLatin1String(":/gammaray/icons/ui/classes/QLabel/default.png");
    s_keyToNumber[s_numberToKey[32]] = 32;
    s_numberToKey[33] = QLatin1String(":/gammaray/icons/ui/classes/QListView/default.png");
    s_keyToNumber[s_numberToKey[33]] = 33;
    s_numberToKey[34] = QLatin1String(":/gammaray/icons/ui/classes/QColumnView/default.png");
    s_keyToNumber[s_numberToKey[34]] = 34;
    s_numberToKey[35] = QLatin1String(":/gammaray/icons/ui/classes/QDial/default.png");
    s_keyToNumber[s_numberToKey[35]] = 35;
    s_numberToKey[36] = QLatin1String(":/gammaray/icons/ui/classes/QFrame/default.png");
    s_keyToNumber[s_numberToKey[36]] = 36;
    s_numberToKey[37] = QLatin1String(":/gammaray/icons/ui/classes/QTabBar/default.png");
    s_keyToNumber[s_numberToKey[37]] = 37;
    s_numberToKey[38] = QLatin1String(":/gammaray/icons/ui/classes/QSlider/default.png");
    s_keyToNumber[s_numberToKey[38]] = 38;
    s_numberToKey[39] = QLatin1String(":/gammaray/icons/ui/classes/QGroupBox/default.png");
    s_keyToNumber[s_numberToKey[39]] = 39;
    s_numberToKey[40] = QLatin1String(":/gammaray/icons/ui/classes/QGraphicsView/default.png");
    s_keyToNumber[s_numberToKey[40]] = 40;
    s_numberToKey[41] = QLatin1String(":/gammaray/icons/ui/classes/QMdiArea/default.png");
    s_keyToNumber[s_numberToKey[41]] = 41;
    s_numberToKey[42] = QLatin1String(":/gammaray/icons/ui/classes/QFontComboBox/default.png");
    s_keyToNumber[s_numberToKey[42]] = 42;
    s_numberToKey[43] = QLatin1String(":/gammaray/icons/ui/classes/QDialogButtonBox/default.png");
    s_keyToNumber[s_numberToKey[43]] = 43;
    s_numberToKey[44] = QLatin1String(":/gammaray/icons/ui/classes/QToolBox/default.png");
    s_keyToNumber[s_numberToKey[44]] = 44;
    s_numberToKey[45] = QLatin1String(":/gammaray/icons/ui/classes/QTimeEdit/default.png");
    s_keyToNumber[s_numberToKey[45]] = 45;
    s_numberToKey[46] = QLatin1String(":/gammaray/icons/ui/classes/QPlainTextEdit/default.png");
    s_keyToNumber[s_numberToKey[46]] = 46;
    s_numberToKey[47] = QLatin1String(":/gammaray/icons/ui/classes/QSlider/orientation=Vertical.png");
    s_keyToNumber[s_numberToKey[47]] = 47;
    s_numberToKey[48] = QLatin1String(":/gammaray/icons/ui/classes/QDoubleSpinBox/default.png");
    s_keyToNumber[s_numberToKey[48]] = 48;
    s_numberToKey[49] = QLatin1String(":/gammaray/icons/ui/classes/QLCDNumber/default.png");
    s_keyToNumber[s_numberToKey[49]] = 49;
    s_numberToKey[50] = QLatin1String(":/gammaray/icons/ui/classes/QToolButton/default.png");
    s_keyToNumber[s_numberToKey[50]] = 50;
    s_numberToKey[51] = QLatin1String(":/gammaray/icons/ui/classes/QTableView/default.png");
    s_keyToNumber[s_numberToKey[51]] = 51;
    s_numberToKey[52] = QLatin1String(":/gammaray/icons/ui/classes/QStackedWidget/default.png");
    s_keyToNumber[s_numberToKey[52]] = 52;
    s_numberToKey[53] = QLatin1String(":/gammaray/icons/ui/classes/QRadioButton/default.png");
    s_keyToNumber[s_numberToKey[53]] = 53;
    s_numberToKey[54] = QLatin1String(":/gammaray/icons/ui/classes/QPushButton/default.png");
    s_keyToNumber[s_numberToKey[54]] = 54;
    s_numberToKey[55] = QLatin1String(":/gammaray/icons/ui/classes/QAbstractItemView/default.png");
    s_keyToNumber[s_numberToKey[55]] = 55;
    s_numberToKey[56] = QLatin1String(":/gammaray/icons/ui/classes/QSplitter/orientation=Horizontal.png");
    s_keyToNumber[s_numberToKey[56]] = 56;
    s_numberToKey[57] = QLatin1String(":/gammaray/icons/ui/classes/QHBoxLayout/default.png");
    s_keyToNumber[s_numberToKey[57]] = 57;
    s_numberToKey[58] = QLatin1String(":/gammaray/icons/ui/classes/QGridLayout/default.png");
    s_keyToNumber[s_numberToKey[58]] = 58;
    s_numberToKey[59] = QLatin1String(":/gammaray/icons/ui/classes/QSplitter/default.png");
    s_keyToNumber[s_numberToKey[59]] = 59;
    s_numberToKey[60] = QLatin1String(":/gammaray/icons/ui/classes/QVBoxLayout/default.png");
    s_keyToNumber[s_numberToKey[60]] = 60;
    s_numberToKey[61] = QLatin1String(":/gammaray/icons/ui/classes/QFormLayout/default.png");
    s_keyToNumber[s_numberToKey[61]] = 61;
}
示例#10
0
void TestQgsProject::testPathResolverSvg()
{
  QString dataDir( TEST_DATA_DIR ); //defined in CmakeLists.txt
  QString layerPath = dataDir + "/points.shp";

  // build a project with 3 layers, each having a simple renderer with SVG marker
  // - existing SVG file in project dir
  // - existing SVG file in QGIS dir
  // - non-exsiting SVG file

  QTemporaryDir dir;
  QVERIFY( dir.isValid() );
  // on mac the returned path was not canonical and the resolver failed to convert paths properly
  QString dirPath = QFileInfo( dir.path() ).canonicalFilePath();

  QString projectFilename = dirPath + "/project.qgs";
  QString ourSvgPath = dirPath + "/valid.svg";
  QString invalidSvgPath = dirPath + "/invalid.svg";

  QFile svgFile( ourSvgPath );
  QVERIFY( svgFile.open( QIODevice::WriteOnly ) );
  svgFile.write( "<svg/>" );   // not a proper SVG, but good enough for this case
  svgFile.close();

  QVERIFY( QFileInfo::exists( ourSvgPath ) );  // should exist now

  QString librarySvgPath = QgsSymbolLayerUtils::svgSymbolNameToPath( QStringLiteral( "transport/transport_airport.svg" ), QgsPathResolver() );

  QgsVectorLayer *layer1 = new QgsVectorLayer( layerPath, QStringLiteral( "points 1" ), QStringLiteral( "ogr" ) );
  _useRendererWithSvgSymbol( layer1, ourSvgPath );

  QgsVectorLayer *layer2 = new QgsVectorLayer( layerPath, QStringLiteral( "points 2" ), QStringLiteral( "ogr" ) );
  _useRendererWithSvgSymbol( layer2, invalidSvgPath );

  QgsVectorLayer *layer3 = new QgsVectorLayer( layerPath, QStringLiteral( "points 3" ), QStringLiteral( "ogr" ) );
  _useRendererWithSvgSymbol( layer3, librarySvgPath );

  QVERIFY( layer1->isValid() );

  QgsProject project;
  project.addMapLayers( QList<QgsMapLayer *>() << layer1 << layer2 << layer3 );
  project.write( projectFilename );

  // make sure the path resolver works with relative paths (enabled by default)
  QCOMPARE( project.pathResolver().readPath( "./a.txt" ), dirPath + "/a.txt" );
  QCOMPARE( project.pathResolver().writePath( dirPath + "/a.txt" ), QString( "./a.txt" ) );

  // check that the saved paths are relative

  // key = layer name, value = svg path
  QHash<QString, QString> projectFileSvgPaths = _parseSvgPathsForLayers( projectFilename );

  QCOMPARE( projectFileSvgPaths.count(), 3 );
  QCOMPARE( projectFileSvgPaths["points 1"], QString( "./valid.svg" ) ); // relative path to project
  QCOMPARE( projectFileSvgPaths["points 2"], invalidSvgPath );  // full path to non-existent file (not sure why - but that's how it works now)
  QCOMPARE( projectFileSvgPaths["points 3"], QString( "transport/transport_airport.svg" ) );  // relative path to library

  // load project again, check that the paths are absolute
  QgsProject projectLoaded;
  projectLoaded.read( projectFilename );
  QString svg1 = _getLayerSvgMarkerPath( projectLoaded, QStringLiteral( "points 1" ) );
  QString svg2 = _getLayerSvgMarkerPath( projectLoaded, QStringLiteral( "points 2" ) );
  QString svg3 = _getLayerSvgMarkerPath( projectLoaded, QStringLiteral( "points 3" ) );
  QCOMPARE( svg1, ourSvgPath );
  QCOMPARE( svg2, invalidSvgPath );
  QCOMPARE( svg3, librarySvgPath );

  //
  // now let's use these layers in embedded in another project...
  //

  QList<QDomNode> brokenNodes;
  QgsProject projectMaster;
  QVERIFY( projectMaster.createEmbeddedLayer( layer1->id(), projectFilename, brokenNodes ) );
  QVERIFY( projectMaster.createEmbeddedLayer( layer2->id(), projectFilename, brokenNodes ) );
  QVERIFY( projectMaster.createEmbeddedLayer( layer3->id(), projectFilename, brokenNodes ) );

  QString svg1x = _getLayerSvgMarkerPath( projectMaster, QStringLiteral( "points 1" ) );
  QString svg2x = _getLayerSvgMarkerPath( projectLoaded, QStringLiteral( "points 2" ) );
  QString svg3x = _getLayerSvgMarkerPath( projectLoaded, QStringLiteral( "points 3" ) );
  QCOMPARE( svg1x, ourSvgPath );
  QCOMPARE( svg2x, invalidSvgPath );
  QCOMPARE( svg3x, librarySvgPath );

}
/* KAudioDriverType <= QString: */
template<> KAudioDriverType fromString<KAudioDriverType>(const QString &strType)
{
    QHash<QString, KAudioDriverType> list;
    list.insert(QApplication::translate("VBoxGlobal", "Null Audio Driver", "AudioDriverType"),   KAudioDriverType_Null);
    list.insert(QApplication::translate("VBoxGlobal", "Windows Multimedia", "AudioDriverType"),  KAudioDriverType_WinMM);
    list.insert(QApplication::translate("VBoxGlobal", "OSS Audio Driver", "AudioDriverType"),    KAudioDriverType_OSS);
    list.insert(QApplication::translate("VBoxGlobal", "ALSA Audio Driver", "AudioDriverType"),   KAudioDriverType_ALSA);
    list.insert(QApplication::translate("VBoxGlobal", "Windows DirectSound", "AudioDriverType"), KAudioDriverType_DirectSound);
    list.insert(QApplication::translate("VBoxGlobal", "CoreAudio", "AudioDriverType"),           KAudioDriverType_CoreAudio);
    // list.insert(..., KAudioDriverType_MMPM);
    list.insert(QApplication::translate("VBoxGlobal", "PulseAudio", "AudioDriverType"),          KAudioDriverType_Pulse);
    list.insert(QApplication::translate("VBoxGlobal", "Solaris Audio", "AudioDriverType"),       KAudioDriverType_SolAudio);
    if (!list.contains(strType))
    {
        AssertMsgFailed(("No value for '%s'", strType.toUtf8().constData()));
    }
    return list.value(strType, KAudioDriverType_Null);
}
bool InteractionStep::saveClassDrugInteractor(DrugInteractor *interactor, const QList<DrugInteractor *> &completeList, QSqlDatabase &db, DrugInteractor *parent)
{
    if (!db.isOpen()) {
        if (!db.open()) {
            LOG_ERROR_FOR("InteractionStep", tkTr(Trans::Constants::ERROR_1_FROM_DATABASE_2).arg(db.lastError().text()).arg(db.connectionName()));
            return false;
        }
    }

    // save interactor
    QSqlQuery query(db);
    int id = -1;
    // save using all associated ATC codes
    const QStringList &atcCodes = interactor->data(DrugInteractor::ATCCodeStringList).toStringList();
    if (atcCodes.isEmpty() && !interactor->isClass() && parent && parent->isClass()) {
        //        QString req = QString("INSERT INTO ATC_CLASS_TREE (ID_TREE, ID_CLASS, ID_ATC) VALUES "
        //                              "(NULL, %1,%2);")
        //                .arg(parent->data(CLASS_OR_MOL_ID).toString())
        //                .arg(interactor->data(CLASS_OR_MOL_ID).toString());
//        query.prepare(DrugsDB::Tools::drugBase()->prepareInsertQuery(DrugsDB::Constants::Table_ATC_CLASS_TREE));
//        query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID, QVariant());
//        query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID_ATC, interactor->data(CLASS_OR_MOL_ID).toString());
//        query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID_CLASS, parent->data(CLASS_OR_MOL_ID).toString());
//        query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_BIBMASTERID, QVariant());

//        if (!query.exec()) {
//            LOG_QUERY_ERROR_FOR("InteractionStep", query);
//        } else {
//            id = query.lastInsertId().toInt();
//        }
        query.finish();
    } else if (!atcCodes.isEmpty() && !interactor->isClass() && parent && parent->isClass()) {
        foreach(const QString &atc, atcCodes) {
            //            QString req = QString("INSERT INTO ATC_CLASS_TREE (ID_TREE, ID_CLASS, ID_ATC) VALUES "
            //                                  "(NULL, %1, (SELECT ATC_ID FROM ATC WHERE CODE=\"%2\"));")
            //                    .arg(parent->data(CLASS_OR_MOL_ID).toString()).arg(atc);

            QString atcId;
            QHash<int, QString> w;
            w.insert(DrugsDB::Constants::ATC_CODE, QString("='%1'").arg(atc));
//            QString req = DrugsDB::Tools::drugBase()->select(DrugsDB::Constants::Table_ATC, DrugsDB::Constants::ATC_ID, w);
//            if (query.exec(req)) {
//                if (query.next())
//                    atcId = query.value(0).toString();
//            } else {
//                LOG_QUERY_ERROR_FOR("InteractionStep", query);
//                db.rollback();
//                return false;
//            }
            query.finish();

//            query.prepare(DrugsDB::Tools::drugBase()->prepareInsertQuery(DrugsDB::Constants::Table_ATC_CLASS_TREE));
//            query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID, QVariant());
//            query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID_ATC, atcId);
//            query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_ID_CLASS, parent->data(CLASS_OR_MOL_ID).toString());
//            query.bindValue(DrugsDB::Constants::ATC_CLASS_TREE_BIBMASTERID, QVariant());

//            if (!query.exec()) {
//                LOG_QUERY_ERROR_FOR("InteractionStep", query);
//            } else {
//                id = query.lastInsertId().toInt();
//            }
            query.finish();
        }
示例#13
0
void MainSettingsDialog::populateAutoProfiles()
{
    exeAutoProfiles.clear();
    defaultAutoProfiles.clear();

    settings->beginGroup("DefaultAutoProfiles");
    QStringList defaultkeys = settings->allKeys();
    settings->endGroup();

    QString allProfile = settings->value(QString("DefaultAutoProfileAll/Profile"), "").toString();
    QString allActive = settings->value(QString("DefaultAutoProfileAll/Active"), "0").toString();

    if (!allProfile.isEmpty())
    {
        bool defaultActive = allActive == "1" ? true : false;
        allDefaultProfile = new AutoProfileInfo("all", allProfile, defaultActive, this);
        allDefaultProfile->setDefaultState(true);
    }
    else
    {
        allDefaultProfile = new AutoProfileInfo("all", "", false, this);
        allDefaultProfile->setDefaultState(true);
    }

    QStringListIterator iter(defaultkeys);
    while (iter.hasNext())
    {
        QString tempkey = iter.next();
        QString guid = QString(tempkey).replace("GUID", "");

        QString profile = settings->value(QString("DefaultAutoProfile-%1/Profile").arg(guid), "").toString();
        QString active = settings->value(QString("DefaultAutoProfile-%1/Active").arg(guid), "0").toString();
        QString deviceName = settings->value(QString("DefaultAutoProfile-%1/DeviceName").arg(guid), "").toString();

        if (!guid.isEmpty() && !profile.isEmpty() && !deviceName.isEmpty())
        {
            bool profileActive = active == "1" ? true : false;
            if (!defaultAutoProfiles.contains(guid) && guid != "all")
            {
                AutoProfileInfo *info = new AutoProfileInfo(guid, profile, profileActive, this);
                info->setDefaultState(true);
                info->setDeviceName(deviceName);
                defaultAutoProfiles.insert(guid, info);
                defaultList.append(info);
                QList<AutoProfileInfo*> templist;
                templist.append(info);
                deviceAutoProfiles.insert(guid, templist);
            }
        }
    }

    settings->beginGroup("AutoProfiles");
    bool quitSearch = false;

    QHash<QString, QList<QString> > tempAssociation;
    for (int i = 1; !quitSearch; i++)
    {
        QString exe = settings->value(QString("AutoProfile%1Exe").arg(i), "").toString();
        QString guid = settings->value(QString("AutoProfile%1GUID").arg(i), "").toString();
        QString profile = settings->value(QString("AutoProfile%1Profile").arg(i), "").toString();
        QString active = settings->value(QString("AutoProfile%1Active").arg(i), 0).toString();
        QString deviceName = settings->value(QString("AutoProfile%1DeviceName").arg(i), "").toString();

        // Check if all required elements exist. If not, assume that the end of the
        // list has been reached.
        if (!exe.isEmpty() && !guid.isEmpty() && !profile.isEmpty() && !deviceName.isEmpty())
        {
            bool profileActive = active == "1" ? true : false;
            QList<AutoProfileInfo*> templist;
            if (exeAutoProfiles.contains(exe))
            {
                templist = exeAutoProfiles.value(exe);
            }

            QList<QString> tempguids;
            if (tempAssociation.contains(exe))
            {
                tempguids = tempAssociation.value(exe);
            }

            if (!tempguids.contains(guid) && guid != "all")
            {
                AutoProfileInfo *info = new AutoProfileInfo(guid, profile, exe, profileActive, this);
                info->setDeviceName(deviceName);
                tempguids.append(guid);
                tempAssociation.insert(exe, tempguids);
                templist.append(info);
                exeAutoProfiles.insert(exe, templist);
                profileList.append(info);
                QList<AutoProfileInfo*> templist;
                if (deviceAutoProfiles.contains(guid))
                {
                    templist = deviceAutoProfiles.value(guid);
                }
                templist.append(info);
                deviceAutoProfiles.insert(guid, templist);
            }
        }
        else
        {
            quitSearch = true;
        }
    }

    settings->endGroup();
}
示例#14
0
void MainSettingsDialog::fillControllerMappingsTable()
{
    /*QList<QVariant> tempvariant = bindingValues(bind);
    QTableWidgetItem* item = new QTableWidgetItem();
    ui->buttonMappingTableWidget->setItem(associatedRow, 0, item);
    item->setText(temptext);
    item->setData(Qt::UserRole, tempvariant);
    */

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    ui->controllerMappingsTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else
    ui->controllerMappingsTableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif

    QHash<QString, QList<QVariant> > tempHash;

    settings->beginGroup("Mappings");

    QStringList mappings = settings->allKeys();
    QStringListIterator iter(mappings);
    while (iter.hasNext())
    {
        QString tempkey = iter.next();
        QString tempGUID;

        if (tempkey.contains("Disable"))
        {
            bool disableGameController = settings->value(tempkey, false).toBool();
            tempGUID = tempkey.remove("Disable");
            insertTempControllerMapping(tempHash, tempGUID);
            if (tempHash.contains(tempGUID))
            {
                QList<QVariant> templist = tempHash.value(tempGUID);
                templist.replace(2, QVariant(disableGameController));
                tempHash.insert(tempGUID, templist); // Overwrite original list
            }
        }
        else
        {
            QString mappingString = settings->value(tempkey, QString()).toString();
            if (!mappingString.isEmpty())
            {
                tempGUID = tempkey;
                insertTempControllerMapping(tempHash, tempGUID);
                if (tempHash.contains(tempGUID))
                {
                    QList<QVariant> templist = tempHash.value(tempGUID);
                    templist.replace(1, mappingString);
                    tempHash.insert(tempGUID, templist); // Overwrite original list
                }
            }
        }
    }

    settings->endGroup();

    QHashIterator<QString, QList<QVariant> > iter2(tempHash);
    int i = 0;
    while (iter2.hasNext())
    {
        ui->controllerMappingsTableWidget->insertRow(i);

        QList<QVariant> templist = iter2.next().value();
        QTableWidgetItem* item = new QTableWidgetItem(templist.at(0).toString());
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        item->setData(Qt::UserRole, iter2.key());
        item->setToolTip(templist.at(0).toString());
        ui->controllerMappingsTableWidget->setItem(i, 0, item);

        item = new QTableWidgetItem(templist.at(1).toString());
        item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        item->setData(Qt::UserRole, iter2.key());
        //item->setToolTip(templist.at(1).toString());
        ui->controllerMappingsTableWidget->setItem(i, 1, item);

        bool disableController = templist.at(2).toBool();
        item = new QTableWidgetItem();
        item->setCheckState(disableController ? Qt::Checked : Qt::Unchecked);
        item->setData(Qt::UserRole, iter2.key());
        ui->controllerMappingsTableWidget->setItem(i, 2, item);

        i++;
    }
}
void
DatabaseCommand_LoadAllPlaylists::exec( DatabaseImpl* dbi )
{
    Q_D( DatabaseCommand_LoadAllPlaylists );

    TomahawkSqlQuery query = dbi->newquery();
    QString orderToken, sourceToken;

    switch ( d->sortOrder )
    {
    case 0:
        break;

    case ModificationTime:
            orderToken = "ORDER BY playlist.createdOn";
    }

    if ( !source().isNull() )
        sourceToken = QString( "AND source %1 " ).arg( source()->isLocal() ? "IS NULL" : QString( "= %1" ).arg( source()->id() ) );

    QString trackIdJoin;
    QString trackIdFields;
    if ( d->returnPlEntryIds )
    {
        trackIdFields = ", pr.entries";
        trackIdJoin = "JOIN playlist_revision pr ON pr.playlist = p.guid AND pr.guid = p.currentrevision";
    }

    query.exec( QString( " SELECT p.guid, p.title, p.info, p.creator, p.lastmodified, p.shared, p.currentrevision, p.createdOn %6 "
                         " FROM playlist p "
                         " %5 "
                         " WHERE ( ( dynplaylist = 'false' ) OR ( dynplaylist = 0 ) ) "
                         " %1 "
                         " %2 %3 %4 "
                         )
                .arg( sourceToken )
                .arg( orderToken )
                .arg( d->sortDescending ? "DESC" : QString() )
                .arg( d->limitAmount > 0 ? QString( "LIMIT 0, %1" ).arg( d->limitAmount ) : QString() )
                .arg( trackIdJoin )
                .arg( trackIdFields )
                );

    QList<playlist_ptr> plists;
    QHash<playlist_ptr, QStringList> phash;
    while ( query.next() )
    {
        playlist_ptr p( new Playlist( source(),                  //src
                                      query.value(6).toString(), //current rev
                                      query.value(1).toString(), //title
                                      query.value(2).toString(), //info
                                      query.value(3).toString(), //creator
                                      query.value(7).toInt(),    //lastmod / createdOn
                                      query.value(5).toBool(),   //shared
                                      query.value(4).toInt(),    //lastmod
                                      query.value(0).toString()  //GUID
                                    ), &QObject::deleteLater );
        p->setWeakSelf( p.toWeakRef() );
        plists.append( p );

        if ( d->returnPlEntryIds )
        {
            QStringList trackIds = TomahawkUtils::parseJson( query.value( 8 ).toByteArray() ).toStringList();
            phash.insert( p, trackIds );
        }
    }

    emit done( plists );

    if ( d->returnPlEntryIds )
    {
        emit done( phash );
    }
}
示例#16
0
QPixmap
ImageRegistry::pixmap( const QString& image, const QSize& size, TomahawkUtils::ImageMode mode, float opacity, QColor tint )
{
    if ( size.width() < 0 || size.height() < 0 )
    {
        Q_ASSERT( false );
        return QPixmap();
    }

    QHash< qint64, QPixmap > subsubcache;
    QHash< int, QHash< qint64, QPixmap > > subcache;

    if ( s_cache.contains( image ) )
    {
        subcache = s_cache.value( image );

        if ( subcache.contains( mode ) )
        {
            subsubcache = subcache.value( mode );

            const qint64 ck = cacheKey( size, opacity, tint );
            if ( subsubcache.contains( ck ) )
            {
                return subsubcache.value( ck );
            }
        }
    }

    // Image not found in cache. Let's load it.
    QPixmap pixmap;
    if ( image.toLower().endsWith( ".svg" ) )
    {
        QSvgRenderer svgRenderer( image );
        QPixmap p( size.isNull() || size.height() == 0 || size.width() == 0 ? svgRenderer.defaultSize() : size );
        p.fill( Qt::transparent );

        QPainter pixPainter( &p );
        pixPainter.setOpacity( opacity );
        svgRenderer.render( &pixPainter );
        pixPainter.end();

        if ( tint.alpha() > 0 )
            p = TomahawkUtils::tinted( p, tint );

        pixmap = p;
    }
    else
        pixmap = QPixmap( image );

    if ( !pixmap.isNull() )
    {
        switch ( mode )
        {
            case TomahawkUtils::RoundedCorners:
                pixmap = TomahawkUtils::createRoundedImage( pixmap, size );
                break;

            default:
                break;
        }

        if ( !size.isNull() && pixmap.size() != size )
        {
            if ( size.width() == 0 )
            {
                pixmap = pixmap.scaledToHeight( size.height(), Qt::SmoothTransformation );
            }
            else if ( size.height() == 0 )
            {
                pixmap = pixmap.scaledToWidth( size.width(), Qt::SmoothTransformation );
            }
            else
                pixmap = pixmap.scaled( size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation );
        }

        putInCache( image, size, mode, opacity, pixmap, tint );
    }

    return pixmap;
}
示例#17
0
void BrushStroker::addEditedKeys(const QHash<QPoint, QRect> &keysWithRects)
{
	for (auto iter = keysWithRects.begin(); iter != keysWithRects.end(); ++iter)
		addEditedKey(iter.key(), iter.value());
}
void FileDataClientTest::test_method()
{
    try {
    Config config;
    config.setFromString(
            "<testconfig>"
            "   <file name=\"testfile.xml\"/>"
            "</testconfig>"
            );
    Config::TreeAddress address;
    address << Config::NodeId("testconfig", "");
    ConfigNode configNode = config.get(address);
/* No longer relevant
    {
        // Use Case:
        //    Empty data requirements
        // Expect: throw with a suitable complaint

        // setup the test
        QList<DataSpec> lreq;
        DataTypes dt;
        dt.addData(lreq);
        FileDataClient* client = 0;
        CPPUNIT_ASSERT_THROW(client = new FileDataClient(configNode, dt, 0), QString);
        delete client;
    }
*/
    TestStreamAdapter streamAdapter;
    QString stream1("stream1");
    QString version1("version1");
    DataSpec req;
    req.addStreamData(stream1);
    {
        // Use Case:
        //    data requirements are set, empty hash passed
        // Expect: throw

        QList<DataSpec> lreq;
        lreq.append(req);
        DataTypes dt;
        dt.setAdapter(stream1,&streamAdapter);
        dt.addData(lreq);
        FileDataClient client(configNode, dt, 0);

        QHash<QString, DataBlob*> dataHash;
        CPPUNIT_ASSERT_THROW(client.getData(dataHash), QString );
    }
    {  // Use Case:
       // Specifiy a single file and associate it with a Stream
       // correct hash is passed
       // Expect:
       // Data in file to be streamed
       DataTypes types;
       types.setAdapter(stream1,&streamAdapter);
       types.addData(req);
       FileDataClient client(configNode, types, &config);

       QHash<QString, DataBlob*> dataHash;
       DataBlob db("DataBlob");
       dataHash.insert(stream1, &db);
       client.getData(dataHash);
    }
    }
    catch( QString& e ) {
        CPPUNIT_FAIL(e.toStdString());
    }
}
示例#19
0
bool ObjFileLoader::load(const QString& file, std::vector<GLModel*>& modelList)
{
    QFile f(file);
    if(!f.open(QIODevice::ReadOnly))
        return false;

    QString path = "./";
    int idx = file.lastIndexOf('/');
    if(idx != -1)
    {
        path = file.left(idx+1);
    }

    QHash<QString, material> materials;
    QHash<QString, material>::iterator m_itr;
    QTextStream str(&f);

    GLModel *model = new GLModel("");
    int vertexTotal = 0;
    int vertexModel = 0;

    int normalsTotal = 0;
    int normalsModel = 0;

    for(QString line = str.readLine(); !line.isNull(); line = str.readLine())
    {
        if(line.startsWith('#'))
            continue;

        QStringList parts = line.split(' ', QString::SkipEmptyParts);
        if(parts.size() < 2)
            continue;

        int type = getObjType(parts[0]);
        if(type == -1)
            continue;

        switch(type)
        {
            case 5: // model
            {
                if(model)
                {
                    model->createNormals();
                    modelList.push_back(model);
                }
                model = new GLModel(parts.back());
                if(type == 5)
                {
                    vertexTotal += vertexModel;
                    vertexModel = 0;
                    normalsTotal += normalsModel;
                    normalsModel = 0;
                }
                continue;
            }
            case 8: // group
            {
                if(!model)
                    model = new GLModel(parts.back());
                continue;
            }
            case 6: // mtllib
                loadMaterials(path + parts.back(), materials);
                continue;
        }

        if(!model)
            continue;

        switch(type)
        {
            case 0: // vertex
            {
                double coords[4] = { 0.0, 0.0, 0.0, 1.0 };
                for(int i = 1; i < parts.size() && i < 5; ++i)
                    coords[i-1] = parts[i].toDouble();
                model->addVertex(coords);
                ++vertexModel;
                break;
            }
            case 1: // face
            {
                polygonFace f;
                if(loadFace(parts, &f, vertexTotal, normalsTotal))
                    model->addFace(f);
                break;
            }
            case 2: // textures
                break;
            case 3: // normals
            {
                double coords[3] = { 0.0, 0.0, 0.0 };
                for(int i = 1; i < parts.size() && i < 4; ++i)
                    coords[i-1] = parts[i].toDouble();
                model->addNormal(coords);
                ++normalsModel;
                break;
            }
            case 4: // smooth shading
                model->setSmoothShading(parts.back() != "off");
                break;
            case 7: // usemtl
            {
                if(parts.back().isNull())
                    parts.back() = "";

                m_itr = materials.find(parts.back());
                if(m_itr == materials.end())
                    break;
                model->addMaterial(*m_itr);
                break;
            }
        }
    }
    if(model)
    {
        model->createNormals();
        modelList.push_back(model);
    }
    return true;
}
示例#20
0
KoFilter::ConversionStatus EpubFile::writeOpf(KoStore *epubStore,
        QHash<QString, QString> &metadata)
{
    if (!epubStore->open(pathPrefix() + "content.opf")) {
        kDebug(30503) << "Can not create content.opf .";
        return KoFilter::CreationError;
    }

    KoStoreDevice opfDevice(epubStore);
    KoXmlWriter writer(&opfDevice);

    //FIXME: Write   <?xml version="1.0"?> -> FIXED
    writer.startDocument(NULL,NULL,NULL);

    // FIXME: Get the unique identifier
    writer.startElement("package");
    writer.addAttribute("version", "2.0");
    writer.addAttribute("xmlns", "http://www.idpf.org/2007/opf");
    writer.addAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
    writer.addAttribute("xmlns:opf", "http://www.idpf.org/2007/opf");
    writer.addAttribute("unique-identifier", "BookId"); // FIXME: Where to get this?

    // ==== metadata ====
    writer.startElement("metadata");

    // Required elements are: title, language and identifier
    writer.startElement("dc:title");
    writer.addTextNode(metadata.value("title"));
    writer.endElement(); // dc:title

    writer.startElement("meta");
    writer.addAttribute("name", "cover");
    writer.addAttribute("content", "cover-image");
    writer.endElement();

    writer.startElement("dc:language");
    if (!metadata.value("language").isEmpty())
        writer.addTextNode(metadata.value("language"));
    else
        writer.addTextNode("en");
    writer.endElement(); // dc:language

    writer.startElement("dc:identifier");
    writer.addAttribute("id", "BookId");
    writer.addAttribute("opf:scheme", "ISBN");
    writer.addTextNode("123456789X");  // FIXME: Where to get this?
    writer.endElement(); // dc:identifier

    writer.startElement("dc:creator");
    writer.addTextNode(metadata.value("creator"));  // It's the "Author" profile name
    writer.endElement(); // dc:creator

    writer.startElement("dc:subject");
    writer.addTextNode("");  // FIXME: Here should come suject info with form : Fiction &amp; Fantasy &amp; ...
    writer.endElement(); // dc:subject

    // FIXME: many more (optional)

    writer.endElement(); // metadata

    // ==== manifest ====
    writer.startElement("manifest");

    // Write manifest entry for each embedded file.
    foreach(FileInfo *file, files()) {
        // Since paths are relative from where this file is, remove
        // the common prefix from the reference.
        QString relativeFilename = file->m_fileName;
        if (relativeFilename.startsWith(pathPrefix()))
            relativeFilename = relativeFilename.right(relativeFilename.size()
                               - pathPrefix().size());

        writer.startElement("item");
        writer.addAttribute("id", file->m_id);
        writer.addAttribute("href", relativeFilename);
        writer.addAttribute("media-type", file->m_mimetype);
        writer.endElement(); // item
    }
示例#21
0
QgsGrassEditRenderer::QgsGrassEditRenderer()
    : QgsFeatureRendererV2( "grassEdit" )
    , mLineRenderer( 0 )
    , mMarkerRenderer( 0 )
{
  QHash<int, QColor> colors;
  //colors.insert( QgsGrassVectorMap::TopoUndefined, QColor( 125, 125, 125 ) );
  colors.insert( QgsGrassVectorMap::TopoLine, QColor( Qt::black ) );
  colors.insert( QgsGrassVectorMap::TopoBoundaryError, QColor( Qt::red ) );
  colors.insert( QgsGrassVectorMap::TopoBoundaryErrorLeft, QColor( 255, 125, 0 ) );
  colors.insert( QgsGrassVectorMap::TopoBoundaryErrorRight, QColor( 255, 125, 0 ) );
  colors.insert( QgsGrassVectorMap::TopoBoundaryOk, QColor( Qt::green ) );

  QHash<int, QString> labels;
  //labels.insert( QgsGrassVectorMap::TopoUndefined, "Unknown type" );
  labels.insert( QgsGrassVectorMap::TopoLine, "Line" );
  labels.insert( QgsGrassVectorMap::TopoBoundaryError, "Boundary (topological error on both sides)" );
  labels.insert( QgsGrassVectorMap::TopoBoundaryErrorLeft, "Boundary (topological error on the left side)" );
  labels.insert( QgsGrassVectorMap::TopoBoundaryErrorRight, "Boundary (topological error on the right side)" );
  labels.insert( QgsGrassVectorMap::TopoBoundaryOk, "Boundary (correct)" );

  QgsCategoryList categoryList;

  // first/last vertex marker to distinguish vertices from nodes
  QgsMarkerLineSymbolLayerV2 * firstVertexMarkerLine = new QgsMarkerLineSymbolLayerV2( false );
  QgsSimpleMarkerSymbolLayerV2 *markerSymbolLayer = new QgsSimpleMarkerSymbolLayerV2( QgsSimpleMarkerSymbolLayerBase::Cross2, 2 );
  markerSymbolLayer->setColor( QColor( 255, 0, 0 ) );
  markerSymbolLayer->setBorderColor( QColor( 255, 0, 0 ) );
  markerSymbolLayer->setOutlineWidth( 0.5 );
  QgsSymbolLayerV2List markerLayers;
  markerLayers << markerSymbolLayer;
  QgsMarkerSymbolV2 * markerSymbol = new QgsMarkerSymbolV2( markerLayers );
  firstVertexMarkerLine->setSubSymbol( markerSymbol );
  firstVertexMarkerLine->setPlacement( QgsMarkerLineSymbolLayerV2::FirstVertex );
  QgsMarkerLineSymbolLayerV2 * lastVertexMarkerLine = static_cast<QgsMarkerLineSymbolLayerV2 *>( firstVertexMarkerLine->clone() );
  lastVertexMarkerLine->setPlacement( QgsMarkerLineSymbolLayerV2::LastVertex );
  Q_FOREACH ( int value, colors.keys() )
  {
    QgsSymbolV2 * symbol = QgsSymbolV2::defaultSymbol( QGis::Line );
    symbol->setColor( colors.value( value ) );
    symbol->appendSymbolLayer( firstVertexMarkerLine->clone() );
    symbol->appendSymbolLayer( lastVertexMarkerLine->clone() );
    categoryList << QgsRendererCategoryV2( QVariant( value ), symbol, labels.value( value ) );
  }
  delete firstVertexMarkerLine;
  delete lastVertexMarkerLine;
  mLineRenderer = new QgsCategorizedSymbolRendererV2( "topo_symbol", categoryList );

  colors.clear();
  labels.clear();

  colors.insert( QgsGrassVectorMap::TopoPoint, QColor( 0, 255, 255 ) );
  colors.insert( QgsGrassVectorMap::TopoCentroidIn, QColor( 0, 255, 0 ) );
  colors.insert( QgsGrassVectorMap::TopoCentroidOut, QColor( 255, 0, 0 ) );
  colors.insert( QgsGrassVectorMap::TopoCentroidDupl, QColor( 255, 0, 255 ) );

  labels.insert( QgsGrassVectorMap::TopoPoint, "Point" );
  labels.insert( QgsGrassVectorMap::TopoCentroidIn, "Centroid in area" );
  labels.insert( QgsGrassVectorMap::TopoCentroidOut, "Centroid outside area" );
  labels.insert( QgsGrassVectorMap::TopoCentroidDupl, "Duplicate centroid" );

  categoryList.clear();

  Q_FOREACH ( int value, colors.keys() )
  {
    QgsSymbolV2 * symbol = QgsSymbolV2::defaultSymbol( QGis::Point );
    symbol->setColor( colors.value( value ) );
    categoryList << QgsRendererCategoryV2( QVariant( value ), symbol, labels.value( value ) );
  }

  mMarkerRenderer = new QgsCategorizedSymbolRendererV2( "topo_symbol", categoryList );
}
示例#22
0
bool MainWindow::updateCurrentPlaylistEntry(const QHash<QString, QString> &contentHash)
{
   QString playlistPath = getCurrentPlaylistPath();
   QString path;
   QString label;
   QString corePath;
   QString coreName;
   QString dbName;
   QString crc32;
   QByteArray playlistPathArray;
   QByteArray pathArray;
   QByteArray labelArray;
   QByteArray corePathArray;
   QByteArray coreNameArray;
   QByteArray dbNameArray;
   QByteArray crc32Array;
   const char *playlistPathData = NULL;
   const char *pathData = NULL;
   const char *labelData = NULL;
   const char *corePathData = NULL;
   const char *coreNameData = NULL;
   const char *dbNameData = NULL;
   const char *crc32Data = NULL;
   playlist_t *playlist = NULL;
   unsigned index = 0;
   bool ok = false;

   if (playlistPath.isEmpty() || contentHash.isEmpty() || !contentHash.contains("index"))
      return false;

   index = contentHash.value("index").toUInt(&ok);

   if (!ok)
      return false;

   path = contentHash.value("path");
   label = contentHash.value("label");
   coreName = contentHash.value("core_name");
   corePath = contentHash.value("core_path");
   dbName = contentHash.value("db_name");
   crc32 = contentHash.value("crc32");

   if (path.isEmpty() ||
       label.isEmpty() ||
       coreName.isEmpty() ||
       corePath.isEmpty() ||
       dbName.isEmpty() ||
       crc32.isEmpty()
      )
      return false;

   playlistPathArray = playlistPath.toUtf8();
   pathArray = QDir::toNativeSeparators(path).toUtf8();
   labelArray = label.toUtf8();
   coreNameArray = coreName.toUtf8();
   corePathArray = QDir::toNativeSeparators(corePath).toUtf8();
   dbNameArray = (dbName + file_path_str(FILE_PATH_LPL_EXTENSION)).toUtf8();
   crc32Array = crc32.toUtf8();

   playlistPathData = playlistPathArray.constData();
   pathData = pathArray.constData();
   labelData = labelArray.constData();
   coreNameData = coreNameArray.constData();
   corePathData = corePathArray.constData();
   dbNameData = dbNameArray.constData();
   crc32Data = crc32Array.constData();

   if (path_is_compressed_file(pathData))
   {
      struct string_list *list = file_archive_get_file_list(pathData, NULL);

      if (list)
      {
         if (list->size == 1)
         {
            /* assume archives with one file should have that file loaded directly */
            pathArray = QDir::toNativeSeparators(QString(pathData) + "#" + list->elems[0].data).toUtf8();
            pathData = pathArray.constData();
         }

         string_list_free(list);
      }
   }

   playlist = playlist_init(playlistPathData, COLLECTION_SIZE);

   playlist_update(playlist, index, pathData, labelData,
         corePathData, coreNameData, crc32Data, dbNameData);
   playlist_write_file(playlist);
   playlist_free(playlist);

   reloadPlaylists();

   return true;
}
示例#23
0
void AddTaskDialog::setValidProtocols(const QHash<QString, int> &schemes)
{
    protocols = schemes.keys();
    scanClipboard();
}
示例#24
0
inline static bool comp_hash_label_key_lower(const QHash<QString, QString> &lhs, const QHash<QString, QString> &rhs)
{
   return lhs.value("label").toLower() < rhs.value("label").toLower();
}
示例#25
0
static QAction* getAction(int idx)
{
	return actionsDict.value(idx);
}
示例#26
0
/* Takes a list of files and folders and adds them to the currently selected playlist. Folders will have their contents added recursively. */
void MainWindow::addFilesToPlaylist(QStringList files)
{
   QStringList list;
   QString currentPlaylistPath;
   QListWidgetItem *currentItem = m_listWidget->currentItem();
   QByteArray currentPlaylistArray;
   QScopedPointer<QProgressDialog> dialog(NULL);
   PlaylistEntryDialog *playlistDialog = playlistEntryDialog();
   QHash<QString, QString> selectedCore;
   QHash<QString, QString> itemToAdd;
   QString selectedDatabase;
   QString selectedName;
   QString selectedPath;
   const char *currentPlaylistData = NULL;
   playlist_t *playlist = NULL;
   int i;

   /* Assume a blank list means we will manually enter in all fields. */
   if (files.isEmpty())
   {
      /* Make sure hash isn't blank, that would mean there's multiple entries to add at once. */
      itemToAdd["label"] = "";
      itemToAdd["path"] = "";
   }
   else if (files.count() == 1)
   {
      QString path = files.at(0);
      QFileInfo info(path);

      if (info.isFile())
      {
         itemToAdd["label"] = info.completeBaseName();
         itemToAdd["path"] = path;
      }
   }

   if (currentItem)
   {
      currentPlaylistPath = currentItem->data(Qt::UserRole).toString();

      if (!currentPlaylistPath.isEmpty())
      {
         currentPlaylistArray = currentPlaylistPath.toUtf8();
         currentPlaylistData = currentPlaylistArray.constData();
      }
   }

   if (currentPlaylistPath == ALL_PLAYLISTS_TOKEN)
   {
      showMessageBox(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_CANNOT_ADD_TO_ALL_PLAYLISTS), MainWindow::MSGBOX_TYPE_ERROR, Qt::ApplicationModal, false);
      return;
   }

   /* a blank itemToAdd means there will be multiple */
   if (!playlistDialog->showDialog(itemToAdd))
      return;

   selectedName = m_playlistEntryDialog->getSelectedName();
   selectedPath = m_playlistEntryDialog->getSelectedPath();
   selectedCore = m_playlistEntryDialog->getSelectedCore();
   selectedDatabase = m_playlistEntryDialog->getSelectedDatabase();

   if (selectedDatabase.isEmpty())
      selectedDatabase = QFileInfo(currentPlaylistPath).fileName();
   else
      selectedDatabase += file_path_str(FILE_PATH_LPL_EXTENSION);

   dialog.reset(new QProgressDialog(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_GATHERING_LIST_OF_FILES), "Cancel", 0, 0, this));
   dialog->setWindowModality(Qt::ApplicationModal);

   if (selectedName.isEmpty() || selectedPath.isEmpty() ||
       selectedDatabase.isEmpty())
   {
      showMessageBox(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_PLEASE_FILL_OUT_REQUIRED_FIELDS), MainWindow::MSGBOX_TYPE_ERROR, Qt::ApplicationModal, false);
      return;
   }

   if (files.isEmpty())
      files.append(selectedPath);

   for (i = 0; i < files.count(); i++)
   {
      QString path(files.at(i));
      QFileInfo fileInfo(path);

      if (dialog->wasCanceled())
         return;

      if (i % 25 == 0)
      {
         /* Needed to update progress dialog while doing a lot of stuff on the main thread. */
         qApp->processEvents();
      }

      if (fileInfo.isDir())
      {
         QDir dir(path);
         addDirectoryFilesToList(list, dir);
         continue;
      }

      if (fileInfo.isFile())
         list.append(fileInfo.absoluteFilePath());
      else if (files.count() == 1)
      {
         /* If adding a single file, tell user that it doesn't exist. */
         showMessageBox(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_FILE_DOES_NOT_EXIST), MainWindow::MSGBOX_TYPE_ERROR, Qt::ApplicationModal, false);
         return;
      }
   }

   dialog->setLabelText(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_ADDING_FILES_TO_PLAYLIST));
   dialog->setMaximum(list.count());

   playlist = playlist_init(currentPlaylistData, COLLECTION_SIZE);

   for (i = 0; i < list.count(); i++)
   {
      QString fileName = list.at(i);
      QFileInfo fileInfo;
      QByteArray fileBaseNameArray;
      QByteArray pathArray;
      QByteArray corePathArray;
      QByteArray coreNameArray;
      QByteArray databaseArray;
      const char *pathData = NULL;
      const char *fileNameNoExten = NULL;
      const char *corePathData = NULL;
      const char *coreNameData = NULL;
      const char *databaseData = NULL;

      if (dialog->wasCanceled())
      {
         playlist_free(playlist);
         return;
      }

      if (fileName.isEmpty())
         continue;

      fileInfo = fileName;

      if (files.count() == 1 && list.count() == 1 && i == 0)
      {
         fileBaseNameArray = selectedName.toUtf8();
         pathArray = QDir::toNativeSeparators(selectedPath).toUtf8();
      }
      else
      {
         fileBaseNameArray = fileInfo.completeBaseName().toUtf8();
         pathArray = QDir::toNativeSeparators(fileName).toUtf8();
      }

      fileNameNoExten = fileBaseNameArray.constData();

      /* a modal QProgressDialog calls processEvents() automatically in setValue() */
      dialog->setValue(i + 1);

      pathData = pathArray.constData();

      if (selectedCore.isEmpty())
      {
         corePathData = "DETECT";
         coreNameData = "DETECT";
      }
      else
      {
         corePathArray = QDir::toNativeSeparators(selectedCore.value("core_path")).toUtf8();
         coreNameArray = selectedCore.value("core_name").toUtf8();
         corePathData = corePathArray.constData();
         coreNameData = coreNameArray.constData();
      }

      databaseArray = selectedDatabase.toUtf8();
      databaseData = databaseArray.constData();

      if (path_is_compressed_file(pathData))
      {
         struct string_list *list = file_archive_get_file_list(pathData, NULL);

         if (list)
         {
            if (list->size == 1)
            {
               /* assume archives with one file should have that file loaded directly */
               pathArray = QDir::toNativeSeparators(QString(pathData) + "#" + list->elems[0].data).toUtf8();
               pathData = pathArray.constData();
            }

            string_list_free(list);
         }
      }

      playlist_push(playlist, pathData, fileNameNoExten,
            corePathData, coreNameData, "00000000|crc", databaseData);
   }

   playlist_write_file(playlist);
   playlist_free(playlist);

   reloadPlaylists();
}
const Style *DefaultStyleEngine::applyObjectStyle(const Style *baseStyle, const StyledObject &styledObject,
                                                  const Parameters *parameters)
{
    ElementType elementType = objectType(styledObject.object());

    class DepthProperties
    {
    public:
        DepthProperties()
            : m_elementType(TypeOther),
              m_visualPrimaryRole(DObject::PrimaryRoleNormal),
              m_visualSecondaryRole(DObject::SecondaryRoleNone)
        {
        }

        DepthProperties(ElementType elementType, DObject::VisualPrimaryRole visualPrimaryRole,
                        DObject::VisualSecondaryRole visualSecondaryRole)
            : m_elementType(elementType),
              m_visualPrimaryRole(visualPrimaryRole),
              m_visualSecondaryRole(visualSecondaryRole)
        {
        }

        ElementType m_elementType;
        DObject::VisualPrimaryRole m_visualPrimaryRole;
        DObject::VisualSecondaryRole m_visualSecondaryRole;
    };

    // find colliding elements which best match visual appearance of styled object
    DObject::VisualPrimaryRole styledVisualPrimaryRole = styledObject.objectVisuals().visualPrimaryRole();
    DObject::VisualSecondaryRole styledVisualSecondaryRole = styledObject.objectVisuals().visualSecondaryRole();
    QHash<int, DepthProperties> depths;
    foreach (const DObject *collidingObject, styledObject.collidingObjects()) {
        int collidingDepth = collidingObject->depth();
        if (collidingDepth < styledObject.object()->depth()) {
            ElementType collidingElementType = objectType(collidingObject);
            DObject::VisualPrimaryRole collidingVisualPrimaryRole = collidingObject->visualPrimaryRole();
            DObject::VisualSecondaryRole collidingVisualSecondaryRole = collidingObject->visualSecondaryRole();
            if (!depths.contains(collidingDepth)) {
                depths.insert(collidingDepth, DepthProperties(collidingElementType, collidingVisualPrimaryRole,
                                                              collidingVisualSecondaryRole));
            } else {
                bool updateProperties = false;
                DepthProperties properties = depths.value(collidingDepth);
                if (properties.m_elementType != elementType && collidingElementType == elementType) {
                    properties.m_elementType = collidingElementType;
                    properties.m_visualPrimaryRole = collidingVisualPrimaryRole;
                    properties.m_visualSecondaryRole = collidingVisualSecondaryRole;
                    updateProperties = true;
                } else if (properties.m_elementType == elementType && collidingElementType == elementType) {
                    if ((properties.m_visualPrimaryRole != styledVisualPrimaryRole
                         || properties.m_visualSecondaryRole != styledVisualSecondaryRole)
                            && collidingVisualPrimaryRole == styledVisualPrimaryRole
                            && collidingVisualSecondaryRole == styledVisualSecondaryRole) {
                        properties.m_visualPrimaryRole = collidingVisualPrimaryRole;
                        properties.m_visualSecondaryRole = collidingVisualSecondaryRole;
                        updateProperties = true;
                    }
                }
                if (updateProperties)
                    depths.insert(collidingDepth, properties);
            }
        }
    }
    int depth = 0;
    if (!depths.isEmpty()) {
        QList<int> keys = depths.keys();
        qSort(keys);
        foreach (int d, keys) {
            DepthProperties properties = depths.value(d);
            if (properties.m_elementType == elementType
                    && areStackingRoles(properties.m_visualPrimaryRole, properties.m_visualSecondaryRole,
                                        styledVisualPrimaryRole, styledVisualSecondaryRole)) {
                ++depth;
            } else {
                depth = 0;
            }
        }
QHash<quint32,MonsterDrops> BaseServerFight::loadMonsterDrop(const QString &file, QHash<quint32,Item> items,const QHash<quint32,Monster> &monsters)
{
    QMultiHash<quint32,MonsterDrops> monsterDrops;
    //open and quick check the file
    QFile xmlFile(file);
    QByteArray xmlContent;
    if(!xmlFile.open(QIODevice::ReadOnly))
    {
        DebugClass::debugConsole(QString("Unable to open the xml file: %1, error: %2").arg(xmlFile.fileName()).arg(xmlFile.errorString()));
        return monsterDrops;
    }
    xmlContent=xmlFile.readAll();
    xmlFile.close();
    QDomDocument domDocument;
    QString errorStr;
    int errorLine,errorColumn;
    if (!domDocument.setContent(xmlContent, false, &errorStr,&errorLine,&errorColumn))
    {
        DebugClass::debugConsole(QString("Unable to open the xml file: %1, Parse error at line %2, column %3: %4").arg(xmlFile.fileName()).arg(errorLine).arg(errorColumn).arg(errorStr));
        return monsterDrops;
    }
    QDomElement root = domDocument.documentElement();
    if(root.tagName()!="list")
    {
        DebugClass::debugConsole(QString("Unable to open the xml file: %1, \"plants\" root balise not found for the xml file").arg(xmlFile.fileName()));
        return monsterDrops;
    }

    //load the content
    bool ok;
    QDomElement item = root.firstChildElement("monster");
    while(!item.isNull())
    {
        if(item.isElement())
        {
            if(item.hasAttribute("id"))
            {
                quint32 id=item.attribute("id").toUInt(&ok);
                if(!ok)
                    DebugClass::debugConsole(QString("Unable to open the xml file: %1, id not a number: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                else if(!monsters.contains(id))
                    DebugClass::debugConsole(QString("Unable to open the xml file: %1, id into the monster list, skip: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                else
                {
                    QDomElement drops = item.firstChildElement("drops");
                    if(!drops.isNull())
                    {
                        if(drops.isElement())
                        {
                            QDomElement drop = drops.firstChildElement("drop");
                            while(!drop.isNull())
                            {
                                if(drop.isElement())
                                {
                                    if(drop.hasAttribute("item"))
                                    {
                                        MonsterDrops dropVar;
                                        if(drop.hasAttribute("quantity_min"))
                                        {
                                            dropVar.quantity_min=drop.attribute("quantity_min").toUInt(&ok);
                                            if(!ok)
                                                DebugClass::debugConsole(QString("Unable to open the xml file: %1, quantity_min is not a number: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                        }
                                        else
                                            dropVar.quantity_min=1;
                                        if(ok)
                                        {
                                            if(drop.hasAttribute("quantity_max"))
                                            {
                                                dropVar.quantity_max=drop.attribute("quantity_max").toUInt(&ok);
                                                if(!ok)
                                                    DebugClass::debugConsole(QString("Unable to open the xml file: %1, quantity_max is not a number: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                            else
                                                dropVar.quantity_max=1;
                                        }
                                        if(ok)
                                        {
                                            if(dropVar.quantity_min<=0)
                                            {
                                                ok=false;
                                                DebugClass::debugConsole(QString("Unable to open the xml file: %1, dropVar.quantity_min is 0: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                        }
                                        if(ok)
                                        {
                                            if(dropVar.quantity_max<=0)
                                            {
                                                ok=false;
                                                DebugClass::debugConsole(QString("Unable to open the xml file: %1, dropVar.quantity_max is 0: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                        }
                                        if(ok)
                                        {
                                            if(dropVar.quantity_max<dropVar.quantity_min)
                                            {
                                                ok=false;
                                                DebugClass::debugConsole(QString("Unable to open the xml file: %1, dropVar.quantity_max<dropVar.quantity_min: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                        }
                                        if(ok)
                                        {
                                            if(drop.hasAttribute("luck"))
                                            {
                                                QString luck=drop.attribute("luck");
                                                luck.remove("%");
                                                dropVar.luck=luck.toUShort(&ok);
                                                if(!ok)
                                                    DebugClass::debugConsole(QString("Unable to open the xml file: %1, luck is not a number: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                            else
                                                dropVar.luck=100;
                                        }
                                        if(ok)
                                        {
                                            if(dropVar.luck<=0)
                                            {
                                                ok=false;
                                                DebugClass::debugConsole(QString("Unable to open the xml file: %1, luck is 0!: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                            if(dropVar.luck>100)
                                            {
                                                ok=false;
                                                DebugClass::debugConsole(QString("Unable to open the xml file: %1, luck is greater than 100: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                        }
                                        if(ok)
                                        {
                                            if(drop.hasAttribute("item"))
                                            {
                                                dropVar.item=drop.attribute("item").toUInt(&ok);
                                                if(!ok)
                                                    DebugClass::debugConsole(QString("Unable to open the xml file: %1, item is not a number: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                            else
                                                dropVar.luck=100;
                                        }
                                        if(ok)
                                        {
                                            if(!items.contains(dropVar.item))
                                            {
                                                ok=false;
                                                DebugClass::debugConsole(QString("Unable to open the xml file: %1, the item is not into the item list: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                            }
                                        }
                                        if(ok)
                                            monsterDrops.insert(id,dropVar);
                                    }
                                    else
                                        DebugClass::debugConsole(QString("Unable to open the xml file: %1, as not item attribute: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                }
                                else
                                    DebugClass::debugConsole(QString("Unable to open the xml file: %1, effect balise is not an element: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                                drop = drop.nextSiblingElement("drop");
                            }
                        }
                        else
                            DebugClass::debugConsole(QString("Unable to open the xml file: %1, drops balise is not an element: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
                    }
                }
            }
            else
                DebugClass::debugConsole(QString("Unable to open the xml file: %1, have not the monster id: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
        }
        else
            DebugClass::debugConsole(QString("Unable to open the xml file: %1, is not an element: child.tagName(): %2 (at line: %3)").arg(xmlFile.fileName()).arg(item.tagName()).arg(item.lineNumber()));
        item = item.nextSiblingElement("monster");
    }
    return monsterDrops;
}
示例#29
0
文件: Model.cpp 项目: komadori/HsQML
QHash<int, QByteArray> HsQMLAutoListModel::roleNames() const
{
    QHash<int, QByteArray> roleNames;
    roleNames.insert(Qt::UserRole, QByteArray("modelData"));
    return roleNames;
}
示例#30
0
void PreferencesDialog::InitWaveInfo()
{
    QHash<MachineType, int> toprows;

    waveModel->clear();
    machlevel.clear();
    toprows.clear();
    QStringList headers;
    headers.append(tr("Name"));
    headers.append(tr("Color"));
    headers.append(tr("Overview"));
    headers.append(tr("Lower"));
    headers.append(tr("Upper"));
    headers.append(tr("Label"));
    headers.append(tr("Details"));
    waveModel->setHorizontalHeaderLabels(headers);
    ui->waveView->setColumnWidth(0, 200);
    ui->waveView->setColumnWidth(1, 40);
    ui->waveView->setColumnWidth(2, 60);
    ui->waveView->setColumnWidth(3, 50);
    ui->waveView->setColumnWidth(4, 50);
    ui->waveView->setColumnWidth(5, 100);
    ui->waveView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->waveView->setSelectionBehavior(QAbstractItemView::SelectItems);

    waveModel->setColumnCount(7);

    QStandardItem *hdr = nullptr;

    QMap<MachineType, QString> Section;

    Section[MT_CPAP] = tr("CPAP Waveforms");
    Section[MT_OXIMETER] = tr("Oximeter Waveforms");
    Section[MT_POSITION] = tr("Positional Waveforms");
    Section[MT_SLEEPSTAGE] = tr("Sleep Stage Waveforms");

    QMap<MachineType, QString>::iterator it;

    for (it = Section.begin(); it != Section.end(); ++it) {
        machlevel[it.key()] = hdr = new QStandardItem(it.value());
        hdr->setEditable(false);
        QList<QStandardItem *> list;
        list.append(hdr);
        for (int i=0; i<6; i++) {
            QStandardItem *it = new QStandardItem();
            it->setEnabled(false);
            list.append(it);
        }
        waveModel->appendRow(list);
    }

    ui->waveView->setAlternatingRowColors(true);

    // ui->graphView->setFirstColumnSpanned(0,daily->index(),true); // Crashes on windows.. Why do I need this again?

    QHash<QString, schema::Channel *>::iterator ci;

    SpinBoxDelegate * spinbox = new SpinBoxDelegate(ui->waveView);

    ui->waveView->setItemDelegateForColumn(3,spinbox);
    ui->waveView->setItemDelegateForColumn(4,spinbox);

    int row = 0;
    for (ci = schema::channel.names.begin(); ci != schema::channel.names.end(); ci++) {
        schema::Channel * chan = ci.value();
        if (chan->type() != schema::WAVEFORM) continue;

        QList<QStandardItem *> items;
        QStandardItem *it = new QStandardItem(chan->fullname());

        it->setCheckable(true);
        it->setCheckState(chan->enabled() ? Qt::Checked : Qt::Unchecked);
        it->setEditable(true);
        it->setData(chan->id(), Qt::UserRole);
        it->setToolTip(tr("Double click to change the descriptive name this channel."));
        items.push_back(it);

        it = new QStandardItem();
        it->setBackground(QBrush(chan->defaultColor()));
        it->setEditable(false);
        it->setData(chan->defaultColor().rgba(), Qt::UserRole);
        it->setToolTip(tr("Double click to change the default color for this channel plot/flag/data."));
        it->setSelectable(false);
        items.push_back(it);

        it = new QStandardItem();
        it->setCheckable(true);
        it->setCheckState(chan->showInOverview() ? Qt::Checked : Qt::Unchecked);
        it->setEditable(true);
        it->setData(chan->id(), Qt::UserRole);
        it->setToolTip(tr("Whether a breakdown of this waveform displays in overview."));
        items.push_back(it);


        it = new QStandardItem(QString::number(chan->lowerThreshold(),'f',1));
        it->setToolTip(tr("Here you can set the <b>lower</b> threshold used for certain calculations on the %1 waveform").arg(chan->fullname()));
        it->setEditable(true);
        items.push_back(it);

        it = new QStandardItem(QString::number(chan->upperThreshold(),'f',1));
        it->setToolTip(tr("Here you can set the <b>upper</b> threshold used for certain calculations on the %1 waveform").arg(chan->fullname()));
        it->setEditable(true);
        items.push_back(it);

        it = new QStandardItem(chan->label());
        it->setToolTip(tr("This is the short-form label to indicate this channel on screen."));

        it->setEditable(true);
        items.push_back(it);

        it = new QStandardItem(chan->description());
        it->setToolTip(tr("This is a description of what this channel does."));

        it->setEditable(true);
        items.push_back(it);

        row = toprows[chan->machtype()]++;
        machlevel[chan->machtype()]->insertRow(row, items);
    }

    for(QHash<MachineType, QStandardItem *>::iterator i = machlevel.begin(); i != machlevel.end(); ++i) {
        if (i.value()->rowCount() == 0) {
            waveModel->removeRow(i.value()->row());
        }
    }

    ui->waveView->expandAll();
    ui->waveView->setSortingEnabled(true);
}