Ejemplo n.º 1
0
int main(int argc, char **argv)
{
    KAboutData aboutData("previewer", 0, ki18n("Plasma-Studio Previewer"),
                         "1.0", ki18n(description), KAboutData::License_BSD,
                         ki18n("XXXX"));
    aboutData.setProgramIconName("plasma");
    aboutData.addAuthor(ki18n("XXX"),
                         ki18n("Original author"),
                        "*****@*****.**");

    KCmdLineArgs::init(argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add("list", ki18n("Displays a list of known applets"));
    options.add("f");
    options.add("formfactor <name>", ki18nc("Do not translate horizontal, vertical, mediacenter nor planar", "The formfactor to use (horizontal, vertical, mediacenter or planar)"), "planar");
    options.add("l");
    options.add("location <name>", ki18nc("Do not translate floating, desktop, fullscreen, top, bottom, left nor right", "The location constraint to start the Containment with (floating, desktop, fullscreen, top, bottom, left, right)"), "floating");
    options.add("c");
    options.add("containment <name>", ki18n("Name of the containment plugin"), "null");
    options.add("w");
    options.add("wallpaper <name>", ki18n("Name of the wallpaper plugin"), QByteArray());
    options.add("p");
    options.add("pixmapcache <size>", ki18n("The size in KB to set the pixmap cache to"));
    options.add("+applet", ki18n("Name of applet to add (required)"));
    options.add("+[args]", ki18n("Optional arguments of the applet to add"));
    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs() ;

    if (args->isSet("list")) {
        int maxLen = 0;
        QMap<QString, QString> applets;
        foreach (const KPluginInfo &info, Plasma::Applet::listAppletInfo()) {
            if (info.property("NoDisplay").toBool())
                continue;

            int len = info.pluginName().length();
            if (len > maxLen)
                maxLen = len;

            QString name = info.pluginName();
            QString comment = info.comment();

            if(comment.isEmpty())
                comment = i18n("No description available");

            applets.insert(name, comment);
        }

        QMap<QString, QString>::const_iterator it;
        for(it = applets.constBegin(); it != applets.constEnd(); it++) {
            QString applet("%1 - %2");

            applet = applet.arg(it.key().leftJustified(maxLen, ' ')).arg(it.value());
            std::cout << applet.toLocal8Bit().data() << std::endl;
        }

        return 0;
    }
Ejemplo n.º 2
0
void QgsWfsProjectParser::featureTypeList( QDomElement& parentElement, QDomDocument& doc ) const
{
    const QList<QDomElement>& projectLayerElements = mProjectParser->projectLayerElements();
    if ( projectLayerElements.size() < 1 )
    {
        return;
    }

    QStringList wfsLayersId = mProjectParser->wfsLayers();
    QSet<QString> wfstUpdateLayersId = wfstUpdateLayers();
    QSet<QString> wfstInsertLayersId = wfstInsertLayers();
    QSet<QString> wfstDeleteLayersId = wfstDeleteLayers();

    QMap<QString, QgsMapLayer *> layerMap;

    Q_FOREACH ( const QDomElement &elem, projectLayerElements )
    {
        QString type = elem.attribute( QStringLiteral( "type" ) );
        if ( type == QLatin1String( "vector" ) )
        {
            QString layerId = mProjectParser->layerId( elem );
            if ( !wfsLayersId.contains( layerId ) )
            {
                continue;
            }
            QgsMapLayer *layer = mProjectParser->createLayerFromElement( elem );
            if ( !layer )
            {
                continue;
            }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
            if ( !mAccessControl->layerReadPermission( layer ) )
            {
                continue;
            }
#endif
            QgsDebugMsg( QString( "add layer %1 to map" ).arg( layer->id() ) );
            layerMap.insert( layer->id(), layer );

            QDomElement layerElem = doc.createElement( QStringLiteral( "FeatureType" ) );
            QDomElement nameElem = doc.createElement( QStringLiteral( "Name" ) );
            //We use the layer name even though it might not be unique.
            //Because the id sometimes contains user/pw information and the name is more descriptive
            QString typeName = layer->name();
            if ( !layer->shortName().isEmpty() )
                typeName = layer->shortName();
            typeName = typeName.replace( QLatin1String( " " ), QLatin1String( "_" ) );
            QDomText nameText = doc.createTextNode( typeName );
            nameElem.appendChild( nameText );
            layerElem.appendChild( nameElem );

            QDomElement titleElem = doc.createElement( QStringLiteral( "Title" ) );
            QString titleName = layer->title();
            if ( titleName.isEmpty() )
            {
                titleName = layer->name();
            }
            QDomText titleText = doc.createTextNode( titleName );
            titleElem.appendChild( titleText );
            layerElem.appendChild( titleElem );

            QDomElement abstractElem = doc.createElement( QStringLiteral( "Abstract" ) );
            QString abstractName = layer->abstract();
            if ( abstractName.isEmpty() )
            {
                abstractName = QLatin1String( "" );
            }
            QDomText abstractText = doc.createTextNode( abstractName );
            abstractElem.appendChild( abstractText );
            layerElem.appendChild( abstractElem );

            //keyword list
            if ( !layer->keywordList().isEmpty() )
            {
                QDomElement keywordsElem = doc.createElement( QStringLiteral( "Keywords" ) );
                QDomText keywordsText = doc.createTextNode( layer->keywordList() );
                keywordsElem.appendChild( keywordsText );
                layerElem.appendChild( keywordsElem );
            }

            //appendExGeographicBoundingBox( layerElem, doc, layer->extent(), layer->crs() );

            QDomElement srsElem = doc.createElement( QStringLiteral( "SRS" ) );
            QDomText srsText = doc.createTextNode( layer->crs().authid() );
            srsElem.appendChild( srsText );
            layerElem.appendChild( srsElem );

            //wfs:Operations element
            QDomElement operationsElement = doc.createElement( QStringLiteral( "Operations" )/*wfs:Operations*/ );
            //wfs:Query element
            QDomElement queryElement = doc.createElement( QStringLiteral( "Query" )/*wfs:Query*/ );
            operationsElement.appendChild( queryElement );

            QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer*>( layer );
            QgsVectorDataProvider* provider = vlayer->dataProvider();
            if (( provider->capabilities() & QgsVectorDataProvider::AddFeatures ) && wfstInsertLayersId.contains( layer->id() ) )
            {
                //wfs:Insert element
                QDomElement insertElement = doc.createElement( QStringLiteral( "Insert" )/*wfs:Insert*/ );
                operationsElement.appendChild( insertElement );
            }
            if (( provider->capabilities() & QgsVectorDataProvider::ChangeAttributeValues ) &&
                    ( provider->capabilities() & QgsVectorDataProvider::ChangeGeometries ) &&
                    wfstUpdateLayersId.contains( layer->id() ) )
            {
                //wfs:Update element
                QDomElement updateElement = doc.createElement( QStringLiteral( "Update" )/*wfs:Update*/ );
                operationsElement.appendChild( updateElement );
            }
            if (( provider->capabilities() & QgsVectorDataProvider::DeleteFeatures ) && wfstDeleteLayersId.contains( layer->id() ) )
            {
                //wfs:Delete element
                QDomElement deleteElement = doc.createElement( QStringLiteral( "Delete" )/*wfs:Delete*/ );
                operationsElement.appendChild( deleteElement );
            }

            layerElem.appendChild( operationsElement );

            QgsRectangle layerExtent = layer->extent();
            QDomElement bBoxElement = doc.createElement( QStringLiteral( "LatLongBoundingBox" ) );
            bBoxElement.setAttribute( QStringLiteral( "minx" ), QString::number( layerExtent.xMinimum() ) );
            bBoxElement.setAttribute( QStringLiteral( "miny" ), QString::number( layerExtent.yMinimum() ) );
            bBoxElement.setAttribute( QStringLiteral( "maxx" ), QString::number( layerExtent.xMaximum() ) );
            bBoxElement.setAttribute( QStringLiteral( "maxy" ), QString::number( layerExtent.yMaximum() ) );
            layerElem.appendChild( bBoxElement );

            // layer metadata URL
            QString metadataUrl = layer->metadataUrl();
            if ( !metadataUrl.isEmpty() )
            {
                QDomElement metaUrlElem = doc.createElement( QStringLiteral( "MetadataURL" ) );
                QString metadataUrlType = layer->metadataUrlType();
                metaUrlElem.setAttribute( QStringLiteral( "type" ), metadataUrlType );
                QString metadataUrlFormat = layer->metadataUrlFormat();
                if ( metadataUrlFormat == QLatin1String( "text/xml" ) )
                {
                    metaUrlElem.setAttribute( QStringLiteral( "format" ), QStringLiteral( "XML" ) );
                }
                else
                {
                    metaUrlElem.setAttribute( QStringLiteral( "format" ), QStringLiteral( "TXT" ) );
                }
                QDomText metaUrlText = doc.createTextNode( metadataUrl );
                metaUrlElem.appendChild( metaUrlText );
                layerElem.appendChild( metaUrlElem );
            }

            parentElement.appendChild( layerElem );
        }
    }
Ejemplo n.º 3
0
void Spider::start(){

    XpathUtil *util = new XpathUtil(page);
    int count = 0;
    global::unVisitedUrl->pop();
    global::unVisitedUrl->pop();
    while (!global::unVisitedUrl->empty())
    {
        Node node = global::unVisitedUrl->top();
        this->node = node;
        //判断url是否本地采集过
        if(global::bf->contains(node.url.toStdString())){
            qDebug()<< node.url<<" already crawled before !";
            global::unVisitedUrl->pop();
            continue;
        }
        count++;
        qDebug()<<count;
        //判断数据采集节点是否服务器已经采集过
        if(node.depth == global::maxDepth){
            instance->flag = false;
            instance->getService = true;
            if(this->get(instance,node.url)){
                qDebug()<<"elasticesearch indexed :" +node.url;
                logInfo(QString::number(count)+" elasticesearch indexed :"+node.url);
                global::bf->insert(node.url.toStdString());
                global::unVisitedUrl->pop();
                continue;
            }
        }
        logInfo(QString::number(count)+" load url :"+node.url);
        qDebug()<<"load url :"+node.url;
        page->flag = true;
        page->mainFrame()->load(QUrl(node.url));
        QEventLoop eventLoop;
        QObject::connect(page, SIGNAL(loadFinished(bool)), &eventLoop, SLOT(quit()));
        QTimer timer;
        timer.setSingleShot(true);
        QObject::connect(&timer,SIGNAL(timeout()),&eventLoop,SLOT(quit()));
        //5s
        timer.start(5000);
        eventLoop.exec();       //block until finish
        if(timer.isActive()){
            timer.stop();
        }
        //采集数据节点
        int emptyCount = 0;
        if(node.depth == global::maxDepth){

            page->flag = true;
            QMap<int,QStringList> result;
            QMap<QString, QVariant> map;
            emptyCount=0;
            for(int j=0;j<node.collectData.size()-3;j++){
                QStringList tmpResult;
                QString nameFiled = node.collectData.at(j)["name"];
                QString resultFiled = util->parserXpath(page,node.collectData.at(j)["xpath"],node.collectData.at(j)["type"].toInt());
                //logInfo("[collect data ] nameFiled : "+nameFiled +" resultFiled :"+resultFiled);
                //logInfo("debug : "+node.collectData.at(j)["xpath"]+ " debug :"+node.collectData.at(j)["type"]);
                tmpResult.append(nameFiled);
                tmpResult.append(resultFiled);
                result.insert(j+1,tmpResult);
                map.insert(nameFiled,resultFiled);
                if(resultFiled.trimmed()==""){
                    emptyCount++;
                }
            }
            QStringList tmpResult;
            tmpResult.append("url");
            tmpResult.append(node.url);
            result.insert(node.collectData.size()-2,tmpResult);
            map.insert("url",node.url);
            QStringList tmpResult2;
            tmpResult2.append("来源");
            tmpResult2.append(global::taskID);
            result.insert(node.collectData.size()-1,tmpResult2);
            map.insert("来源",global::taskID);
            QDateTime current_date_time = QDateTime::currentDateTime();
            QString current_date = current_date_time.toString("yyyy-MM-dd hh:mm:ss");
            QStringList tmpResult3;
            tmpResult3.append("采集时间");
            tmpResult3.append(current_date);
            map.insert("采集时间",current_date);
            result.insert(node.collectData.size(),tmpResult3);
            if(emptyCount<7){
                global::sqlite->insertXpathResult(global::taskID,result);
                this->post(map,instance);

            }

        }else{
            //非采集节点
            page->flag = false;

            //qDebug()<<page->mainFrame()->toHtml();

            for(int j=0;j<node.regionXpath.size();j++){
                qDebug()<<"region xpath";
                this->node = (*(global::nodeMap))[node.depth];
                this->isRegionNode = true;
                this->currentSubNode = node.regionXpath.at(j);

                qDebug()<<"--------------------------";
                qDebug()<<"REGION :GET URL FROM XPATH";

                //QStringList regionUrlResult = util->getUrlFromXpath(page,node.regionXpath.at(j).value);
                QString html = util->parserXpath(page,node.regionXpath.at(j).value,2);
                qDebug()<<"------------------html";
                int time=1;
                while(html==""){
                    QTime t;
                    t.start();
                    while(t.elapsed()<time*1000){
                        QCoreApplication::processEvents();
                    }
                    time++;
                    html = util->parserXpath(page,node.regionXpath.at(j).value,2);
                    if(time>=5){
                        break;
                    }
                }
                qDebug()<<"time***********";
                qDebug()<<time;
                QStringList regionUrlResult = util->getUrl(html);

//                for(int i=0;i<regionUrlResult.length();i++){
//                    qDebug()<< "GET URL FROM XPATH";
//                    qDebug()<< regionUrlResult.at(i);
//                    addUrlToQueue(regionUrlResult.at(i));
//                }
                int count = util->getANodeNumFromXpath(page,node.regionXpath.at(j).value);
                qDebug()<<"**********************";
                qDebug()<<count;
                qDebug()<<"**********************";
                if(count==0){
                    count = util->getANodeNumFromXpath(page,node.regionXpath.at(j).value);
                }
                for(int m=0;m<count;m++){
                    util->clickNodeAtCount(page,node.regionXpath.at(j).value,m);
                }
            }

            for(int j=0;j<node.loopXpath.size();j++){
                qDebug()<<"loop xpath";
                this->node = (*(global::nodeMap))[node.depth];
                this->isRegionNode = false;
                qDebug()<<"--------------------------";
                qDebug()<<"LOOP :GET URL FROM XPATH";
                QStringList loopUrlResult = util->getUrlFromXpath(page,node.loopXpath.at(j).value);
                for(int i=0;i<loopUrlResult.length();i++){
                    qDebug()<< "GET URL FROM XPATH";
                    qDebug()<< loopUrlResult.at(i);
                    addUrlToQueue(loopUrlResult.at(i));
                }

                int count = util->getANodeNumFromXpath(page,node.loopXpath.at(j).value);

                for(int m=0;m<count;m++){
                    util->clickNodeAtCount(page,node.loopXpath.at(j).value,m);
                }
            }
        }
        global::bf->insert(node.url.toStdString());
        global::unVisitedUrl->pop();
    }
    logInfo("spider finished");
    emit finish();
    qDebug()<<"spider finished";
}
Ejemplo n.º 4
0
GroupchatTopicDlg::GroupchatTopicDlg(GCMainDlg *parent) :
    QDialog(parent),
    m_ui(new Ui::GroupchatTopicDlg),
    m_addLangUi(new Ui::GroupChatTopicAddLangDlg)
{
    m_ui->setupUi(this);
    QKeySequence sendKey = ShortcutManager::instance()->shortcut("chat.send");
    if (sendKey == QKeySequence(Qt::Key_Enter) || sendKey == QKeySequence(Qt::Key_Return)) {
        sendKey = QKeySequence(Qt::CTRL + Qt::Key_Return);
    }
    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setShortcut(sendKey);

    auto cw = new QToolButton();
    cw->setIcon(IconsetFactory::icon("psi/add").icon());
    m_ui->twLang->setCornerWidget(cw);
    QObject::connect(m_ui->twLang, &QTabWidget::tabCloseRequested, this, [=](int index) {
        m_ui->twLang->widget(index)->deleteLater();
        m_ui->twLang->removeTab(index);
    });
    QObject::connect(cw, &QToolButton::clicked, this, [=](bool checked) {
        Q_UNUSED(checked);
        if (!addLangDlg) {
            addLangDlg = new QDialog(this);
            m_addLangUi->setupUi(addLangDlg);
            addLangDlg->setWindowIcon(QIcon(IconsetFactory::iconPixmap("psi/logo_128")));
            addLangDlg->setAttribute(Qt::WA_DeleteOnClose);

            m_addLangUi->cmbLang->addItem(tr("Any Language"), 0);
            QMap<QString,QLocale::Language> langs;
            for (auto const &loc : QLocale::matchingLocales(
                     QLocale::AnyLanguage,
                     QLocale::AnyScript,
                     QLocale::AnyCountry))
            {
                if (loc != QLocale::c()) {
                    langs.insert(QLocale::languageToString(loc.language()), loc.language());
                }
            }
            for (auto lang: langs) {
                LanguageManager::LangId id;
                id.language = lang;
                m_addLangUi->cmbLang->addItem(LanguageManager::languageName(id), lang);
            }

            populateCountryAndScript();

            addLangDlg->adjustSize();
            addLangDlg->move(cw->mapToGlobal(QPoint(cw->width() - addLangDlg->width(), cw->height())));
            addLangDlg->show();
            QObject::connect(addLangDlg,  &QDialog::accepted, this, [=]() {
                LanguageManager::LangId id;
                id.language = m_addLangUi->cmbLang->currentData().toInt();
                id.script = m_addLangUi->cmbScript->currentData().toInt();
                id.country = m_addLangUi->cmbCountry->currentData().toInt();
                bool found = false;
                for (int i = 0; i < m_ui->twLang->count(); i++) {
                    QPlainTextEdit *edit = static_cast<QPlainTextEdit *>(m_ui->twLang->widget(i));
                    LanguageManager::LangId tabId = edit->property("langId").value<LanguageManager::LangId>();
                    if (id == tabId) {
                        m_ui->twLang->setCurrentIndex(i);
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    addLanguage(id);
                }
            });

            QObject::connect(m_addLangUi->cmbLang, static_cast<void(QComboBox::*)(int index)>(&QComboBox::currentIndexChanged), this, [=](int index) {
                Q_UNUSED(index)
                populateCountryAndScript();
            });
        } else {
            addLangDlg->setFocus();
        }
    });
}
Ejemplo n.º 5
0
void QgsWCSProjectParser::wcsContentMetadata( QDomElement& parentElement, QDomDocument& doc ) const
{
    const QList<QDomElement>& projectLayerElements = mProjectParser->projectLayerElements();
    if ( projectLayerElements.size() < 1 )
    {
        return;
    }

    QStringList wcsLayersId = wcsLayers();

    QMap<QString, QgsMapLayer *> layerMap;

    Q_FOREACH ( const QDomElement &elem, projectLayerElements )
    {
        QString type = elem.attribute( "type" );
        if ( type == "raster" )
        {
            QgsMapLayer *layer = mProjectParser->createLayerFromElement( elem );
            if ( layer && wcsLayersId.contains( layer->id() ) )
            {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
                if ( !mAccessControl->layerReadPermission( layer ) )
                {
                    continue;
                }
#endif
                QgsDebugMsg( QString( "add layer %1 to map" ).arg( layer->id() ) );
                layerMap.insert( layer->id(), layer );

                QDomElement layerElem = doc.createElement( "CoverageOfferingBrief" );
                QDomElement nameElem = doc.createElement( "name" );
                //We use the layer name even though it might not be unique.
                //Because the id sometimes contains user/pw information and the name is more descriptive
                QString typeName = layer->name();
                if ( !layer->shortName().isEmpty() )
                    typeName = layer->shortName();
                typeName = typeName.replace( " ", "_" );
                QDomText nameText = doc.createTextNode( typeName );
                nameElem.appendChild( nameText );
                layerElem.appendChild( nameElem );

                QDomElement labelElem = doc.createElement( "label" );
                QString titleName = layer->title();
                if ( titleName.isEmpty() )
                {
                    titleName = layer->name();
                }
                QDomText labelText = doc.createTextNode( titleName );
                labelElem.appendChild( labelText );
                layerElem.appendChild( labelElem );

                QDomElement descriptionElem = doc.createElement( "description" );
                QString abstractName = layer->abstract();
                if ( abstractName.isEmpty() )
                {
                    abstractName = "";
                }
                QDomText descriptionText = doc.createTextNode( abstractName );
                descriptionElem.appendChild( descriptionText );
                layerElem.appendChild( descriptionElem );

                //lonLatEnvelope
                QgsCoordinateReferenceSystem layerCrs = layer->crs();
                QgsCoordinateTransform t( layerCrs, QgsCoordinateReferenceSystem( 4326 ) );
                //transform
                QgsRectangle BBox;
                try
                {
                    BBox = t.transformBoundingBox( layer->extent() );
                }
                catch ( QgsCsException &e )
                {
                    QgsDebugMsg( QString( "Transform error caught: %1. Using original layer extent." ).arg( e.what() ) );
                    BBox = layer->extent();
                }
                QDomElement lonLatElem = doc.createElement( "lonLatEnvelope" );
                lonLatElem.setAttribute( "srsName", "urn:ogc:def:crs:OGC:1.3:CRS84" );
                QDomElement lowerPosElem = doc.createElement( "gml:pos" );
                QDomText lowerPosText = doc.createTextNode( QString::number( BBox.xMinimum() ) + " " +  QString::number( BBox.yMinimum() ) );
                lowerPosElem.appendChild( lowerPosText );
                lonLatElem.appendChild( lowerPosElem );
                QDomElement upperPosElem = doc.createElement( "gml:pos" );
                QDomText upperPosText = doc.createTextNode( QString::number( BBox.xMaximum() ) + " " +  QString::number( BBox.yMaximum() ) );
                upperPosElem.appendChild( upperPosText );
                lonLatElem.appendChild( upperPosElem );
                layerElem.appendChild( lonLatElem );

                parentElement.appendChild( layerElem );
            }
        }
    }
Ejemplo n.º 6
0
QMap<QString, QVariant > KstViewBox::widgetHints(const QString& propertyName) const {
  QMap<QString, QVariant> map = KstViewObject::widgetHints(propertyName);
  if (!map.empty()) {
    return map;  
  }
  if (propertyName == "xRound") {
    map.insert(QString("_kst_widgetType"), QString("QSpinBox"));
    map.insert(QString("_kst_label"), i18n("X Roundness"));
    map.insert(QString("minValue"), 0);   
  } else if (propertyName == "yRound") {
    map.insert(QString("_kst_widgetType"), QString("QSpinBox"));
    map.insert(QString("_kst_label"), i18n("Y Roundness"));
    map.insert(QString("minValue"), 0);  
  } else if (propertyName == "foregroundColor") {
    map.insert(QString("_kst_widgetType"), QString("KColorButton"));
    map.insert(QString("_kst_label"), i18n("Fill Color"));
  } else if (propertyName == "transparentFill") {
    map.insert(QString("_kst_widgetType"), QString("QCheckBox"));
    map.insert(QString("_kst_label"), QString::null);
    map.insert(QString("text"), i18n("Transparent fill"));
  } if (propertyName == "borderColor") {
    map.insert(QString("_kst_widgetType"), QString("KColorButton"));
    map.insert(QString("_kst_label"), i18n("Border color"));
  } else if (propertyName == "borderWidth") {
    map.insert(QString("_kst_widgetType"), QString("QSpinBox"));
    map.insert(QString("_kst_label"), i18n("Border width"));
    map.insert(QString("minValue"), 0);
  }
  return map;
}
Ejemplo n.º 7
0
void TimeoutsTest::identityRegisterTwice()
{
    QEventLoop loop;
    QTimer::singleShot(test_timeout, &loop, SLOT(quit()));
    QObject::connect(this, SIGNAL(finished()), &loop, SLOT(quit()));

    QMap<MethodName,MechanismsList> methods;
    methods.insert("dummy", QStringList() << "mech1" << "mech2");
    IdentityInfo info = IdentityInfo(QLatin1String("timeout test"),
                                     QLatin1String("timeout@test"),
                                     methods);
    info.setAccessControlList(QStringList() << "*");
    Identity *identity = Identity::newIdentity(info);
    QVERIFY(identity != NULL);

    QObject::connect(identity,
                     SIGNAL(credentialsStored(const quint32)),
                     this,
                     SLOT(credentialsStored(const quint32)));
    QObject::connect(identity,
                     SIGNAL(error(const SignOn::Error &)),
                     this,
                     SLOT(identityError(const SignOn::Error &)));

    identity->storeCredentials();

    loop.exec();
    QVERIFY(identity->id() != SSO_NEW_IDENTITY);

    QDBusConnection conn = SIGNOND_BUS;

    QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE,
                                                      SIGNOND_DAEMON_OBJECTPATH,
                                                      SIGNOND_DAEMON_INTERFACE,
                                                      "getIdentity");
    QList<QVariant> args;
    args << identity->id();
    msg.setArguments(args);

    QDBusMessage reply = conn.call(msg);
    QCOMPARE(reply.type(), QDBusMessage::ReplyMessage);

    QDBusObjectPath objectPath = reply.arguments()[0].value<QDBusObjectPath>();
    QString path = objectPath.path();
    qDebug() << "Got path" << path;
    QVERIFY(!path.isEmpty());

    bool success;

    QTest::qSleep(100);
    success = triggerDisposableCleanup();
    QVERIFY(success);

    /* The identity object must exist now */
    QVERIFY(identityAlive(path));

    QTest::qSleep(6 * 1000);
    /* now we register the same identity again. The expected behavior is that
     * the registration succeeds, possibly returning the same object path as
     * before.
     * This is to test a regression (NB#182914) which was happening because
     * signond was deleting the expired Identity immediately after returning
     * its object path to the client.
     */
    reply = conn.call(msg);
    QVERIFY(reply.type() == QDBusMessage::ReplyMessage);

    objectPath = reply.arguments()[0].value<QDBusObjectPath>();
    path = objectPath.path();
    qDebug() << "Got path" << path;
    QVERIFY(!path.isEmpty());

    QVERIFY(identityAlive(path));
}
void MTPageNym_AltLocation::initializePage() //virtual
{
    if (!bInitialized)
    {
        bInitialized=true;

    WizardEditProfile * pWizard = dynamic_cast<WizardEditProfile *>(wizard());
    const bool bEditingExistingProfile = (nullptr != pWizard);

    listContactDataTuples copy_of_list;
    if (bEditingExistingProfile) copy_of_list = pWizard->listContactDataTuples_;
    // ------------------------------
    //QList<QWidget *>  listTabs_;
    int nCurrentTab = 0;

    std::set<uint32_t> sections = opentxs::OTAPI_Wrap::OTAPI()->GetContactSections();

    for (auto & indexSection: sections)  //Names (for example)
    {
        nCurrentTab++;
        bool bAddedInitialItem = false;

        QMap<uint32_t, QString> mapTypeNames;
        // ----------------------------------------
        // Create a new (tab page) Widget.
        QWidget * pTab = new QWidget(this);
        std::string sectionName = opentxs::OTAPI_Wrap::OTAPI()->GetContactSectionName (indexSection);

        if (opentxs::proto::CONTACTSECTION_RELATIONSHIPS == indexSection)
        {
            pTab->setEnabled(false);
            pTab->setVisible(false);
        }
        // ----------------------------------------

//      pTab->setWindowTitle(QString::fromStdString(sectionName));
        // ----------------------------
        // Setup the widget

        //QMap<int, QList<GroupBoxContactItems *> * > mapGroupBoxLists_;

        QList<GroupBoxContactItems *> * pListGroupBoxes = new QList<GroupBoxContactItems *>;

        std::set<uint32_t> sectionTypes = opentxs::OTAPI_Wrap::OTAPI()->GetContactSectionTypes(indexSection);

        for (auto & indexSectionType: sectionTypes)
        {
            std::string typeName = opentxs::OTAPI_Wrap::OTAPI()->GetContactTypeName(indexSectionType);
            mapTypeNames.insert(indexSectionType, QString::fromStdString(typeName));
        }
        // -------------------------------
        QVBoxLayout * pvBox = new QVBoxLayout(pTab);
        pvBox->setAlignment(Qt::AlignTop);
        pvBox->setMargin(0);
        pTab->setContentsMargins(0,0,0,0);
        // -------------------------------
        int nContactItemsAdded = 0;

        for (auto & indexSectionType: sectionTypes) // BUSINESS Name (for example)
        {
            GroupBoxContactItems   * pGroupBox = new GroupBoxContactItems(pTab);
            QVBoxLayout            * layout    = new QVBoxLayout(pGroupBox);
            // -------------------------------
            pGroupBox->setFlat(true);
            pGroupBox->setContentsMargins(0,0,0,0);

            layout->setMargin(0);

            pGroupBox->indexSection_ = indexSection;
            pGroupBox->indexSectionType_ = indexSectionType;
            pGroupBox->mapTypeNames_ = mapTypeNames;

            if (bEditingExistingProfile) // We're editing pre-existing claims, so need to add them to the UI.
            {
        //      typedef std::tuple<uint32_t, uint32_t, std::string, bool> tupleContactDataItem;
        //      typedef std::list<tupleContactDataItem> listContactDataTuples;

//                qDebug() << "===> copy_of_list.size(): " << copy_of_list.size();

                int nCounter=0;
                for (auto & data_item: copy_of_list)
                {
//                    qDebug() << "Loop through copy_of_list nCounter: " << nCounter++;
//                    qDebug() << "std::get<0>(data_item): " << std::get<0>(data_item);
//                    qDebug() << "std::get<1>(data_item): " << std::get<1>(data_item);
//                    qDebug() << "std::get<2>(data_item): " << QString::fromStdString(std::get<2>(data_item));
//                    qDebug() << "std::get<3>(data_item): " << std::get<3>(data_item);

                    const uint32_t    item_section = std::get<0>(data_item);
                    const uint32_t    item_type    = std::get<1>(data_item);
                    const std::string item_value   = std::get<2>(data_item);
                    const bool        item_primary = std::get<3>(data_item);

                    if ( (item_section == indexSection) &&
                         (item_type    == indexSectionType) )
                    {
                        // Crash isolated to the below line of code:
                        //qDebug() << "Crash isolated to below line of code: indexSectionType: " << indexSectionType;

                        OT_ASSERT(indexSectionType >= 1);

//                      QWidget * pItem = createSingleContactItem(pGroupBox);
                        QWidget * pItem = createSingleContactItem(pGroupBox, indexSectionType-1,
                                                        QString::fromStdString(item_value), item_primary);

                        if (nullptr != pItem)
                        {
                            layout->addWidget(pItem);
                            nContactItemsAdded++;
                        }
                    }
                }

                if (!bAddedInitialItem && (0 == nContactItemsAdded) )
                {
                    bAddedInitialItem = true;
                    QWidget * pItem = createSingleContactItem(pGroupBox);

                    if (nullptr != pItem)
                    {
                        layout->addWidget(pItem);
                        nContactItemsAdded++;
                    }
                }

                if (nContactItemsAdded > 0)
                    pGroupBox->setLayout(layout);
            }
            else // This wizard is for a new Nym being created for the first time. He has no pre-existing claims.
            {
                if (!bAddedInitialItem &&
                        ( (1 != indexSection) ||     // hardcoded for CONTACTSECTION_NAME
                          (1 == indexSectionType ))  // hardcoded for CITEMTYPE_PERSONAL
                        )
                {
                    bAddedInitialItem = true;
                    QWidget * pInitialItem = nullptr;
                    if (1 == nCurrentTab)
                    {
                        // Pre-fill the name on the first tab.
                        QString qstrName = wizard()->field("Name").toString();
                        pInitialItem = createSingleContactItem(pGroupBox, 0, qstrName, true);
                    }
                    else
                        pInitialItem = createSingleContactItem(pGroupBox);

                    if (nullptr != pInitialItem)
                    {
                        layout->addWidget(pInitialItem);
                        nContactItemsAdded++;
                    }

                    pGroupBox->setLayout(layout);
                }
            }
            // -------------------------------
            pGroupBox->pListGroupBoxes_ = pListGroupBoxes;
            pListGroupBoxes->append(pGroupBox);
            pvBox->addWidget(pGroupBox);

            if (0 == nContactItemsAdded)
                pGroupBox->setVisible(false);
            else
                pGroupBox->setVisible(true);
            // -------------------------------
        }
        pTab->setLayout(pvBox);
        // ----------------------------
        // Add new Widget to TabWidget
        //
        listTabs_.append(pTab);
        mapGroupBoxLists_.insert(indexSection, pListGroupBoxes);
        ui->tabWidget->addTab(pTab, QString::fromStdString(sectionName));
    }

    if (!bEditingExistingProfile)
        PrepareOutputData();
    }
}
Ejemplo n.º 9
0
QMap<ItemId, CommitResult> StorageHandler::commitAddedItems( StoragePlugin& aPlugin, 
		                               ConflictResolver* aConflictResolver )
{
    FUNCTION_CALL_TRACE;

    QMap<ItemId, CommitResult> results = resolveConflicts (aConflictResolver, iAddList, COMMIT_INIT_ADD);    
    QList<ItemId> addIds = iAddList.keys();
    QList<SyncItem*> addItems = iAddList.values();

    LOG_DEBUG( "Committing" << addItems.count() << "added items" );

    QList<StoragePlugin::StoragePluginStatus> addStatus = aPlugin.addItems( addItems );

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

        CommitResult& result = results[addIds[i]];
        result.iItemKey = *addItems[i]->getKey();
        
        LOG_DEBUG( "Item" << addIds[i].iCmdId << "/" << addIds[i].iItemIndex << "committed" );

        switch( addStatus[i] )
        {

            case StoragePlugin::STATUS_OK:
            {
                LOG_DEBUG( "Commit result: COMMIT_ADDED" );
                result.iStatus = COMMIT_ADDED;
                
		emit itemProcessed( MOD_ITEM_ADDED, MOD_LOCAL_DATABASE,
                                    aPlugin.getSourceURI() , addItems[i]->getType(), addItems.count() );

                break;
            }
            case StoragePlugin::STATUS_DUPLICATE:
            {
                LOG_DEBUG( "Commit result: COMMIT_DUPLICATE" );
                result.iStatus = COMMIT_DUPLICATE;

                emit itemProcessed( MOD_ITEM_ADDED, MOD_LOCAL_DATABASE,
                                    aPlugin.getSourceURI() , addItems[i]->getType(), addItems.count() );

                break;
            }
            default:
            {
                result.iStatus = generalStatus( addStatus[i] );

                emit itemProcessed( MOD_ITEM_ERROR, MOD_LOCAL_DATABASE,
                                    aPlugin.getSourceURI() , addItems[i]->getType(), addItems.count() );

                break;
            }

        }

        results.insert( addIds[i], result );

    }

    qDeleteAll( addItems );
    iAddList.clear();

    return results;
}
Ejemplo n.º 10
0
bool CCImage::initWithString(
        const char * pText,
        int nWidth/* = 0*/,
        int nHeight/* = 0*/,
        ETextAlign eAlignMask/* = kAlignCenter*/,
        const char * pFontName/* = nil*/,
        int nSize/* = 0*/)
{
    if (!pText)
    {
        return false;
    }

    QString fontPath(CCFileUtils::fullPathFromRelativePath(pFontName));

    QString fontFamily = pFontName;
    QString fontStyle = "Normal";

    // font already loaded?
    QMap<QString, QString>::iterator fontIter = loadedFontMap.find(fontPath);
    if(fontIter == loadedFontMap.end())
    {
        int fontID = QFontDatabase::addApplicationFont(fontPath);
        if(fontID != -1)
        {
            QStringList familyList = QFontDatabase::applicationFontFamilies(fontID);

            if(familyList.size() > 0)
                fontFamily = familyList.at(0);
        }

        loadedFontMap.insert(fontPath, fontFamily);
    }
    else
    {
        fontFamily = fontIter.value();
    }

    QFontDatabase fd;
    QFont f = fd.font(fontFamily, fontStyle, nSize);
    f.setPixelSize(nSize);

    QFontMetrics fm(f);

    if (nWidth)
    {
        m_nWidth = (short)nWidth;
    }
    else
    {
        m_nWidth = fm.width(QString(pText));
    }

    if (nHeight)
    {
        m_nHeight = (short)nHeight;
    }
    else
    {
        m_nHeight = fm.height();
    }

    m_bHasAlpha = true;
    m_bPreMulti = false;
    m_pData = new unsigned char[m_nWidth * m_nHeight * 4];
    memset(m_pData, 0, m_nWidth * m_nHeight * 4);
    m_nBitsPerComponent = 8;

    QImage image(m_pData, m_nWidth, m_nHeight, QImage::Format_ARGB32_Premultiplied);
    QPainter painter(&image);
    painter.setFont(f);
    painter.setPen(Qt::white);

    int flags = 0;
    switch (eAlignMask)
    {
    case kAlignCenter: // Horizontal center and vertical center.
        flags |= Qt::AlignHCenter;
        flags |= Qt::AlignVCenter;
        break;
    case kAlignTop: // Horizontal center and vertical top.
        flags |= Qt::AlignHCenter;
        flags |= Qt::AlignTop;
        break;
    case kAlignTopRight: // Horizontal right and vertical top.
        flags |= Qt::AlignRight;
        flags |= Qt::AlignTop;
        break;
    case kAlignRight: // Horizontal right and vertical center.
        flags |= Qt::AlignRight;
        flags |= Qt::AlignVCenter;
        break;
    case kAlignBottomRight: // Horizontal right and vertical bottom.
        flags |= Qt::AlignRight;
        flags |= Qt::AlignBottom;
        break;
    case kAlignBottom: // Horizontal center and vertical bottom.
        flags |= Qt::AlignHCenter;
        flags |= Qt::AlignBottom;
        break;
    case kAlignBottomLeft: // Horizontal left and vertical bottom.
        flags |= Qt::AlignLeft;
        flags |= Qt::AlignBottom;
        break;
    case kAlignLeft: // Horizontal left and vertical center.
        flags |= Qt::AlignLeft;
        flags |= Qt::AlignVCenter;
        break;
    case kAlignTopLeft: // Horizontal left and vertical top.
        flags |= Qt::AlignLeft;
        flags |= Qt::AlignTop;
        break;
    }

    painter.drawText(QRect(0, 0, m_nWidth, m_nHeight), flags, QString(pText));
    painter.end();

    return true;
}
Ejemplo n.º 11
0
bool KArchiveDirectory::copyTo(const QString &dest, bool recursiveCopy) const
{
    QDir root;

    QList<const KArchiveFile *> fileList;
    QMap<qint64, QString> fileToDir;

    // placeholders for iterated items
    QStack<const KArchiveDirectory *> dirStack;
    QStack<QString> dirNameStack;

    dirStack.push(this);       // init stack at current directory
    dirNameStack.push(dest);   // ... with given path
    do {
        const KArchiveDirectory *curDir = dirStack.pop();
        const QString curDirName = dirNameStack.pop();
        if (!root.mkpath(curDirName)) {
            return false;
        }

        const QStringList dirEntries = curDir->entries();
        for (QStringList::const_iterator it = dirEntries.begin(); it != dirEntries.end(); ++it) {
            const KArchiveEntry *curEntry = curDir->entry(*it);
            if (!curEntry->symLinkTarget().isEmpty()) {
                QString linkName = curDirName + QLatin1Char('/') + curEntry->name();
                // To create a valid link on Windows, linkName must have a .lnk file extension.
#ifdef Q_OS_WIN
                if (!linkName.endsWith(QStringLiteral(".lnk"))) {
                    linkName += QStringLiteral(".lnk");
                }
#endif
                QFile symLinkTarget(curEntry->symLinkTarget());
                if (!symLinkTarget.link(linkName)) {
                    //qDebug() << "symlink(" << curEntry->symLinkTarget() << ',' << linkName << ") failed:" << strerror(errno);
                }
            } else {
                if (curEntry->isFile()) {
                    const KArchiveFile *curFile = dynamic_cast<const KArchiveFile *>(curEntry);
                    if (curFile) {
                        fileList.append(curFile);
                        fileToDir.insert(curFile->position(), curDirName);
                    }
                }

                if (curEntry->isDirectory() && recursiveCopy) {
                    const KArchiveDirectory *ad = dynamic_cast<const KArchiveDirectory *>(curEntry);
                    if (ad) {
                        dirStack.push(ad);
                        dirNameStack.push(curDirName + QLatin1Char('/') + curEntry->name());
                    }
                }
            }
        }
    } while (!dirStack.isEmpty());

    qSort(fileList.begin(), fileList.end(), sortByPosition);    // sort on d->pos, so we have a linear access

    for (QList<const KArchiveFile *>::const_iterator it = fileList.constBegin(), end = fileList.constEnd();
            it != end; ++it) {
        const KArchiveFile *f = *it;
        qint64 pos = f->position();
        if (!f->copyTo(fileToDir[pos])) {
            return false;
        }
    }
    return true;
}
Ejemplo n.º 12
0
void QgsGeometryCheckerSetupTab::runChecks()
{
  // Get selected layer
  QList<QgsVectorLayer *> layers = getSelectedLayers();
  if ( layers.isEmpty() )
    return;

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    for ( QgsVectorLayer *layer : layers )
    {
      if ( layer->dataProvider()->dataSourceUri().startsWith( ui.lineEditOutputDirectory->text() ) )
      {
        QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The chosen output directory contains one or more input layers." ) );
        return;
      }
    }
  }
  QgsVectorLayer *lineLayerCheckLayer = ui.comboLineLayerIntersection->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ) : nullptr;
  QgsVectorLayer *followBoundaryCheckLayer = ui.comboBoxFollowBoundaries->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboBoxFollowBoundaries->currentData().toString() ) ) : nullptr;
  if ( layers.contains( lineLayerCheckLayer ) || layers.contains( followBoundaryCheckLayer ) )
  {
    QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The selected input layers cannot contain a layer also selected for a topology check." ) );
    return;
  }

  for ( QgsVectorLayer *layer : layers )
  {
    if ( layer->isEditable() )
    {
      QMessageBox::critical( this, tr( "Check Geometries" ), tr( "Input layer '%1' is not allowed to be in editing mode." ).arg( layer->name() ) );
      return;
    }
  }
  bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked();

  // Set window busy
  setCursor( Qt::WaitCursor );
  mRunButton->setEnabled( false );
  ui.labelStatus->setText( tr( "<b>Preparing output...</b>" ) );
  ui.labelStatus->show();
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );

  QList<QgsVectorLayer *> processLayers;
  if ( ui.radioButtonOutputNew->isChecked() )
  {
    // Get output directory and file extension
    QDir outputDir = QDir( ui.lineEditOutputDirectory->text() );
    QString outputDriverName = ui.comboBoxOutputFormat->currentData().toString();
    QgsVectorFileWriter::MetaData metadata;
    if ( !QgsVectorFileWriter::driverMetadata( outputDriverName, metadata ) )
    {
      QMessageBox::critical( this, tr( "Check Geometries" ), tr( "The specified output format cannot be recognized." ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
    QString outputExtension = metadata.ext;

    // List over input layers, check which existing project layers need to be removed and create output layers
    QString filenamePrefix = ui.lineEditFilenamePrefix->text();
    QSettings().setValue( "/geometry_checker/previous_values/filename_prefix", filenamePrefix );
    QStringList toRemove;
    QStringList createErrors;
    for ( QgsVectorLayer *layer : layers )
    {
      QString outputPath = outputDir.absoluteFilePath( filenamePrefix + layer->name() + "." + outputExtension );

      // Remove existing layer with same uri from project
      for ( QgsVectorLayer *projectLayer : QgsProject::instance()->layers<QgsVectorLayer *>() )
      {
        if ( projectLayer->dataProvider()->dataSourceUri().startsWith( outputPath ) )
        {
          toRemove.append( projectLayer->id() );
        }
      }

      // Create output layer
      QString errMsg;
      QgsVectorFileWriter::WriterError err =  QgsVectorFileWriter::writeAsVectorFormat( layer, outputPath, layer->dataProvider()->encoding(), layer->crs(), outputDriverName, selectedOnly, &errMsg );
      if ( err != QgsVectorFileWriter::NoError )
      {
        createErrors.append( errMsg );
        continue;
      }

      QgsVectorLayer *newlayer = new QgsVectorLayer( outputPath, QFileInfo( outputPath ).completeBaseName(), QStringLiteral( "ogr" ) );
      if ( selectedOnly )
      {
        QgsFeature feature;

        // Get features to select (only selected features were written up to this point)
        QgsFeatureIds selectedFeatures = newlayer->allFeatureIds();

        // Write non-selected feature ids
        QgsFeatureList features;
        QgsFeatureIterator it = layer->getFeatures();
        while ( it.nextFeature( feature ) )
        {
          if ( !layer->selectedFeatureIds().contains( feature.id() ) )
          {
            features.append( feature );
          }
        }
        newlayer->dataProvider()->addFeatures( features );

        // Set selected features
        newlayer->selectByIds( selectedFeatures );
      }
      processLayers.append( newlayer );
    }

    //  Remove layers from project
    if ( !toRemove.isEmpty() )
    {
      QgsProject::instance()->removeMapLayers( toRemove );
    }

    // Error if an output layer could not be created
    if ( !createErrors.isEmpty() )
    {
      QMessageBox::critical( this, tr( "Check Geometries" ), tr( "Failed to create one or more output layers:\n%1" ).arg( createErrors.join( "\n" ) ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
  }
  else
  {
    processLayers = layers;
  }

  // Check if output layers are editable
  QList<QgsVectorLayer *> nonEditableLayers;
  for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) )
  {
    if ( ( layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 )
    {
      nonEditableLayers.append( layer );
    }
  }
  if ( !nonEditableLayers.isEmpty() )
  {
    QStringList nonEditableLayerNames;
    for ( QgsVectorLayer *layer : nonEditableLayers )
    {
      nonEditableLayerNames.append( layer->name() );
    }
    if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Check Geometries" ), tr( "The following output layers are in a format that does not support editing features:\n%1\n\nThe geometry check can be performed, but it will not be possible to fix any errors. Do you want to continue?" ).arg( nonEditableLayerNames.join( "\n" ) ), QMessageBox::Yes, QMessageBox::No ) )
    {
      if ( ui.radioButtonOutputNew->isChecked() )
      {
        for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) )
        {
          QString layerPath = layer->dataProvider()->dataSourceUri();
          delete layer;
          if ( ui.comboBoxOutputFormat->currentText() == QLatin1String( "ESRI Shapefile" ) )
          {
            QgsVectorFileWriter::deleteShapeFile( layerPath );
          }
          else
          {
            QFile( layerPath ).remove();
          }
        }
        mRunButton->setEnabled( true );
        ui.labelStatus->hide();
        unsetCursor();
      }
      return;
    }
  }

  // Setup checker
  ui.labelStatus->setText( tr( "<b>Building spatial index...</b>" ) );
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
  QMap<QString, QgsFeaturePool *> featurePools;
  for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) )
  {
    double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer );
    QgsCoordinateTransform layerToMapTransform( layer->crs(), QgsProject::instance()->crs(), QgsProject::instance() );
    featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) );
  }
  // LineLayerIntersection check is enabled, make sure there is also a feature pool for that layer
  if ( ui.checkLineLayerIntersection->isChecked() && !featurePools.keys().contains( ui.comboLineLayerIntersection->currentData().toString() ) )
  {
    QgsVectorLayer *layer = dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) );
    Q_ASSERT( layer );
    double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer );
    QgsCoordinateTransform layerToMapTransform( layer->crs(), QgsProject::instance()->crs(), QgsProject::instance() );
    featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) );
  }

  QgsGeometryCheckerContext *context = new QgsGeometryCheckerContext( ui.spinBoxTolerance->value(), QgsProject::instance()->crs(), featurePools );

  QList<QgsGeometryCheck *> checks;
  for ( const QgsGeometryCheckFactory *factory : QgsGeometryCheckFactoryRegistry::getCheckFactories() )
  {
    QgsGeometryCheck *check = factory->createInstance( context, ui );
    if ( check )
    {
      checks.append( check );
    }
  }
  QgsGeometryChecker *checker = new QgsGeometryChecker( checks, context );

  emit checkerStarted( checker );

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    QList<QgsMapLayer *> addLayers;
    for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) )
    {
      addLayers.append( layer );
    }
    QgsProject::instance()->addMapLayers( addLayers );
  }

  // Run
  ui.buttonBox->addButton( mAbortButton, QDialogButtonBox::ActionRole );
  mRunButton->hide();
  ui.progressBar->setRange( 0, 0 );
  ui.labelStatus->hide();
  ui.progressBar->show();
  ui.widgetInputs->setEnabled( false );
  QEventLoop evLoop;
  QFutureWatcher<void> futureWatcher;
  connect( checker, &QgsGeometryChecker::progressValue, ui.progressBar, &QProgressBar::setValue );
  connect( &futureWatcher, &QFutureWatcherBase::finished, &evLoop, &QEventLoop::quit );
  connect( mAbortButton, &QAbstractButton::clicked, &futureWatcher, &QFutureWatcherBase::cancel );
  connect( mAbortButton, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::showCancelFeedback );

  mIsRunningInBackground = true;

  int maxSteps = 0;
  futureWatcher.setFuture( checker->execute( &maxSteps ) );
  ui.progressBar->setRange( 0, maxSteps );
  evLoop.exec();

  mIsRunningInBackground = false;

  // Restore window
  unsetCursor();
  mAbortButton->setEnabled( true );
  ui.buttonBox->removeButton( mAbortButton );
  mRunButton->setEnabled( true );
  mRunButton->show();
  ui.progressBar->hide();
  ui.labelStatus->hide();
  ui.widgetInputs->setEnabled( true );

  // Show result
  emit checkerFinished( !futureWatcher.isCanceled() );
}
Ejemplo n.º 13
0
QMap<QString, QSharedPointer<DeviceState> > MusicScene::getDeviceState()
{
    QMap<QString, QSharedPointer<DeviceState> > ret;
    ret.insert(player.getDeviceId(),player.createEmptyState());
    return ret;
}
Ejemplo n.º 14
0
QMap<QString, QString> CSSCustomDialog::cssDict()
{
    QMap<QString, QString> dict;

    // Fontsizes ------------------------------------------------------

    int bfs = basefontsize->currentText().toInt();
    dict.insert(QStringLiteral("fontsize-base"), px(bfs, 1.0));

    if (dontScale->isChecked()) {
        dict.insert(QStringLiteral("fontsize-small-1"), px(bfs, 1.0));
        dict.insert(QStringLiteral("fontsize-large-1"), px(bfs, 1.0));
        dict.insert(QStringLiteral("fontsize-large-2"), px(bfs, 1.0));
        dict.insert(QStringLiteral("fontsize-large-3"), px(bfs, 1.0));
        dict.insert(QStringLiteral("fontsize-large-4"), px(bfs, 1.0));
        dict.insert(QStringLiteral("fontsize-large-5"), px(bfs, 1.0));
    } else {
        // TODO: use something harmonic here
        dict.insert(QStringLiteral("fontsize-small-1"), px(bfs, 0.8));
        dict.insert(QStringLiteral("fontsize-large-1"), px(bfs, 1.2));
        dict.insert(QStringLiteral("fontsize-large-2"), px(bfs, 1.4));
        dict.insert(QStringLiteral("fontsize-large-3"), px(bfs, 1.5));
        dict.insert(QStringLiteral("fontsize-large-4"), px(bfs, 1.6));
        dict.insert(QStringLiteral("fontsize-large-5"), px(bfs, 1.8));
    }

    // Colors --------------------------------------------------------

    if (customColor->isChecked()) {
        dict.insert(QStringLiteral("background-color"), backgroundColorButton->color().name());
        dict.insert(QStringLiteral("foreground-color"), foregroundColorButton->color().name());
    } else {
        const char *blackOnWhiteFG[2] = {"White", "Black"};
        bool bw = blackOnWhite->isChecked();
        dict.insert(QStringLiteral("foreground-color"), QLatin1String(blackOnWhiteFG[bw]));
        dict.insert(QStringLiteral("background-color"), QLatin1String(blackOnWhiteFG[!bw]));
    }

    const char *notImportant[2] = {"", "! important"};
    dict.insert(QStringLiteral("force-color"), QLatin1String(notImportant[sameColor->isChecked()]));

    // Fonts -------------------------------------------------------------
    dict.insert(QStringLiteral("font-family"), fontFamily->currentText());
    dict.insert(QStringLiteral("force-font"), QLatin1String(notImportant[sameFamily->isChecked()]));

    // Images

    const char *bgNoneImportant[2] = {"", "background-image : none ! important"};
    dict.insert(QStringLiteral("display-images"), QLatin1String(bgNoneImportant[hideImages->isChecked()]));
    dict.insert(QStringLiteral("display-background"), QLatin1String(bgNoneImportant[hideBackground->isChecked()]));

    return dict;
}
/*!
  Parses the MIME header \a header and returns the map of those headers.
  This function is for internal use only.
*/
QMap<QByteArray, QByteArray> TMimeHeader::parseHeaderParameter(const QByteArray &header)
{
    QMap<QByteArray, QByteArray> result;
    int pos = 0;

    for (;;) {
        pos = skipWhitespace(header, pos);
        if (pos >= header.length())
            return result;

        int semicol = header.indexOf(';', pos);
        if (semicol < 0)
            semicol = header.length();

        QByteArray key;
        int equal = header.indexOf('=', pos);
        if (equal < 0 || equal > semicol) {
            key = header.mid(pos, semicol - pos).trimmed();
            if (!key.isEmpty()) {
                result.insert(key, QByteArray());
            }
            pos = semicol + 1;
            continue;
        }

        key = header.mid(pos,  equal - pos).trimmed();
        pos = equal + 1;

        pos = skipWhitespace(header, pos);
        if (pos >= header.length())
            return result;

        QByteArray value;
        if (header[pos] == '"') {
            ++pos;
            while (pos < header.length()) {
                char c = header.at(pos);
                if (c == '"') {
                    // end of quoted text
                    break;
                } else if (c == '\\') {
                    ++pos;
                    if (pos >= header.length()) {
                        // broken header
                        return result;
                    }
                    c = header[pos];
                }

                value += c;
                ++pos;
            }
        } else {
            while (pos < header.length()) {
                char c = header.at(pos);
                if (c == ' ' || c == '\t' || c == '\r'
                    || c == '\n' || c == ';') {
                    break;
                }
                value += c;
                ++pos;
            }
        }

        result.insert(key, value);
    }
    return result;
}
Ejemplo n.º 16
0
void OpenModelica::setInputVariablesXml(QDomDocument & doc, QString modelName, MOVector<Variable> *variables)
{
    QDomElement xfmi = doc.firstChildElement("fmiModelDescription");
    QDomElement oldxfmi = xfmi;

    QDomElement xModelVars = xfmi.firstChildElement("ModelVariables");
    QDomElement oldxModelVars = xModelVars;

    QDomNodeList listScalarVars = xModelVars.elementsByTagName("ScalarVariable");


    // filling map
    QMap<QString,int> mapScalarVars; //<name,index in listScalarVars>
    QMap<QDomElement,QDomElement> mapNewScalarVars; // <old node,new node>
    QDomElement curVar;
    QDomElement oldVar;
    QDomElement newVar;
    int index;
    QDomElement oldType;
    QDomElement newType;
    QString localVarName;

    // create map for index looking
    for(int i=0;i<listScalarVars.size();i++)
    {
        curVar = listScalarVars.at(i).toElement();
        mapScalarVars.insert(curVar.attribute("name"),i);
    }

    // change variables values
    for(int i=0;i<variables->size();i++)
    {
        // getting local var name (name in init file does not contain model name)
        localVarName = variables->at(i)->name(Variable::SHORT);
        //localVarName = localVarName.remove(modelName+".");

        index = mapScalarVars.value(localVarName,-1);
        if(index>-1)
        {
            oldVar = listScalarVars.at(index).toElement();
            newVar = oldVar;

            oldType = newVar.firstChildElement("Real");
            if(oldType.isNull())
                oldType = newVar.firstChildElement("Integer");
            if(oldType.isNull())
                oldType = newVar.firstChildElement("Boolean");

            if(!oldType.isNull())
            {
                newType = oldType;
                newType.setAttribute("start",variables->at(i)->value().toString());
                newVar.replaceChild(newType,oldType);
                xModelVars.replaceChild(newVar,oldVar);
            }
            xModelVars.replaceChild(newVar,oldVar);
        }
    }

    // update xfmi with new vars
    xfmi.replaceChild(xModelVars,oldxModelVars);
    doc.replaceChild(xfmi,oldxfmi);
}
Ejemplo n.º 17
0
bool KstChangeFileDialogI::applyFileChange() {
  KstDataSourcePtr file;
  KST::dataSourceList.lock().writeLock();
  KstDataSourceList::Iterator it = KST::dataSourceList.findReusableFileName(_dataFile->url().url());
  QString invalidSources;
  int invalid = 0;

  if (it == KST::dataSourceList.end()) {
    file = KstDataSource::loadSource(_dataFile->url().url());
    if (!file || !file->isValid()) {
      KST::dataSourceList.lock().unlock();
      KMessageBox::sorry(this, i18n("The file could not be loaded."));
      return false;
    }
    if (file->isEmpty()) {
      KST::dataSourceList.lock().unlock();
      KMessageBox::sorry(this, i18n("The file does not contain data."));
      return false;
    }
    KST::dataSourceList.append(file);
  } else {
    file = *it;
  }
  KST::dataSourceList.lock().unlock();

  KstApp *app = KstApp::inst();
  KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList);
  KstRMatrixList rml = kstObjectSubList<KstMatrix,KstRMatrix>(KST::matrixList);
  int selected = 0;
  int handled = 0;

  int count = (int)ChangeFileCurveList->count();
  for (int i = 0; i < count; i++) {
    if (ChangeFileCurveList->isSelected(i)) {
      ++selected;
    }
  }

  // a map to keep track of which objects have been duplicated, and mapping
  // old object -> new object
  KstDataObjectDataObjectMap duplicatedMap;
  QMap<KstVectorPtr, KstVectorPtr> duplicatedVectors;
  QMap<KstMatrixPtr, KstMatrixPtr> duplicatedMatrices;

  KstDataSourceList oldSources;
  
  // go through the vectors
  for (int i = 0; i < (int)rvl.count(); i++) {
    if (ChangeFileCurveList->isSelected(i)) {
      KstRVectorPtr vector = rvl[i];
      vector->writeLock();
      file->readLock();
      bool valid = file->isValidField(vector->field());
      file->unlock();
      if (!valid) {
        if (invalid > 0) {
          // FIXME: invalid list construction for i18n
          invalidSources = i18n("%1, %2").arg(invalidSources).arg(vector->field());
        } else {
          invalidSources = vector->field();
        }
        ++invalid;
      } else {
        if (_duplicateSelected->isChecked()) {
          // block vector updates until vector is setup properly
          KST::vectorList.lock().writeLock();

          // create a new vector
          KstRVectorPtr newVector = vector->makeDuplicate();
          if (!oldSources.contains(newVector->dataSource())) {
            oldSources << newVector->dataSource();
          }
          newVector->changeFile(file);

          KST::vectorList.lock().unlock();

          // duplicate dependents
          if (_duplicateDependents->isChecked()) {
            duplicatedVectors.insert(KstVectorPtr(vector), KstVectorPtr(newVector));
            KST::duplicateDependents(KstVectorPtr(vector), duplicatedMap, duplicatedVectors);
          }
        } else {
          if (!oldSources.contains(vector->dataSource())) {
            oldSources << vector->dataSource();
          }
          vector->changeFile(file);
        }
      }
      vector->unlock();
      app->slotUpdateProgress(selected, ++handled, i18n("Updating vectors..."));
    }
  }
  
  // go through the matrices
  for (int i = (int)rvl.count(); i < (int)ChangeFileCurveList->count(); i++) {
    if (ChangeFileCurveList->isSelected(i)) {
      KstRMatrixPtr matrix = rml[i-rvl.count()];
      matrix->writeLock();
      file->readLock();
      bool valid = file->isValidMatrix(matrix->field());
      file->unlock();
      if (!valid) {
        if (invalid > 0) {
          // FIXME: invalid list construction for i18n
          invalidSources = i18n("%1, %2").arg(invalidSources).arg(matrix->field());
        } else {
          invalidSources = matrix->field();
        }
        ++invalid;
      } else {
        if (_duplicateSelected->isChecked()) {
          // block matrix updates until matrix is setup properly
          KST::matrixList.lock().writeLock();

          // create a new matrix
          KstRMatrixPtr newMatrix = matrix->makeDuplicate();
          if (!oldSources.contains(newMatrix->dataSource())) {
            oldSources << newMatrix->dataSource();
          }
          newMatrix->changeFile(file);

          KST::matrixList.lock().unlock();

          // duplicate dependents
          if (_duplicateDependents->isChecked()) {
            duplicatedMatrices.insert(KstMatrixPtr(matrix), KstMatrixPtr(newMatrix));
            KST::duplicateDependents(KstMatrixPtr(matrix), duplicatedMap, duplicatedMatrices);
          }
        } else {
          if (!oldSources.contains(matrix->dataSource())) {
            oldSources << matrix->dataSource();
          }
          matrix->changeFile(file);
        }
      }
      matrix->unlock();
      app->slotUpdateProgress(selected, ++handled, i18n("Updating matrices..."));
    }
  }

  app->slotUpdateProgress(0, 0, QString::null);
  file = 0L;
  
  // now add any curves and images to plots if they were duplicated
  if (_duplicateSelected->isChecked() && _duplicateDependents->isChecked()) { 
    KstApp *app = KstApp::inst();
    QList<KMdiChildView*> childViews = app->childViews();
    QListIterator<KMdiChildView*> it(childViews);
    while (it.hasNext()) {
      KstViewWindow *w = dynamic_cast<KstViewWindow*>(it.next());
      if (w) {
        KstTopLevelViewPtr view = kst_cast<KstTopLevelView>(w->view());
        if (view) {
          Kst2DPlotList plots = view->findChildrenType<Kst2DPlot>(true);
          for (Kst2DPlotList::Iterator plotIter = plots.begin(); plotIter != plots.end(); ++plotIter) {
            for (KstDataObjectDataObjectMap::ConstIterator iter = duplicatedMap.begin(); iter != duplicatedMap.end(); ++iter) {
              if (KstBaseCurvePtr curve = kst_cast<KstBaseCurve>(iter.value())) {
                if ((*plotIter)->Curves.contains(kst_cast<KstBaseCurve>(iter.key())) && !(*plotIter)->Curves.contains(kst_cast<KstBaseCurve>(curve))) {
                  (*plotIter)->addCurve(curve);
                }
              }
            }
          }
        }
      }
      it.next();
    }
  }

  // clean up unused data sources
//  qDebug() << "cleaning up data sources" << endl;
  KST::dataSourceList.lock().writeLock();
  for (KstDataSourceList::Iterator it = oldSources.begin(); it != oldSources.end(); ++it) {
//    qDebug() << "DATA SOURCE: " << (*it)->tag().displayString() << " (" << (void*)(*it) << ") USAGE: " << (*it)->getUsage() << endl;
    if ((*it)->getUsage() == 1) {
//      qDebug() << "    -> REMOVED" << endl;
      KST::dataSourceList.remove((*it).data());
    }
  }
  KST::dataSourceList.lock().unlock();
  
  if (!invalidSources.isEmpty()) {
    if (invalid == 1) {
      KMessageBox::sorry(this, i18n("The following field is not defined for the requested file:\n%1").arg(invalidSources));
    } else {
      KMessageBox::sorry(this, i18n("The following fields are not defined for the requested file:\n%1").arg(invalidSources));
    }
  }

  emit docChanged();

  // force an update in case we're in paused mode
  KstApp::inst()->forceUpdate();
  return true;
}
Ejemplo n.º 18
0
TabRoom::TabRoom(TabSupervisor *_tabSupervisor, AbstractClient *_client, ServerInfo_User *_ownUser, const ServerInfo_Room &info)
    : Tab(_tabSupervisor), client(_client), roomId(info.room_id()), roomName(QString::fromStdString(info.name())), ownUser(_ownUser)
{
    const int gameTypeListSize = info.gametype_list_size();
    for (int i = 0; i < gameTypeListSize; ++i)
        gameTypes.insert(info.gametype_list(i).game_type_id(), QString::fromStdString(info.gametype_list(i).description()));

    QMap<int, GameTypeMap> tempMap;
    tempMap.insert(info.room_id(), gameTypes);
    gameSelector = new GameSelector(client, tabSupervisor, this, QMap<int, QString>(), tempMap, true, true);
    userList = new UserList(tabSupervisor, client, UserList::RoomList);
    connect(userList, SIGNAL(openMessageDialog(const QString &, bool)), this, SIGNAL(openMessageDialog(const QString &, bool)));

    chatView = new ChatView(tabSupervisor, 0, true);
    connect(chatView, SIGNAL(showMentionPopup(QString&)), this, SLOT(actShowMentionPopup(QString&)));
    connect(chatView, SIGNAL(messageClickedSignal()), this, SLOT(focusTab()));
    connect(chatView, SIGNAL(openMessageDialog(QString, bool)), this, SIGNAL(openMessageDialog(QString, bool)));
    connect(chatView, SIGNAL(showCardInfoPopup(QPoint, QString)), this, SLOT(showCardInfoPopup(QPoint, QString)));
    connect(chatView, SIGNAL(deleteCardInfoPopup(QString)), this, SLOT(deleteCardInfoPopup(QString)));
    connect(chatView, SIGNAL(addMentionTag(QString)), this, SLOT(addMentionTag(QString)));
    sayLabel = new QLabel;
    sayEdit = new QLineEdit;
    sayLabel->setBuddy(sayEdit);
    connect(sayEdit, SIGNAL(returnPressed()), this, SLOT(sendMessage()));

    QMenu *chatSettingsMenu = new QMenu(this);

    aClearChat = chatSettingsMenu->addAction(QString());
    aClearChat->setShortcut(QKeySequence("F12"));
    connect(aClearChat, SIGNAL(triggered()), this, SLOT(actClearChat()));

    chatSettingsMenu->addSeparator();

    aOpenChatSettings = chatSettingsMenu->addAction(QString());
    connect(aOpenChatSettings, SIGNAL(triggered()), this, SLOT(actOpenChatSettings()));

    QToolButton *chatSettingsButton = new QToolButton;
    chatSettingsButton->setIcon(QIcon(":/resources/icon_settings.svg"));
    chatSettingsButton->setMenu(chatSettingsMenu);
    chatSettingsButton->setPopupMode(QToolButton::InstantPopup);

    QHBoxLayout *sayHbox = new QHBoxLayout;
    sayHbox->addWidget(sayLabel);
    sayHbox->addWidget(sayEdit);
    sayHbox->addWidget(chatSettingsButton);

    QVBoxLayout *chatVbox = new QVBoxLayout;
    chatVbox->addWidget(chatView);
    chatVbox->addLayout(sayHbox);

    chatGroupBox = new QGroupBox;
    chatGroupBox->setLayout(chatVbox);

    QSplitter *splitter = new QSplitter(Qt::Vertical);
    splitter->addWidget(gameSelector);
    splitter->addWidget(chatGroupBox);

    QHBoxLayout *hbox = new QHBoxLayout;
    hbox->addWidget(splitter, 3);
    hbox->addWidget(userList, 1);

    aLeaveRoom = new QAction(this);
    connect(aLeaveRoom, SIGNAL(triggered()), this, SLOT(actLeaveRoom()));

    roomMenu = new QMenu(this);
    roomMenu->addAction(aLeaveRoom);
    addTabMenu(roomMenu);

    retranslateUi();
    setLayout(hbox);

    const int userListSize = info.user_list_size();
    for (int i = 0; i < userListSize; ++i)
        userList->processUserInfo(info.user_list(i), true);
    userList->sortItems();

    const int gameListSize = info.game_list_size();
    for (int i = 0; i < gameListSize; ++i)
        gameSelector->processGameInfo(info.game_list(i));
}
Ejemplo n.º 19
0
void QgsSearchQueryBuilder::loadQuery()
{
  QSettings s;
  QString lastQueryFileDir = s.value( "/UI/lastQueryFileDir", "" ).toString();

  QString queryFileName = QFileDialog::getOpenFileName( 0, tr( "Load query from file" ), lastQueryFileDir, tr( "Query files" ) + "(*.qqf);;" + tr( "All files" ) + "(*)" );
  if ( queryFileName.isNull() )
  {
    return;
  }

  QFile queryFile( queryFileName );
  if ( !queryFile.open( QIODevice::ReadOnly ) )
  {
    QMessageBox::critical( 0, tr( "Error" ), tr( "Could not open file for reading" ) );
    return;
  }
  QDomDocument queryDoc;
  if ( !queryDoc.setContent( &queryFile ) )
  {
    QMessageBox::critical( 0, tr( "Error" ), tr( "File is not a valid xml document" ) );
    return;
  }

  QDomElement queryElem = queryDoc.firstChildElement( "Query" );
  if ( queryElem.isNull() )
  {
    QMessageBox::critical( 0, tr( "Error" ), tr( "File is not a valid query document" ) );
    return;
  }

  QString query = queryElem.text();

  //todo: test if all the attributes are valid
  QgsSearchString search;
  if ( !search.setString( query ) )
  {
    QMessageBox::critical( this, tr( "Search string parsing error" ), search.parserErrorMsg() );
    return;
  }

  QgsSearchTreeNode* searchTree = search.tree();
  if ( !searchTree )
  {
    QMessageBox::critical( this, tr( "Error creating search tree" ), search.parserErrorMsg() );
    return;
  }

  QStringList attributes = searchTree->referencedColumns();
  QMap< QString, QString> attributesToReplace;
  QStringList existingAttributes;

  //get all existing fields
  QMap<QString, int>::const_iterator fieldIt = mFieldMap.constBegin();
  for ( ; fieldIt != mFieldMap.constEnd(); ++fieldIt )
  {
    existingAttributes.push_back( fieldIt.key() );
  }

  //if a field does not exist, ask what field should be used instead
  QStringList::const_iterator attIt = attributes.constBegin();
  for ( ; attIt != attributes.constEnd(); ++attIt )
  {
    //test if attribute is there
    if ( !mFieldMap.contains( *attIt ) )
    {
      bool ok;
      QString replaceAttribute = QInputDialog::getItem( 0, tr( "Select attribute" ), tr( "There is no attribute '%1' in the current vector layer. Please select an existing attribute" ).arg( *attIt ),
                                 existingAttributes, 0, false, &ok );
      if ( !ok || replaceAttribute.isEmpty() )
      {
        return;
      }
      attributesToReplace.insert( *attIt, replaceAttribute );
    }
  }

  //Now replace all the string in the query
  QList<QgsSearchTreeNode*> columnRefList = searchTree->columnRefNodes();
  QList<QgsSearchTreeNode*>::iterator columnIt = columnRefList.begin();
  for ( ; columnIt != columnRefList.end(); ++columnIt )
  {
    QMap< QString, QString>::const_iterator replaceIt = attributesToReplace.find(( *columnIt )->columnRef() );
    if ( replaceIt != attributesToReplace.constEnd() )
    {
      ( *columnIt )->setColumnRef( replaceIt.value() );
    }
  }

  txtSQL->clear();
  QString newQueryText = query;
  if ( attributesToReplace.size() > 0 )
  {
    newQueryText = searchTree->makeSearchString();
  }
  txtSQL->insertPlainText( newQueryText );
}
Ejemplo n.º 20
0
void QNPutExtraPrivate::insert(const QString &key, const QString &value)
{
    m_params.insert(key, value);
}
Ejemplo n.º 21
0
void TimeoutsTest::identityTimeout()
{
    QEventLoop loop;
    QTimer::singleShot(test_timeout, &loop, SLOT(quit()));
    QObject::connect(this, SIGNAL(finished()), &loop, SLOT(quit()));

    QMap<MethodName,MechanismsList> methods;
    methods.insert("dummy", QStringList() << "mech1" << "mech2");
    IdentityInfo info = IdentityInfo(QLatin1String("timeout test"),
                                     QLatin1String("timeout@test"),
                                     methods);
    info.setAccessControlList(QStringList() << "*");
    Identity *identity = Identity::newIdentity(info);
    QVERIFY(identity != NULL);

    QObject::connect(identity,
                     SIGNAL(credentialsStored(const quint32)),
                     this,
                     SLOT(credentialsStored(const quint32)));
    QObject::connect(identity,
                     SIGNAL(error(const SignOn::Error&)),
                     this,
                     SLOT(identityError(const SignOn::Error&)));

    identity->storeCredentials();

    loop.exec();
    QVERIFY(identity->id() != SSO_NEW_IDENTITY);

    QDBusConnection conn = SIGNOND_BUS;

    QDBusMessage msg = QDBusMessage::createMethodCall(SIGNOND_SERVICE,
                                                      SIGNOND_DAEMON_OBJECTPATH,
                                                      SIGNOND_DAEMON_INTERFACE,
                                                      "getIdentity");
    QList<QVariant> args;
    args << identity->id();
    msg.setArguments(args);

    QDBusMessage reply = conn.call(msg);
    QCOMPARE(reply.type(), QDBusMessage::ReplyMessage);

    QDBusObjectPath objectPath = reply.arguments()[0].value<QDBusObjectPath>();
    QString path = objectPath.path();
    qDebug() << "Got path" << path;
    QVERIFY(!path.isEmpty());

    bool success;

    QTest::qSleep(100);
    success = triggerDisposableCleanup();
    QVERIFY(success);

    /* The identity object must exist now */
    QVERIFY(identityAlive(path));

    QTest::qSleep(6 * 1000);
    success = triggerDisposableCleanup();
    QVERIFY(success);

    /* After SSO_IDENTITY_TIMEOUT seconds, the identity must have been
     * destroyed */
    QVERIFY(!identityAlive(path));

    /* Calling a method on the client should re-register the identity */
    QSignalSpy removed(identity, SIGNAL(removed()));
    QObject::connect(identity, SIGNAL(removed()),
                     &loop, SLOT(quit()), Qt::QueuedConnection);
    identity->remove();
    loop.exec();

    QCOMPARE(removed.count(), 1);
}
Ejemplo n.º 22
0
bool QgsMapToolFeatureAction::doAction( QgsVectorLayer *layer, int x, int y )
{
  if ( !layer )
    return false;

  QgsPoint point = mCanvas->getCoordinateTransform()->toMapCoordinates( x, y );

  QgsFeatureList featList;

  // toLayerCoordinates will throw an exception for an 'invalid' point.
  // For example, if you project a world map onto a globe using EPSG 2163
  // and then click somewhere off the globe, an exception will be thrown.
  try
  {
    // create the search rectangle
    double searchRadius = searchRadiusMU( mCanvas );

    QgsRectangle r;
    r.setXMinimum( point.x() - searchRadius );
    r.setXMaximum( point.x() + searchRadius );
    r.setYMinimum( point.y() - searchRadius );
    r.setYMaximum( point.y() + searchRadius );

    r = toLayerCoordinates( layer, r );

    QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest().setFilterRect( r ).setFlags( QgsFeatureRequest::ExactIntersect ) );
    QgsFeature f;
    while ( fit.nextFeature( f ) )
      featList << QgsFeature( f );
  }
  catch ( QgsCsException & cse )
  {
    Q_UNUSED( cse );
    // catch exception for 'invalid' point and proceed with no features found
    QgsDebugMsg( QString( "Caught CRS exception %1" ).arg( cse.what() ) );
  }

  if ( featList.size() == 0 )
    return false;

  Q_FOREACH ( const QgsFeature& feat, featList )
  {
    if ( layer->actions()->defaultAction() >= 0 )
    {
      // define custom substitutions: layer id and clicked coords
      QMap<QString, QVariant> substitutionMap;
      substitutionMap.insert( "$layerid", layer->id() );
      point = toLayerCoordinates( layer, point );
      substitutionMap.insert( "$clickx", point.x() );
      substitutionMap.insert( "$clicky", point.y() );

      int actionIdx = layer->actions()->defaultAction();
      layer->actions()->doAction( actionIdx, feat, &substitutionMap );
    }
    else
    {
      QgsMapLayerAction* mapLayerAction = QgsMapLayerActionRegistry::instance()->defaultActionForLayer( layer );
      if ( mapLayerAction )
      {
        mapLayerAction->triggerForFeature( layer, &feat );
      }
    }
  }

  return true;
}
Ejemplo n.º 23
0
/*!
	\brief Fills a settings map from the state of the subcontrols
*/
QMap<QString, QVariant> QEditConfig::dumpKeys() const
{
    QMap<QString, QVariant> m;

    QFont font = ui->cbFont->currentFont();
    font.setPointSize(ui->spnFontSize->value());

    m.insert("font", font);
    m.insert("tab_width", ui->spnTabWidth->value());

    m.insert("show_leading_whitespace", ui->chkShowLeadingWhitespace->isChecked());
    m.insert("show_trailing_whitespace", ui->chkShowTrailingWhitespace->isChecked());
    m.insert("show_tabs_in_text", ui->chkShowTabsInText->isChecked());

    m.insert("replace_tabs", ui->chkReplaceTabs->isChecked());
    m.insert("remove_trailing", ui->chkAutoRemoveTrailingWhitespace->isChecked());
    m.insert("preserve_trailing_indent", ui->chkPreserveTrailingIndent->isChecked());

    m.insert("encoding", ui->cbEncoding->currentText());

    if ( ui->chkDetectLE->isChecked() )
        m.insert("line_endings", (int)QDocument::Conservative);
    else
        m.insert("line_endings", ui->cbLineEndings->currentIndex() + 1);

    return m;
}
Ejemplo n.º 24
0
void HistogramBox::setHistogramType(HistogramBoxType type)
{
    // all possible channels for histogram widget are defined in this map
    QMap<int, QPair<QString, QString> > channelDescMap;

    // this string will contain the WhatsThis message for the channelCB
    QString channelCBDescr(i18n("<p>Select the histogram channel to display:</p>"));

    // those pairs hold the combobox text and WhatsThis description for each channel item
    typedef QPair<QString, QString> ChannelPair;

    ChannelPair luminosityPair(i18nc("The luminosity channel", "Luminosity"), i18n(
                                   "<b>Luminosity</b>: display the image's luminosity values."));

    ChannelPair redPair(i18nc("The red channel", "Red"), i18n(
                            "<b>Red</b>: display the red image-channel values."));

    ChannelPair greenPair(i18nc("The green channel", "Green"), i18n(
                              "<b>Green</b>: display the green image-channel values."));

    ChannelPair bluePair(i18nc("The blue channel", "Blue"), i18n(
                             "<b>Blue</b>: display the blue image-channel values."));

    ChannelPair colorsPair(i18nc("The colors channel", "Colors"), i18n(
                               "<b>Colors</b>: Display all color channel values at the same time."));

    ChannelPair alphaPair(i18nc("The alpha channel", "Alpha"), i18n(
                              "<b>Alpha</b>: display the alpha image-channel values. "
                              "This channel corresponds to the transparency value and "
                              "is supported by some image formats, such as PNG or TIF."));

    channelDescMap.insert(LuminosityChannel, luminosityPair);
    channelDescMap.insert(RedChannel, redPair);
    channelDescMap.insert(GreenChannel, greenPair);
    channelDescMap.insert(BlueChannel, bluePair);
    channelDescMap.insert(ColorChannels, colorsPair);
    channelDescMap.insert(AlphaChannel, alphaPair);

    switch (type)
    {
        case RGB:
            d->channelCB->clear();
            d->channelCB->addItem(channelDescMap[RedChannel].first, QVariant(RedChannel));
            d->channelCB->addItem(channelDescMap[GreenChannel].first, QVariant(GreenChannel));
            d->channelCB->addItem(channelDescMap[BlueChannel].first, QVariant(BlueChannel));
            channelCBDescr.append("<p>");
            channelCBDescr.append(channelDescMap[RedChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[GreenChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[BlueChannel].second);
            channelCBDescr.append("</p>");
            break;

        case RGBA:
            d->channelCB->clear();
            d->channelCB->addItem(channelDescMap[RedChannel].first, QVariant(RedChannel));
            d->channelCB->addItem(channelDescMap[GreenChannel].first, QVariant(GreenChannel));
            d->channelCB->addItem(channelDescMap[BlueChannel].first, QVariant(BlueChannel));
            d->channelCB->addItem(channelDescMap[AlphaChannel].first, QVariant(AlphaChannel));
            channelCBDescr.append("<p>");
            channelCBDescr.append(channelDescMap[RedChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[GreenChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[BlueChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[AlphaChannel].second);
            channelCBDescr.append("</p>");
            break;

        case LRGB:
            d->channelCB->clear();
            d->channelCB->addItem(channelDescMap[LuminosityChannel].first, QVariant(LuminosityChannel));
            d->channelCB->addItem(channelDescMap[RedChannel].first, QVariant(RedChannel));
            d->channelCB->addItem(channelDescMap[GreenChannel].first, QVariant(GreenChannel));
            d->channelCB->addItem(channelDescMap[BlueChannel].first, QVariant(BlueChannel));
            channelCBDescr.append("<p>");
            channelCBDescr.append(channelDescMap[LuminosityChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[RedChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[GreenChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[BlueChannel].second);
            channelCBDescr.append("</p>");
            break;

        case LRGBA:
            d->channelCB->clear();
            d->channelCB->addItem(channelDescMap[LuminosityChannel].first, QVariant(LuminosityChannel));
            d->channelCB->addItem(channelDescMap[RedChannel].first, QVariant(RedChannel));
            d->channelCB->addItem(channelDescMap[GreenChannel].first, QVariant(GreenChannel));
            d->channelCB->addItem(channelDescMap[BlueChannel].first, QVariant(BlueChannel));
            d->channelCB->addItem(channelDescMap[AlphaChannel].first, QVariant(AlphaChannel));
            channelCBDescr.append("<p>");
            channelCBDescr.append(channelDescMap[LuminosityChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[RedChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[GreenChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[BlueChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[AlphaChannel].second);
            channelCBDescr.append("</p>");
            break;

        case LRGBC:
            d->channelCB->clear();
            d->channelCB->addItem(channelDescMap[LuminosityChannel].first, QVariant(LuminosityChannel));
            d->channelCB->addItem(channelDescMap[RedChannel].first, QVariant(RedChannel));
            d->channelCB->addItem(channelDescMap[GreenChannel].first, QVariant(GreenChannel));
            d->channelCB->addItem(channelDescMap[BlueChannel].first, QVariant(BlueChannel));
            d->channelCB->addItem(channelDescMap[ColorChannels].first, QVariant(ColorChannels));
            channelCBDescr.append("<p>");
            channelCBDescr.append(channelDescMap[LuminosityChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[RedChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[GreenChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[BlueChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[ColorChannels].second);
            channelCBDescr.append("</p>");
            break;

        case LRGBAC:
            d->channelCB->clear();
            d->channelCB->addItem(channelDescMap[LuminosityChannel].first, QVariant(LuminosityChannel));
            d->channelCB->addItem(channelDescMap[RedChannel].first, QVariant(RedChannel));
            d->channelCB->addItem(channelDescMap[GreenChannel].first, QVariant(GreenChannel));
            d->channelCB->addItem(channelDescMap[BlueChannel].first, QVariant(BlueChannel));
            d->channelCB->addItem(channelDescMap[AlphaChannel].first, QVariant(AlphaChannel));
            d->channelCB->addItem(channelDescMap[ColorChannels].first, QVariant(ColorChannels));
            channelCBDescr.append("<p>");
            channelCBDescr.append(channelDescMap[LuminosityChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[RedChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[GreenChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[BlueChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[AlphaChannel].second).append("<br/>");
            channelCBDescr.append(channelDescMap[ColorChannels].second);
            channelCBDescr.append("</p>");
            break;

        default:
            break;
    }

    d->channelCB->setWhatsThis(channelCBDescr);
}
Ejemplo n.º 25
0
int QgsRasterCalculator::processCalculation( QProgressDialog* p )
{
  //prepare search string / tree
  QString errorString;
  QgsRasterCalcNode* calcNode = QgsRasterCalcNode::parseRasterCalcString( mFormulaString, errorString );
  if ( !calcNode )
  {
    //error
    return static_cast<int>( ParserError );
  }

  QMap< QString, QgsRasterBlock* > inputBlocks;
  QVector<QgsRasterCalculatorEntry>::const_iterator it = mRasterEntries.constBegin();
  for ( ; it != mRasterEntries.constEnd(); ++it )
  {
    if ( !it->raster ) // no raster layer in entry
    {
      delete calcNode;
      qDeleteAll( inputBlocks );
      return static_cast< int >( InputLayerError );
    }

    QgsRasterBlock* block = nullptr;
    // if crs transform needed
    if ( it->raster->crs() != mOutputCrs )
    {
      QgsRasterProjector proj;
      proj.setCrs( it->raster->crs(), mOutputCrs );
      proj.setInput( it->raster->dataProvider() );
      proj.setPrecision( QgsRasterProjector::Exact );

      block = proj.block( it->bandNumber, mOutputRectangle, mNumOutputColumns, mNumOutputRows );
    }
    else
    {
      block = it->raster->dataProvider()->block( it->bandNumber, mOutputRectangle, mNumOutputColumns, mNumOutputRows );
    }
    if ( block->isEmpty() )
    {
      delete block;
      delete calcNode;
      qDeleteAll( inputBlocks );
      return static_cast<int>( MemoryError );
    }
    inputBlocks.insert( it->ref, block );
  }

  //open output dataset for writing
  GDALDriverH outputDriver = openOutputDriver();
  if ( !outputDriver )
  {
    return static_cast< int >( CreateOutputError );
  }

  GDALDatasetH outputDataset = openOutputFile( outputDriver );
  GDALSetProjection( outputDataset, mOutputCrs.toWkt().toLocal8Bit().data() );
  GDALRasterBandH outputRasterBand = GDALGetRasterBand( outputDataset, 1 );

  float outputNodataValue = -FLT_MAX;
  GDALSetRasterNoDataValue( outputRasterBand, outputNodataValue );

  if ( p )
  {
    p->setMaximum( mNumOutputRows );
  }

  QgsRasterMatrix resultMatrix;
  resultMatrix.setNodataValue( outputNodataValue );

  //read / write line by line
  for ( int i = 0; i < mNumOutputRows; ++i )
  {
    if ( p )
    {
      p->setValue( i );
    }

    if ( p && p->wasCanceled() )
    {
      break;
    }

    if ( calcNode->calculate( inputBlocks, resultMatrix, i ) )
    {
      bool resultIsNumber = resultMatrix.isNumber();
      float* calcData = new float[mNumOutputColumns];

      for ( int j = 0; j < mNumOutputColumns; ++j )
      {
        calcData[j] = ( float )( resultIsNumber ? resultMatrix.number() : resultMatrix.data()[j] );
      }

      //write scanline to the dataset
      if ( GDALRasterIO( outputRasterBand, GF_Write, 0, i, mNumOutputColumns, 1, calcData, mNumOutputColumns, 1, GDT_Float32, 0, 0 ) != CE_None )
      {
        QgsDebugMsg( "RasterIO error!" );
      }

      delete[] calcData;
    }

  }

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

  //close datasets and release memory
  delete calcNode;
  qDeleteAll( inputBlocks );
  inputBlocks.clear();

  if ( p && p->wasCanceled() )
  {
    //delete the dataset without closing (because it is faster)
    GDALDeleteDataset( outputDriver, TO8F( mOutputFile ) );
    return static_cast< int >( Cancelled );
  }
  GDALClose( outputDataset );

  return static_cast< int >( Success );
}
Ejemplo n.º 26
0
bool KNMusicLRCLyricsParser::parseData(const QString &lyricsTextData,
                                       QList<qint64> &positionList,
                                       QStringList &textList)
{
    //Clear the position list and text list.
    positionList.clear();
    textList.clear();
    //Split the lyrics text data.
    QStringList lyricsRawData=lyricsTextData.split(QRegExp("\n"),
                                                   QString::SkipEmptyParts);
    QList<LyricsLine> lyricsLineList;
    //Remove the same line in the lyrics raw data.
    lyricsRawData.removeDuplicates();
    //Parse the lyrics raw data.
    while(!lyricsRawData.isEmpty())
    {
        //Get the first line of the current list and remove all spaces.
        QString currentLine=lyricsRawData.takeFirst().simplified();
        //Find frames in the current line.
        QRegularExpressionMatchIterator frameMatcher=
                m_frameCatchRegExp.globalMatch(currentLine);
        int lastPosition=0;
        QLinkedList<QString> frameLists;
        //Get all the frames.
        while(frameMatcher.hasNext())
        {
            QRegularExpressionMatch matchedFrame=frameMatcher.next();
            //Check is the current matched frame is at the last position.
            //An example is:
            //  [00:00:01] Won't chu kiss me![00:00:03]Saikou no
            if(matchedFrame.capturedStart()!=lastPosition)
            {
                //Then we should pick out the data before the current start and
                //last position.
                //Like 'Won't chu kiss me!' in the example.
                QString text=currentLine.mid(lastPosition,
                                             matchedFrame.capturedStart()-lastPosition);
                //Parse the datas to frame lists.
                while(!frameLists.isEmpty())
                {
                    parseFrames(frameLists.takeFirst(),
                                text,
                                lyricsLineList);
                }
            }
            //Add current frame to frame list.
            frameLists.append(currentLine.mid(matchedFrame.capturedStart(),
                                              matchedFrame.capturedLength()));
            //Update the last position.
            lastPosition=matchedFrame.capturedEnd();
        }
        //Remove the previous datas, and parse the left datas to frame lists.
        currentLine.remove(0, lastPosition);
        while(!frameLists.isEmpty())
        {
            parseFrames(frameLists.takeFirst(),
                        currentLine,
                        lyricsLineList);
        }
    }
    //Check is the lyrics line list is empty or not, if it's empty, means we
    //can't parse it.
    if(lyricsLineList.isEmpty())
    {
        return false;
    }
    //Sorr the lyrics line.
    //- Why stable sort?
    //  Because there might be some frames at the same time. Display them with
    //their exist order.
    qStableSort(lyricsLineList.begin(), lyricsLineList.end(), frameLessThan);
    //Combine the same timestamp lyrics.
    QMap<qint64, QString> lyricsCombineMap;
    for(QList<LyricsLine>::iterator i=lyricsLineList.begin();
        i!=lyricsLineList.end();
        ++i)
    {
        lyricsCombineMap.insert((*i).position,
                                lyricsCombineMap.contains((*i).position)?
                                    lyricsCombineMap.value((*i).position)+'\n'+(*i).text:
                                    (*i).text);
    }
    //Export the position and the text.
    positionList=lyricsCombineMap.keys();
    textList=lyricsCombineMap.values();
    return true;
}
Ejemplo n.º 27
0
QMap<QString, Token> Image::generateTokens(Profile *profile) const
{
	QSettings *settings = profile->getSettings();
	QStringList ignore = profile->getIgnored();
	QStringList remove = settings->value("ignoredtags").toString().split(' ', QString::SkipEmptyParts);

	QMap<QString, Token> tokens;

	// Pool
	QRegularExpression poolRegexp("pool:(\\d+)");
	QRegularExpressionMatch poolMatch = poolRegexp.match(m_search.join(' '));
	tokens.insert("pool", Token(poolMatch.hasMatch() ? poolMatch.captured(1) : "", ""));

	// Metadata
	tokens.insert("filename", Token(QUrl::fromPercentEncoding(m_url.section('/', -1).section('.', 0, -2).toUtf8()), ""));
	tokens.insert("website", Token(m_parentSite->url(), ""));
	tokens.insert("websitename", Token(m_parentSite->name(), ""));
	tokens.insert("md5", Token(md5(), ""));
	tokens.insert("date", Token(m_createdAt, QDateTime()));
	tokens.insert("id", Token(m_id, 0));
	tokens.insert("rating", Token(m_rating, "unknown"));
	tokens.insert("score", Token(m_score, 0));
	tokens.insert("height", Token(m_size.height(), 0));
	tokens.insert("width", Token(m_size.width(), 0));
	tokens.insert("mpixels", Token(m_size.width() * m_size.height(), 0));
	tokens.insert("url_file", Token(m_url, ""));
	tokens.insert("url_sample", Token(m_sampleUrl.toString(), ""));
	tokens.insert("url_thumbnail", Token(m_previewUrl.toString(), ""));
	tokens.insert("url_page", Token(m_pageUrl.toString(), ""));
	tokens.insert("source", Token(m_source, ""));
	tokens.insert("filesize", Token(m_fileSize, 0));
	tokens.insert("author", Token(m_author, ""));
	tokens.insert("authorid", Token(m_authorId, 0));
	tokens.insert("parentid", Token(m_parentId, 0));

	// Flags
	tokens.insert("has_children", Token(m_hasChildren, false));
	tokens.insert("has_note", Token(m_hasNote, false));
	tokens.insert("has_comments", Token(m_hasComments, false));

	// Search
	for (int i = 0; i < m_search.size(); ++i)
	{ tokens.insert("search_" + QString::number(i + 1), Token(m_search[i], "")); }
	for (int i = m_search.size(); i < 10; ++i)
	{ tokens.insert("search_" + QString::number(i + 1), Token("", "")); }
	tokens.insert("search", Token(m_search.join(' '), ""));

	// Tags
	QMap<QString, QStringList> details;
	for (const Tag &tag : filteredTags(remove))
	{
		QString t = tag.text();

		details[ignore.contains(t, Qt::CaseInsensitive) ? "general" : tag.type().name()].append(t);
		details["alls"].append(t);
		details["alls_namespaces"].append(tag.type().name());

		QString underscored = QString(t);
		underscored.replace(' ', '_');
		details["allos"].append(underscored);
	}

	// Shorten copyrights
	if (settings->value("Save/copyright_useshorter", true).toBool())
	{
		QStringList copyrights;
		for (const QString &cop : details["copyright"])
		{
			bool found = false;
			for (int r = 0; r < copyrights.size(); ++r)
			{
				if (copyrights.at(r).left(cop.size()) == cop.left(copyrights.at(r).size()))
				{
					if (cop.size() < copyrights.at(r).size())
					{ copyrights[r] = cop; }
					found = true;
				}
			}
			if (!found)
			{ copyrights.append(cop); }
		}
		details["copyright"] = copyrights;
	}

	// Tags
	tokens.insert("general", Token(details["general"]));
	tokens.insert("artist", Token(details["artist"], "replaceAll", "anonymous", "multiple artists"));
	tokens.insert("copyright", Token(details["copyright"], "replaceAll", "misc", "crossover"));
	tokens.insert("character", Token(details["character"], "replaceAll", "unknown", "group"));
	tokens.insert("model", Token(details["model"], "replaceAll", "unknown", "multiple"));
	tokens.insert("species", Token(details["species"], "replaceAll", "unknown", "multiple"));
	tokens.insert("meta", Token(details["meta"], "replaceAll", "none", "multiple"));
	tokens.insert("allos", Token(details["allos"]));
	tokens.insert("allo", Token(details["allos"].join(' '), ""));
	tokens.insert("tags", Token(details["alls"]));
	tokens.insert("all", Token(details["alls"]));
	tokens.insert("all_namespaces", Token(details["alls_namespaces"]));

	// Extension
	QString ext = getExtension(m_url);
	if (settings->value("Save/noJpeg", true).toBool() && ext == "jpeg")
		ext = "jpg";
	tokens.insert("ext", Token(ext, "jpg"));
	tokens.insert("filetype", Token(ext, "jpg"));

	return tokens;
}
Ejemplo n.º 28
0
//判断该类型中是否存在需要升级(安装)的软件
const QMap<QString, SoftData> CERPCategory::UpgradeSoftwareData()
{
	QMap<QString, SoftData> srcData = GetData();
	QMap<QString, SoftData> upgradeData;
	//本地没有任何品牌安装
	if(GetLocalBrand().isEmpty())
	{
		//本地没有品牌安装,那么就需要进行一次扫描,以确定本地
		//是否存在已安装的软件,扫描出的列表可能含有多种品牌,
		//那么扫描结束后需要做进一步的处理
		QMapIterator<QString, SoftData> iter(srcData);
		while(iter.hasNext())
		{
			iter.next();
			SoftData data = iter.value();
			//此处的本地文件夹扫描,只是为了设置确定已安装的品牌
			LocalInstall(data);
			if(data.state == SMonitor::Normal || data.state == SMonitor::Upgrade)
			{
				//本地数据已安装,则需要记录已经安装的品牌
				SetLocalBrand(data.brand);
			}
			//本地扫描后,会有合法路径得出,所以这里要重新进行赋值
			srcData.insert(data.name, data);
		}
	}

	QString brand = GetLocalBrand();
	if(brand.isEmpty())
	{
		//由于任何软件的安装都会改变本地安装brand, 扫描后本地未存在任何已安装
		//的品牌,那么则表示为全新的环境,则服务器数据需要全部显示
		QMapIterator<QString, SoftData> iter(srcData);
		while(iter.hasNext())
		{
			iter.next();
			SoftData data = iter.value();
			//此处已经确定无任何品牌安装,所以无需再判断是否安装至本地
			//LocalInstall(data);
			emit MessageNotify(QDateTime::currentDateTime(), 
				QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装")
				.arg(data.name).arg(data.version));
			ClientLogger->AddLog(QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装")
				.arg(data.name).arg(data.version));
			upgradeData.insert(data.name, data);
		}
	}
	else
	{
		QMap<QString, SoftData> LocalData = CategoryFactory->LocalData().value(Category(), QMap<QString, SoftData> ());
		QMapIterator<QString, SoftData> iter(srcData);
		while(iter.hasNext())
		{
			iter.next();
			SoftData data = iter.value();
			if(data.brand == brand) //只显示已安装品牌的软件
			{
				if(LocalData.contains(iter.key()))//本地数据包含
				{
					const SoftData& lData = LocalData.value(iter.key());
					if(CMisc::IsNeedUpdate(lData.version, data.version))
					{
						//软件需要进行升级
						data.state = SMonitor::Upgrade;
						emit MessageNotify(QDateTime::currentDateTime(), 
							QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]")
							.arg(data.name).arg(data.version));
						ClientLogger->AddLog(QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]")
							.arg(data.name).arg(data.version));
						upgradeData.insert(data.name, data);
					}
					else
					{//无需升级,需要检查一下程序是否还存在
						if(!LocalInstall(data))
						{//已经不存在了
							upgradeData.insert(data.name, data);
							emit MessageNotify(QDateTime::currentDateTime(), 
								QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装")
								.arg(data.name).arg(data.version));
							ClientLogger->AddLog(QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装")
								.arg(data.name).arg(data.version));
						}
						else
						{
							if(data.version.isEmpty())
								continue;

							//本地已安装,则需要比较版本号,判断是否需要进行升级
							QString version = CMisc::GetVersionFileVersion(data.location);
							if(CMisc::IsNeedUpdate(version, data.version))
							{
								//软件需要进行升级
								data.state = SMonitor::Upgrade;
								upgradeData.insert(data.name, data);
								emit MessageNotify(QDateTime::currentDateTime(), 
									QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]")
									.arg(data.name).arg(data.version));
								ClientLogger->AddLog(QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]")
									.arg(data.name).arg(data.version));
							}
						}
					}
				}
				else
				{
					//判断本地是否已经安装
					if(LocalInstall(data))
					{
						//本地已安装,则需要比较版本号,判断是否需要进行升级
						QString version = CMisc::GetVersionFileVersion(data.location);
						if(CMisc::IsNeedUpdate(version, data.version))
						{
							//软件需要进行升级
							data.state = SMonitor::Upgrade;
							upgradeData.insert(data.name, data);
							emit MessageNotify(QDateTime::currentDateTime(), 
								QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]")
								.arg(data.name).arg(data.version));
							ClientLogger->AddLog(QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]")
								.arg(data.name).arg(data.version));
						}
						else
						{//本地已安装,但是本地数据中不包含,那么也需要显示
							data.state = SMonitor::Normal;
							upgradeData.insert(data.name, data);
						}
					}
					else
					{
						upgradeData.insert(data.name, data);
						emit MessageNotify(QDateTime::currentDateTime(), 
							QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装")
							.arg(data.name).arg(data.version));
						ClientLogger->AddLog(QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装")
							.arg(data.name).arg(data.version));
					}
				}
			}
		}
		
	}

	return upgradeData;
}
Ejemplo n.º 29
0
bool Spider::initial(const QString &xml){
    global::xml = xml;
    XpathUtil *util = new XpathUtil(this->page);
    QString id;
    //提取id号
    QStringList ids = util->xmlParser(xml,"//id");
    if(ids.size()==1){
        id = ids.at(0);
        qDebug()<<"taskID :"<<id;
    }else if(ids.size()==0){
        Logger::initial("error","",QDir::currentPath());
        logInfo("\n"+xml);
        logError("id error");
        return false;
    }

    global::taskID = id;
    global::mainServer = global::mainServer+id;
    global::slaveServer = global::slaveServer+id;

    Logger::initial(global::taskID,"",QDir::currentPath());

    logInfo("\n"+xml);

    //提取所有node节点
    QStringList nodes = util->xmlParser(xml,"//node");
    for(int i=0;i<nodes.length();i++){
        QString urlXpath = "//node["+QString::number(i+1)+"]/url";
        QString depthXpath = "//node["+QString::number(i+1)+"]/depth";
        QString regionXpath = "//node["+QString::number(i+1)+"]/regionXpath/property_group";
        //QString regionXpath = "//node["+QString::number(i+1)+"]/regionXpath/property[@name='value']";
        //QString regionstartWithFilterXpath = "//node["+QString::number(i+1)+"]/regionXpath/property[@name='startWithFilter']";
        QString loopXpath = "//node["+QString::number(i+1)+"]/loopXpath/property[@name='value']";

        QString collectDataXpath = "//node["+QString::number(i+1)+"]/collectDataXpath/property_group";

        Node node;
        QStringList urlist = util->xmlParser(xml,urlXpath);
        QStringList depthlist = util->xmlParser(xml,depthXpath);
        //QStringList filterlist = util->xmlParser(xml,regionstartWithFilterXpath);
        QStringList collectDatalist = util->xmlParser(xml,collectDataXpath);
        QStringList loopXpathlist = util->xmlParser(xml,loopXpath);
        QStringList regionXpathlist = util->xmlParser(xml,regionXpath);

        if(urlist.size()==1){
            node.url = urlist.at(0).trimmed();
            qDebug()<<"url :"<<node.url;
        }
        if(depthlist.size()==1){
            node.depth = depthlist.at(0).trimmed().toInt();
            qDebug()<<"depth :"<<node.depth;
        }
        qDebug()<<"loopXpath------------";
        if(loopXpathlist.size()!=0){
            for(int j=0;j<loopXpathlist.size();j++){
                xpath subNode;
                subNode.value = loopXpathlist.at(j).trimmed();
                node.loopXpath.append(subNode);
                qDebug()<<"loopXpath :"<<loopXpathlist.at(j).trimmed();
            }
        }
        qDebug()<<"regionXpath------------";
        if(regionXpathlist.size()!=0){

            for(int j=0;j<regionXpathlist.size();j++){
                xpath subNode;
                QString startWithFilterXpath = regionXpath+"["+QString::number(j+1)+"]/property[@name='startWithFilter']";
                QString endWithFilterXpath = regionXpath+"["+QString::number(j+1)+"]/property[@name='endWithFilter']";
                QString generalFilterXpath = regionXpath+"["+QString::number(j+1)+"]/property[@name='generalFilter']";
                QString inclusiveXpath = regionXpath+"["+QString::number(j+1)+"]/property[@name='inclusive']";
                QString valueXpath = regionXpath+"["+QString::number(j+1)+"]/property[@name='value']";
                QStringList startWithFilter = util->xmlParser(xml,startWithFilterXpath);
                QStringList endWithFilter = util->xmlParser(xml,endWithFilterXpath);
                QStringList generalFilter = util->xmlParser(xml,generalFilterXpath);
                QStringList inclusive = util->xmlParser(xml,inclusiveXpath);
                QStringList value = util->xmlParser(xml,valueXpath);
                if(startWithFilter.size()!=0){
                    subNode.startWithFilter = startWithFilter.at(0).trimmed();
                }
                if(endWithFilter.size()!=0){
                    subNode.endWithFilter = endWithFilter.at(0).trimmed();
                }
                if(generalFilter.size()!=0){
                    subNode.generalFilter = generalFilter.at(0).trimmed();
                }
                if(inclusive.size()!=0){
                    if(inclusive.at(0).trimmed()=="true"){
                        subNode.inclusive = true;
                    }
                }
                if(value.size()!=0){
                    subNode.value = value.at(0).trimmed();
                }
                node.regionXpath.append(subNode);
                qDebug()<<"startWith Filter:"<<subNode.startWithFilter;
                qDebug()<<"endWith Filter:"<<subNode.endWithFilter;
                qDebug()<<"general Filter:"<<subNode.generalFilter;
                qDebug()<<"inclusive :"<<subNode.inclusive;
                qDebug()<<"value :"<<subNode.value;
            }
        }

        //提取采集数据节点
        qDebug()<<"collectData ---------";
        if(collectDatalist.size()!=0){
            for(int j=0;j<collectDatalist.size();j++){
                QString collectDataTypeXpath = collectDataXpath+"["+QString::number(j+1)+"]/property[@name='type']";
                QString collectDataNameXpath = collectDataXpath+"["+QString::number(j+1)+"]/property[@name='name']";
                QString collectDataXpathXpath = collectDataXpath+"["+QString::number(j+1)+"]/property[@name='xpath']";
                QString collectDataDescXpath = collectDataXpath+"["+QString::number(j+1)+"]/property[@name='desc']";
                QMap<QString,QString> tmp;
                tmp.insert("type",util->xmlParser(xml,collectDataTypeXpath).at(0).trimmed());
                tmp.insert("name",util->xmlParser(xml,collectDataNameXpath).at(0).trimmed());
                tmp.insert("xpath",util->xmlParser(xml,collectDataXpathXpath).at(0).trimmed());
                tmp.insert("desc",util->xmlParser(xml,collectDataDescXpath).at(0).trimmed());
                node.collectData.append(tmp);
                qDebug()<<"type : "<<util->xmlParser(xml,collectDataTypeXpath).at(0).trimmed();
                qDebug()<<"name : "<<util->xmlParser(xml,collectDataNameXpath).at(0).trimmed();
                qDebug()<<"xpath : "<<util->xmlParser(xml,collectDataXpathXpath).at(0).trimmed();
                qDebug()<<"desc : "<<(util->xmlParser(xml,collectDataDescXpath).at(0).trimmed());
            }
        }
        global::unVisitedUrl->push(node);
        global::nodeMap->insert(node.depth,node);
        //qDebug()<<util->xmlParser(xml,urlXpath);
        //qDebug()<<util->xmlParser(xml,depthXpath);
        //qDebug()<<util->xmlParser(xml,regionXpath);
        //qDebug()<<util->xmlParser(xml,loopXpath).size();
        //qDebug()<<util->xmlParser(xml,collectDataXpath);
        qDebug()<<"----------------------------------------------------------------";
    }
    global::maxDepth = global::unVisitedUrl->top().depth;
    global::sqlite->openDB(global::taskID);
    global::sqlite->createTable(global::taskID,global::unVisitedUrl->top().collectData);
    return true;
}
Ejemplo n.º 30
0
  bool OMEMO::encryptMessage(const QString &ownJid, int account, QDomElement &xml, bool buildSessions, const uint32_t *toDeviceId) {
    std::shared_ptr<Signal> signal = getSignal(account);
    QString recipient = m_contactInfoAccessor->realJid(account, xml.attribute("to")).split("/").first();
    bool isGroup = xml.attribute("type") == "groupchat";
    if (!isEnabledForUser(account, recipient)) {
      return false;
    }

    if (buildSessions) {
      QMap<QString, QVector<uint32_t>> invalidSessions;
      QVector<uint32_t> invalidSessionsWithOwnDevices;
      if (isGroup) {
        forEachMucParticipant(account, ownJid, recipient, [&](const QString &userJid) {
          QVector<uint32_t> sessions = signal->invalidSessions(userJid);
          if (!sessions.isEmpty()) {
            invalidSessions.insert(userJid, sessions);
          }
          return true;
        });
      }
      else {
        QVector<uint32_t> sessions = signal->invalidSessions(recipient);
        if (!sessions.isEmpty()) {
          invalidSessions.insert(recipient, sessions);
        }
      }
      invalidSessionsWithOwnDevices = signal->invalidSessions(ownJid);
      invalidSessionsWithOwnDevices.removeOne(signal->getDeviceId());
      if (!invalidSessions.isEmpty() || !invalidSessionsWithOwnDevices.isEmpty()) {
        buildSessionsFromBundle(invalidSessions, invalidSessionsWithOwnDevices, ownJid, account, xml);
        xml = QDomElement();
        return true;
      }
    }

    signal->processUndecidedDevices(recipient, false);
    signal->processUndecidedDevices(ownJid, true);

    QDomElement encrypted = xml.ownerDocument().createElementNS(OMEMO_XMLNS, "encrypted");
    QDomElement header = xml.ownerDocument().createElement("header");
    header.setAttribute("sid", signal->getDeviceId());
    encrypted.appendChild(header);
    xml.appendChild(encrypted);

    QByteArray iv = Crypto::randomBytes(OMEMO_AES_GCM_IV_LENGTH);

    QDomElement ivElement = xml.ownerDocument().createElement("iv");
    ivElement.appendChild(xml.ownerDocument().createTextNode(iv.toBase64()));
    header.appendChild(ivElement);

    QByteArray key = Crypto::randomBytes(OMEMO_AES_128_KEY_LENGTH);
    QDomElement body = xml.firstChildElement("body");
    QPair<QByteArray, QByteArray> encryptedBody;
    if (!body.isNull()) {
      QString plainText = body.firstChild().nodeValue();
      encryptedBody = Crypto::aes_gcm(Crypto::Encode, iv, key, plainText.toUtf8());
      key += encryptedBody.second;
    }
    QList<EncryptedKey> encryptedKeys;
    if (isGroup) {
      forEachMucParticipant(account, ownJid, recipient, [&](const QString &userJid) {
        encryptedKeys.append(signal->encryptKey(ownJid, userJid, key));
        return true;
      });
    }
    else {
      encryptedKeys = signal->encryptKey(ownJid, recipient, key);
    }

    if (encryptedKeys.isEmpty()) {
      m_accountController->appendSysMsg(account, xml.attribute("to"), "[OMEMO] Unable to build any sessions, the message was not sent");
      xml = QDomElement();
    }
    else {
      foreach (EncryptedKey encKey, encryptedKeys) {
        if (toDeviceId != nullptr && *toDeviceId != encKey.deviceId) {
          continue;
        }
        QDomElement keyElement = xml.ownerDocument().createElement("key");
        keyElement.setAttribute("rid", encKey.deviceId);
        if (encKey.isPreKey) {
          keyElement.setAttribute("prekey", 1);
        }
        setNodeText(keyElement, encKey.key);
        header.appendChild(keyElement);
      }

      if (!body.isNull()) {
        if (isGroup) {
          m_encryptedGroupMessages.insert(xml.attribute("id"), body.firstChild().nodeValue());
        }
        xml.removeChild(body);

        QDomElement payload = xml.ownerDocument().createElement("payload");
        payload.appendChild(xml.ownerDocument().createTextNode(encryptedBody.first.toBase64()));
        encrypted.appendChild(payload);

        QDomElement html = xml.firstChildElement("html");
        if (!html.isNull()) {
          xml.removeChild(html);
        }
      }

      xml.appendChild(xml.ownerDocument().createElementNS("urn:xmpp:hints", "store"));

      QDomElement encryption = xml.ownerDocument().createElementNS("urn:xmpp:eme:0", "encryption");
      encryption.setAttribute("namespace", OMEMO_XMLNS);
      encryption.setAttribute("name", "OMEMO");
      xml.appendChild(encryption);
    }

    return true;
  }