Пример #1
1
    void json2tvalue(QVariant & output, const rapidjson::Value & input, int itype)
    {
        if(input.IsNull())
        {
            output.clear();
        }
        else if(input.IsInt64())
        {
            output = QVariant(input.GetInt64());
        }
        else if(input.IsInt())
        {
            output = QVariant(input.GetInt());
        }
        else if(input.IsDouble())
        {
            output = QVariant(input.GetDouble());
        }
        else if(input.IsBool())
        {
            output = QVariant(input.GetBool());
        }
        else if(input.IsString())
        {
            output = QVariant(QString(input.GetString()));
        }
        else if(input.IsArray())
        {
            switch(itype)
            {
            case QVariant::Point:
            {
                assert(input.Size() == 2);
                output = QPoint(input[0u].GetDouble(), input[1].GetDouble());
                break;
            }
            case QVariant::PointF:
            {
                assert(input.Size() == 2);
                output = QPointF(input[0u].GetDouble(), input[1].GetDouble());
                break;
            }
            case QVariant::Size:
            {
                assert(input.Size() == 2);
                output = QSize(input[0u].GetDouble(), input[1].GetDouble());
                break;
            }
            case QVariant::SizeF:
            {
                assert(input.Size() == 2);
                output = QSizeF(input[0u].GetDouble(), input[1].GetDouble());
                break;
            }
            case QVariant::Rect:
            {
                assert(input.Size() == 4);
                output = QRect(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
                break;
            }
            case QVariant::RectF:
            {
                assert(input.Size() == 4);
                output = QRectF(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
                break;
            }
            case QVariant::Vector2D:
            {
                assert(input.Size() == 2);
                output = QVector2D(input[0u].GetDouble(), input[1].GetDouble());
                break;
            }
            case QVariant::Vector3D:
            {
                assert(input.Size() == 3);
                output = QVector3D(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble());
                break;
            }
            case QVariant::Vector4D:
            {
                assert(input.Size() == 4);
                output = QVector4D(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
                break;
            }
            case QVariant::Color:
            {
                assert(input.Size() == 4);
                output = QColor(input[0u].GetDouble(), input[1].GetDouble(), input[2].GetDouble(), input[3].GetDouble());
                break;
            }
            case QVariant::StringList:
            {
                QStringList list;
                list.reserve(input.Size());

                for(rapidjson::Value::ConstValueIterator it = input.Begin(); it != input.End(); ++it)
                {
                    QString tmp(it->GetString());
                    list.append(tmp);
                }
                output = list;
                break;
            }
            case QVariant::List:
            default:
            {
                QList<QVariant> list;
                list.reserve(input.Size());

                for(rapidjson::SizeType i = 0; i < input.Size(); ++i)
                {
                    QVariant tmp;
                    json2tvalue(tmp, input[i], QVariant::Invalid);
                    list.append(tmp);
                }
                output = list;
                break;
            }
            }
        }
        else if(input.IsObject())
        {
            QMap<QString, QVariant> map;

            for(rapidjson::Value::ConstMemberIterator it= input.MemberBegin();
                it != input.MemberEnd(); ++it)
            {
                QString qstring(QLatin1String(it->name.GetString(), it->name.GetStringLength()));
                QVariant qvalue;
                json2tvalue(qvalue, it->value, QVariant::Invalid);

                map.insert(qstring, qvalue);
            }

            output = map;
        }
        else
        {
            output.clear();
            assert(false && "shouldn't execute to here.");
        }
    }
Пример #2
0
void WelcomeBrowser::loadData()
{
    QString data = m_templateData;

    QStringList sessionList;
    sessionList.append("<ul>");
    sessionList.append(QString("<li><a href=\"session:default\">default</a></li>"));
    sessionList.append("</ul>");


    QStringList list;
    QStringList schemeList;
    //schemeList = m_liteApp->fileManager()->schemeList();
    schemeList << "folder" << "file";
    schemeList.append(m_liteApp->fileManager()->schemeList());
    schemeList.removeDuplicates();
    foreach (QString scheme, schemeList) {
        QString s = scheme.left(1).toUpper()+scheme.right(scheme.length()-1);
        list.append(QString("<h3><i>Recent %1</i></h3>").arg(s));
        list.append("<table border=\"0\"><tr><td>");
        list.append("<ul>");
        QStringList recentProjects = m_liteApp->fileManager()->recentFiles(scheme);
        int count = 0;
        foreach (QString file, recentProjects) {
            QFileInfo info(file);
            list.append(QString("<li><a href=\"%1:%2\">%3</a> <span class=\"recent\">%4</span></li>")
                               .arg(scheme)
                               .arg(info.filePath())
                               .arg(info.fileName())
                               .arg(QDir::toNativeSeparators(info.filePath())));
            if (count++ > 8) {
                break;
            }
        }
Пример #3
0
bool FileServerHandler::HandleQueryFileTransfer(SocketHandler *socket,
                        QStringList &commands, QStringList &slist)
{
    if (commands.size() != 2)
        return false;

    if (slist.size() < 2)
        return false;

    QStringList res;
    int recnum = commands[1].toInt();
    FileTransfer *ft;

    {
        QReadLocker rlock(&m_ftLock);
        if (!m_ftMap.contains(recnum))
        {
            if (slist[1] == "DONE")
                res << "ok";
            else
            {
                LOG(VB_GENERAL, LOG_ERR,
                    QString("Unknown file transfer socket: %1").arg(recnum));
                res << "ERROR"
                    << "unknown_file_transfer_socket";
            }

            socket->SendStringList(res);
            return true;
        }

        ft = m_ftMap[recnum];
        ft->UpRef();
    }

    if (slist[1] == "IS_OPEN")
    {
        res << QString::number(ft->isOpen());
    }
    else if (slist[1] == "DONE")
    {
        ft->Stop();
        res << "ok";
    }
    else if (slist[1] == "REQUEST_BLOCK")
    {
        if (slist.size() != 3)
        {
            LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER "
                                     "REQUEST_BLOCK call");
            res << "ERROR" << "invalid_call";
        }
        else
        {
            int size = slist[2].toInt();
            res << QString::number(ft->RequestBlock(size));
        }
    }
    else if (slist[1] == "WRITE_BLOCK")
    {
        if (slist.size() != 3)
        {
            LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER "
                                     "WRITE_BLOCK call");
            res << "ERROR" << "invalid_call";
        }
        else
        {
            int size = slist[2].toInt();
            res << QString::number(ft->WriteBlock(size));
        }
    }
    else if (slist[1] == "SEEK")
    {
        if (slist.size() != 5)
        {
            LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER SEEK call");
            res << "ERROR" << "invalid_call";
        }
        else
        {
            long long pos = slist[2].toLongLong();
            int whence = slist[3].toInt();
            long long curpos = slist[4].toLongLong();

            res << QString::number(ft->Seek(curpos, pos, whence));
        }
    }
    else if (slist[1] == "SET_TIMEOUT")
    {
        if (slist.size() != 3)
        {
            LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER "
                                     "SET_TIMEOUT call");
            res << "ERROR" << "invalid_call";
        }
        else
        {
            bool fast = slist[2].toInt();
            ft->SetTimeout(fast);
            res << "ok";
        }
    }
    else
    {
        LOG(VB_GENERAL, LOG_ERR, "Invalid QUERY_FILETRANSFER call");
        res << "ERROR" << "invalid_call";
    }

    ft->DownRef();
    socket->SendStringList(res);
    return true;
}
Пример #4
0
bool FileServerHandler::HandleGetFileList(SocketHandler *socket,
                                          QStringList &slist)
{
    QStringList res;

    bool fileNamesOnly = false;
    if (slist.size() == 5)
        fileNamesOnly = slist[4].toInt();
    else if (slist.size() != 4)
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Invalid Request. %1")
                                     .arg(slist.join("[]:[]")));
        res << "EMPTY LIST";
        socket->SendStringList(res);
        return true;
    }

    QString host = gCoreContext->GetHostName();
    QString wantHost = slist[1];
    QString groupname = slist[2];
    QString path = slist[3];

    LOG(VB_FILE, LOG_INFO,
        QString("HandleSGGetFileList: group = %1  host = %2  "
                "path = %3 wanthost = %4")
            .arg(groupname).arg(host).arg(path).arg(wantHost));

    if ((host.toLower() == wantHost.toLower()) ||
        (gCoreContext->GetSetting("BackendServerIP") == wantHost))
    {
        StorageGroup sg(groupname, host);
        LOG(VB_FILE, LOG_INFO, "Getting local info");
        if (fileNamesOnly)
            res = sg.GetFileList(path);
        else
            res = sg.GetFileInfoList(path);

        if (res.count() == 0)
            res << "EMPTY LIST";
    }
    else
    {
        // handle request on remote server
        SocketHandler *remsock = NULL;
        {
            QReadLocker rlock(&m_fsLock);
            if (m_fsMap.contains(wantHost))
            {
                remsock = m_fsMap[wantHost];
                remsock->UpRef();
            }
        }

        if (remsock)
        {
            LOG(VB_FILE, LOG_INFO, "Getting remote info");
            res << "QUERY_SG_GETFILELIST" << wantHost << groupname << path
                << QString::number(fileNamesOnly);
            remsock->SendReceiveStringList(res);
            remsock->DownRef();
        }
        else
        {
            LOG(VB_FILE, LOG_ERR, QString("Failed to grab slave socket : %1 :")
                     .arg(wantHost));
            res << "SLAVE UNREACHABLE: " << wantHost;
        }
    }

    socket->SendStringList(res);
    return true;
}
Пример #5
0
/**
 * \addtogroup myth_network_protocol
 * \par        QUERY_FILE_EXISTS \e storagegroup \e filename
 */
bool FileServerHandler::HandleQueryFileExists(SocketHandler *socket,
                                              QStringList &slist)
{
    QString storageGroup = "Default";
    QStringList res;

    if (slist.size() == 3)
    {
        if (!slist[2].isEmpty())
            storageGroup = slist[2];
    }
    else if (slist.size() != 2)
        return false;

    QString filename = slist[1];
    if ((filename.isEmpty()) || 
        (filename.contains("/../")) || 
        (filename.startsWith("../")))
    {
        LOG(VB_GENERAL, LOG_ERR, 
            QString("ERROR checking for file, filename '%1' "
                    "fails sanity checks").arg(filename));
        res << "";
        socket->SendStringList(res);
        return true;
    }

    StorageGroup sgroup(storageGroup, gCoreContext->GetHostName());
    QString fullname = sgroup.FindFile(filename);

    if (!fullname.isEmpty())
    {
        res << "1"
            << fullname;

        // TODO: convert me to QFile
        struct stat fileinfo;
        if (stat(fullname.toLocal8Bit().constData(), &fileinfo) >= 0)
        {
            res << QString::number(fileinfo.st_dev)
                << QString::number(fileinfo.st_ino)
                << QString::number(fileinfo.st_mode)
                << QString::number(fileinfo.st_nlink)
                << QString::number(fileinfo.st_uid)
                << QString::number(fileinfo.st_gid)
                << QString::number(fileinfo.st_rdev)
                << QString::number(fileinfo.st_size)
#ifdef USING_MINGW
                << "0"
                << "0"
#else
                << QString::number(fileinfo.st_blksize)
                << QString::number(fileinfo.st_blocks)
#endif
                << QString::number(fileinfo.st_atime)
                << QString::number(fileinfo.st_mtime)
                << QString::number(fileinfo.st_ctime);
        }
    }
    else
        res << "0";

    socket->SendStringList(res);
    return true;
}
Пример #6
0
    void tvalue2json(rapidjson::Value & output, const QVariant & input, rapidjson::Value::AllocatorType & allocator)
    {
        switch(input.type())
        {
        case QVariant::Invalid:
        {
            output.SetNull();
            break;
        }
        case QVariant::Bool:
        {
            output.SetBool(input.toBool());
            break;
        }
        case QVariant::Int:
        {
            output.SetInt64(input.toInt());
            break;
        }
        case QVariant::LongLong:
        {
            output.SetInt64(input.toLongLong());
            break;
        }
        case QVariant::Double:
        {
            output.SetDouble(input.toDouble());
            break;
        }
        case QVariant::String:
        {
            QByteArray str = input.toString().toUtf8();
            output.SetString(str.data(), str.size(), allocator);
            break;
        }
        case QVariant::StringList:
        {
            QStringList list = input.toStringList();

            output.SetArray();
            output.Reserve(list.size(), allocator);

            rapidjson::Value temp;
            for(QStringList::const_iterator it = list.begin(); it != list.end(); ++it)
            {
                QByteArray str = it->toUtf8();
                temp.SetString(str.data(), str.size(), allocator);
                output.PushBack(temp, allocator);
            }
            break;
        }
        case QVariant::List:
        {
            QList<QVariant> list = input.toList();

            output.SetArray();
            output.Reserve(list.size(), allocator);

            rapidjson::Value temp;
            for(QList<QVariant>::const_iterator it = list.begin(); it != list.end(); ++it)
            {
                tvalue2json(temp, *it, allocator);
                output.PushBack(temp, allocator);
            }
            break;
        }
        case QVariant::Map:
        {
            output.SetObject();
            rapidjson::Value tempK, tempV;

            QMap<QString, QVariant> qmap = input.toMap();
            for(QMap<QString, QVariant>::const_iterator it = qmap.begin(); it != qmap.end(); ++it)
            {
                tvalue2json(tempK, it.key(), allocator);
                tvalue2json(tempV, it.value(), allocator);
                output.AddMember(tempK, tempV, allocator);
            }
            break;
        }
        case QVariant::Point:
        {
            QPoint pt = input.toPoint();

            output.SetArray();
            output.Reserve(2, allocator);

            output.PushBack(pt.x(), allocator);
            output.PushBack(pt.y(), allocator);
            break;
        }
        case QVariant::PointF:
        {
            QPointF pt = input.toPointF();

            output.SetArray();
            output.Reserve(2, allocator);

            output.PushBack(pt.x(), allocator);
            output.PushBack(pt.y(), allocator);
            break;
        }
        case QVariant::Size:
        {
            QSize pt = input.toSize();

            output.SetArray();
            output.Reserve(2, allocator);

            output.PushBack(pt.width(), allocator);
            output.PushBack(pt.height(), allocator);
            break;
        }
        case QVariant::SizeF:
        {
            QSizeF pt = input.toSizeF();

            output.SetArray();
            output.Reserve(2, allocator);

            output.PushBack(pt.width(), allocator);
            output.PushBack(pt.height(), allocator);
            break;
        }
        case QVariant::Rect:
        {
            QRect pt = input.toRect();

            output.SetArray();
            output.Reserve(4, allocator);

            output.PushBack(pt.x(), allocator);
            output.PushBack(pt.y(), allocator);
            output.PushBack(pt.width(), allocator);
            output.PushBack(pt.height(), allocator);
            break;
        }
        case QVariant::RectF:
        {
            QRectF pt = input.toRectF();

            output.SetArray();
            output.Reserve(4, allocator);

            output.PushBack(pt.x(), allocator);
            output.PushBack(pt.y(), allocator);
            output.PushBack(pt.width(), allocator);
            output.PushBack(pt.height(), allocator);
            break;
        }
        case QVariant::Vector2D:
        {
            QVector2D pt = input.value<QVector2D>();

            output.SetArray();
            output.Reserve(2, allocator);

            output.PushBack(pt.x(), allocator);
            output.PushBack(pt.y(), allocator);
            break;
        }
        case QVariant::Vector3D:
        {
            QVector3D pt = input.value<QVector3D>();

            output.SetArray();
            output.Reserve(3, allocator);

            output.PushBack(pt.x(), allocator);
            output.PushBack(pt.y(), allocator);
            output.PushBack(pt.z(), allocator);
            break;
        }
        case QVariant::Vector4D:
        {
            QVector4D pt = input.value<QVector4D>();

            output.SetArray();
            output.Reserve(4, allocator);

            output.PushBack(pt.x(), allocator);
            output.PushBack(pt.y(), allocator);
            output.PushBack(pt.z(), allocator);
            output.PushBack(pt.w(), allocator);
            break;
        }
        case QVariant::Color:
        {
            QColor pt = input.value<QColor>();

            output.SetArray();
            output.Reserve(4, allocator);

            output.PushBack(pt.red(), allocator);
            output.PushBack(pt.green(), allocator);
            output.PushBack(pt.blue(), allocator);
            output.PushBack(pt.alpha(), allocator);
            break;
        }
        default:
        {
            output.SetNull();
            assert(false && "shuldn't execute to here.");
        }
        }
    }
Пример #7
0
void PhoneInfoWidget::showPhoneInfo()
{
        QString data,tmp="1";
        QStringList list;
        QProcess *proces=new QProcess;
        proces->start("\""+sdk+"\""+"adb shell getprop");
        while (!tmp.isEmpty())
        {
            proces->waitForReadyRead(-1);
            tmp=proces->readLine();
            list.append(tmp);
        }

        for (int i=0;i<list.length();i++)
        {
            qDebug()<<"Getprop - "<<list.at(i);
            if (list.at(i).contains("[ro.product.model]"))
            {
                tmp=list.at(i);
                tmp.remove("[ro.product.model]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditModel->setText(tmp);
            }
            else if (list.at(i).contains("[ro.baseband]"))
            {
                tmp=list.at(i);
                tmp.remove("[ro.baseband]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditRadio->setText(tmp);
            }
            else if (list.at(i).contains("[ro.bootloader]"))
            {
                tmp=list.at(i);
                tmp.remove("[ro.bootloader]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditBootloader->setText(tmp);
            }
            else if (list.at(i).contains("[ro.build.display.id]"))
            {
                tmp=list.at(i);
                tmp.remove("[ro.build.display.id]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditRom->setText(tmp);
            }
            else if (list.at(i).contains("[gsm.operator.alpha]"))
            {
                tmp=list.at(i);
                tmp.remove("[gsm.operator.alpha]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditOperator->setText(tmp);
            }
        }
//        ui->lineEditSerialNumber->setText(this->phone->serialNumber);



        proces->start("\""+sdk+"\""+"adb shell busybox cat /sys/class/power_supply/battery/capacity");
        proces->waitForReadyRead(-1);
        tmp=proces->readLine();
        ui->progressBarBatteryLevel->setValue(tmp.toInt());
        proces->close();
        //get sd-ext folder
        QString sdFolder;
//        QStringList lines, split;
//        sdFolder.clear();
//        proces->start("\"" + this->sdk + "\"adb shell busybox mount");
//        proces->waitForFinished(-1);
//        tmp = proces->readAll();
//        qDebug()<<"Get phone info mount - "<<tmp;
//        if (tmp.contains("ext"))
//        {
//            lines = tmp.split("\n", QString::SkipEmptyParts);
//            while (lines.size() > 0)
//            {
//                tmp = lines.takeFirst();
//                if (tmp.contains("ext"))
//                {
//                    split = tmp.split(QRegExp("\\s+"),QString::SkipEmptyParts);
//                    if (split.size() > 2)
//                    {
//                        sdFolder = split.at(2);
//                        if (sdFolder.endsWith("/",Qt::CaseInsensitive))
//                            sdFolder.remove(sdFolder.length() - 1, 1);
//                    }
//                }
//            }
//        }
        QSettings settings;
        sdFolder = settings.value("sdFolder").toString();
        if (!sdFolder.isEmpty() && !sdFolder.contains(QRegExp("<.*>")))
        {
            if (sdFolder.endsWith("/",Qt::CaseInsensitive))
                sdFolder.chop(1);
        }
        proces->start("\""+sdk+"\""+"adb shell busybox df");
        tmp.clear();

        while (true)
        {
            proces->waitForReadyRead(-1);
            data=proces->readLine();
            if (data.isEmpty())
                break;
            tmp.append(data);
        }
        if (!tmp.contains(sdFolder) || sdFolder.isEmpty())
        {
            ui->progressBarExt->setDisabled(true);
            ui->labelExtAvailable->setDisabled(true);
            ui->labelExt->setDisabled(true);
            ui->labelExtSize->setDisabled(true);
            ui->labelExtUsed->setDisabled(true);
            ui->lineEditExtAvailable->setDisabled(true);
            ui->lineEditExtSize->setDisabled(true);
            ui->lineEditExtUsed->setDisabled(true);
        }
        list=tmp.split("\n");
        QStringList parts;
        QString used,available;
        while (list.count()>0)
        {
            tmp=list.takeFirst();
            qDebug()<<"df - "<<tmp;
            parts=tmp.split(QRegExp("\\s+"));
            if (parts.size()>2)
            {
                parts.removeLast();
                tmp=parts.takeLast();
                parts.removeLast();
                available=parts.takeLast();
                used=parts.takeLast();
            }

            if (tmp=="/data")
            {
                ui->lineEditDataAvailable->setText(PhoneInfoWidget::humanReadableSize(available+"000"));
                ui->lineEditDataUsed->setText(PhoneInfoWidget::humanReadableSize(used+"000"));
                ui->lineEditDataSize->setText(PhoneInfoWidget::humanReadableSize(QString::number(used.toUInt()+available.toUInt())+"000"));
                ui->progressBarData->setMaximum(used.toUInt()+available.toUInt());
                ui->progressBarData->setValue(used.toUInt());
            }
            else if (tmp=="/system")
            {
                ui->lineEditSystemAvailable->setText(PhoneInfoWidget::humanReadableSize(available+"000"));
                ui->lineEditSystemUsed->setText(PhoneInfoWidget::humanReadableSize(used+"000"));
                ui->lineEditSystemSize->setText(PhoneInfoWidget::humanReadableSize(QString::number(used.toUInt()+available.toUInt())+"000"));
                ui->progressBarSystem->setMaximum(used.toUInt()+available.toUInt());
                ui->progressBarSystem->setValue(used.toUInt());
            }
            else if (tmp.contains(sdFolder) && !sdFolder.isEmpty())
            {
                ui->lineEditExtAvailable->setText(PhoneInfoWidget::humanReadableSize(available+"000"));
                ui->lineEditExtUsed->setText(PhoneInfoWidget::humanReadableSize(used+"000"));
                ui->lineEditExtSize->setText(PhoneInfoWidget::humanReadableSize(QString::number(used.toUInt()+available.toUInt())+"000"));
                ui->progressBarExt->setMaximum(used.toUInt()+available.toUInt());
                ui->progressBarExt->setValue(used.toUInt());
            }
            else if (tmp.contains("/sdcard"))
            {
                ui->lineEditSdcardAvailable->setText(PhoneInfoWidget::humanReadableSize(available+"000"));
                ui->lineEditSdcardUsed->setText(PhoneInfoWidget::humanReadableSize(used+"000"));
                ui->lineEditSdcardSize->setText(PhoneInfoWidget::humanReadableSize(QString::number(used.toUInt()+available.toUInt())+"000"));
                ui->progressBarSdcard->setMaximum(used.toUInt()+available.toUInt());
                ui->progressBarSdcard->setValue(used.toUInt());
            }
        }
//        int i=0;
        //df
}
Пример #8
0
bool AutoReply::incomingStanza(int account, const QDomElement& stanza) {
    if (enabled) {
        if (stanza.tagName() == "message") {
            QString Status = AccInfoHost->getStatus(account);
            bool state = false;
            if(Status == "online" && SOnline) { state = true;
            } else {
                if(Status == "away" && SAway) { state = true;
                } else {
                    if(Status == "chat" && SChat) { state = true;
                    } else {
                        if(Status == "xa" && SXa) { state = true;
                        } else {
                            if(Status == "dnd" && SDnd) { state = true;
                            } else {
                                if(Status == "invisible" && SInvis) { state = true;
                                }
                            }
                        }
                    }
                }
            }
            if(!state)    return false;

            QStringList Disable = DisableForAcc.split(QRegExp("\\s+"), QString::SkipEmptyParts);
            QString AccJid = AccInfoHost->getJid(account);
            while(!Disable.isEmpty()) {
                if(AccJid == Disable.takeFirst()) return false;
            }

            QString type = "";
            type = stanza.attribute("type");
            if(type == "groupchat" || type == "error" || type == "normal")    return false;

            QDomElement Body = stanza.firstChildElement("body");
            if(Body.isNull())  return false;

            if(Body.text() == Message)    return false;

            QDomElement rec =  stanza.firstChildElement("received");
            if(!rec.isNull())  return false;

            QDomElement subj = stanza.firstChildElement("subject");
            if (subj.text() == "AutoReply" || subj.text() == "StopSpam" || subj.text() == "StopSpam Question") return false;

            QString from = stanza.attribute("from");
            QString to = stanza.attribute("to");
            QString valF = from.split("/").takeFirst();
            QString valT = to.split("/").takeFirst();
            if(valF.toLower() == valT.toLower())  return false;

            if(!from.contains("@")) return false;

            Disable = DisableFor.split(QRegExp("\\s+"), QString::SkipEmptyParts);
            if(EnableDisable) {
                while(!Disable.isEmpty()) {
                    QString J =     Disable.takeFirst();
                    if(J.toLower() == valF.toLower() || from.contains(J, Qt::CaseInsensitive)) {
                        return false;
                    }
                }
            }
            else {
                bool b = false;
                while(!Disable.isEmpty()) {
                    QString J =     Disable.takeFirst();
                    if(J.toLower() == valF.toLower() || from.contains(J, Qt::CaseInsensitive)) {
                        b = true;
                    }
                }
                if(!b) { return false;
                }
            }

            if(ActiveTabIsEnable) {
                QString getJid = ActiveTabHost->getJid();
                if(getJid.toLower() == from.toLower()) return false;
            }

            if(NotInRoster) {
                QStringList Roster = AccInfoHost->getRoster(account);
                if(!Roster.contains(valF, Qt::CaseInsensitive)) return false;
            }

            if(Times == 0) return false;
            if(Times != -1) {
                int i = Counter.size();
                if(FindAcc(account, from, i)) {
                    Base &B = Counter[i];
                    if(B.count >= Times) {
                        if(QDateTime::currentDateTime().secsTo(B.LastMes) >= -ResetTime*60) {
                            return false;
                        }
                        else {
                            B.count = 1;
                            B.LastMes = QDateTime::currentDateTime();
                        }
                    }
                    else {
                        B.count++;
                        B.LastMes = QDateTime::currentDateTime();
                    }
                }
                else {
                    Base B = {account, from, 1, QDateTime::currentDateTime() };
                    Counter << B;
                }
            }

            QString mes = "<message to='" + StanzaHost->escape(from) + "'";
            if(type != "") {
                mes += " type='" + StanzaHost->escape(type) + "'";
            }
            else {
                mes += "><subject>AutoReply</subject";
            }
            mes += "><body>" + StanzaHost->escape(Message) + "</body></message>";
            StanzaHost->sendStanza(account, mes);
        }
    }
    return false;
}
QString ChecklistGuideWizard::templateHtml (CoordSystemIndex coordSystemIndex) const
{
  LOG4CPP_INFO_S ((*mainCat)) << "ChecklistGuideWizard::templateHtml";

  QStringList curveNames = m_pageCurves [coordSystemIndex]->curveNames();
  bool withLines = m_pageCurves [coordSystemIndex]->withLines();

  QString html;
  QTextStream str (&html);

  // Insert additional space between successive list items, using stylesheet
  str << "<style type='text/css'>li { margin-top: 10px 0; }</style>";

  str << "<p>" << tr ("The coordinates are defined by creating axis points:") << "</p>\n";
  str << "<p>" << TAG_ANCHOR_AXIS_1 << "&nbsp;" << tr ("Add first of three axis points.") << " " << TAG_AHREF_AXIS_1 << "</p>\n";
  str << TAG_DIV_AXIS_START_1;
  str << "<ul>\n";
  str << "<li>" << tr ("Click on") << " <img src="":/engauge/img/16-DigitAxis""> " << tr ("for <b>Axis Points</b> mode") << "</li>\n";
  str << "<li>" << tr ("Click on an axis tick mark, or intersection of two grid lines, with labeled coordinates") << "</li>\n";
  str << "<li>" << tr ("Enter the coordinates of the axis point") << "</li>\n";
  str << "<li>" << tr ("Click on Ok") << "</li>\n";
  str << "</ul>\n";
  str << TAG_DIV_AXIS_END_1;
  str << "<p>" << TAG_ANCHOR_AXIS_2 << "&nbsp;" << tr ("Add second of three axis points.") << " " << TAG_AHREF_AXIS_2 << "</p>\n";
  str << TAG_DIV_AXIS_START_2;
  str << "<ul>\n";
  str << "<li>" << tr ("Click on") << " <img src="":/engauge/img/16-DigitAxis""> " << tr ("for <b>Axis Points</b> mode") << "</li>\n";
  str << "<li>" << tr ("Click on an axis tick mark, or intersection of two grid lines, with labeled coordinates, away from the other axis point") << "</li>\n";
  str << "<li>" << tr ("Enter the coordinates of the axis point") << "</li>\n";
  str << "<li>" << tr ("Click on Ok") << "</li>\n";
  str << "</ul>\n";
  str << TAG_DIV_AXIS_END_2;
  str << "<p>" << TAG_ANCHOR_AXIS_3 << "&nbsp;" << tr ("Add third of three axis points.") << " " << TAG_AHREF_AXIS_3 << "</p>\n";
  str << TAG_DIV_AXIS_START_3;
  str << "<ul>\n";
  str << "<li>" << tr ("Click on") << " <img src="":/engauge/img/16-DigitAxis""> " << tr ("for <b>Axis Points</b> mode") << "</li>\n";
  str << "<li>" << tr ("Click on an axis tick mark, or intersection of two grid lines, with labeled coordinates, away from the other axis points") << "</li>\n";
  str << "<li>" << tr ("Enter the coordinates of the axis point") << "</li>\n";
  str << "<li>" << tr ("Click on Ok") << "</li>\n";
  str << "</ul>\n";
  str << TAG_DIV_AXIS_END_3;

  str << "<p>&nbsp;</p>\n";
  str << "<p>" << tr ("Points are digitized along each curve:") << "</p>\n";
  QStringList::const_iterator itr;
  for (itr = curveNames.begin(); itr != curveNames.end(); itr++) {

    QString curveName = *itr;

    QString tagACurve = QString ("%1%2%3")
                        .arg (TAG_AHREF_DELIMITER_START)
                        .arg (curveName)
                        .arg (TAG_AHREF_DELIMITER_END);

    str << "<p>" << TAG_ANCHOR_DELIMITER_START << curveName << TAG_ANCHOR_DELIMITER_END
        << "&nbsp;" << tr ("Add points for curve") << " <b>" << curveName << "</b>. " << tagACurve << "</p>\n";
    str << TAG_DIV_DELIMITER_START << curveName << TAG_DIV_DELIMITER_END;
    str << "<ul>\n";

    if (withLines) {

      str << "<li>" << tr ("Click on") << " <img src="":/engauge/img/16-DigitSegment""> " << tr ("for <b>Segment Fill</b> mode") << "</li>\n";
      str << "<li>" << tr ("Select curve") << " <b>" << curveName << "</b> " << tr ("in the drop-down list") << "</li>\n";
      str << "<li>" << tr ("Move the cursor over the curve. If a line does not appear then adjust the <b>Color Filter</b> settings for this curve") << ":\n";
      str << templateHtmlToAdjustColorFilterSettings () << "</li>\n";
      str << "<li>" << tr ("Move the cursor over the curve again. When the <b>Segment Fill</b> line appears, click on it to generate points") << "</li>\n";
      str << "</ul>\n";

    } else {

      str << "<li>" << tr ("Click on") << " <img src="":/engauge/img/16-DigitPointMatch""> " << tr ("for <b>Point Match</b> mode") << "</li>\n";
      str << "<li>" << tr ("Select curve") << " <b>" << curveName << "</b> " << tr ("in the drop-down list") << "</li>\n";
      str << "<li>" << tr ("Move the cursor over a typical point in the curve. If the cursor circle does not change color then adjust "
                           "the <b>Color Filter</b> settings for this curve") << ":\n";
      str << templateHtmlToAdjustColorFilterSettings () << "</li>\n";
      str << "<li>" << tr ("Move the cursor over a typical point in the curve again. Click on the point to start point matching") << "</li>\n";
      str << "<li>" << tr ("Engauge will display a candidate point. To accept that candidate point, press the right arrow key") << "</li>\n";
      str << "<li>" << tr ("The previous step repeats until you select a different mode") << "</li>\n";
      str << "</ul>\n";
    }

    str << TAG_DIV_DELIMITER_START_SLASH << curveName << TAG_DIV_DELIMITER_END;
  }

  str << "<p>&nbsp;</p>\n";
  str << "<p>" << tr ("The digitized points can be exported") << ":</p>\n";
  str << "<p>" << TAG_ANCHOR_EXPORT << "&nbsp;" << tr ("Export the points to a file") << ". " << TAG_AHREF_EXPORT << "</p>\n";
  str << TAG_DIV_EXPORT_START;
  str << "<ul>\n";
  str << "<li>" << tr ("Select menu option <b>File / Export</b>") << "</li>\n";
  str << "<li>" << tr ("Enter the file name") << "</li>\n";
  str << "<li>" << tr ("Click on Ok") << "</li>\n";
  str << "<li>" << tr ("Congratulations!") << "</li>\n";
  str << "</ul>\n";
  str << TAG_DIV_EXPORT_END;

  str << "<p>&nbsp;</p>\n";
  str << "<p>" << tr ("Hint - The background image can be switched between the original image and filtered image.") << " " << TAG_AHREF_BACKGROUND << "</p>\n";
  str << TAG_DIV_BACKGROUND_START;
  str << "<ul>\n";
  str << "<li>" << tr ("Select menu option <b>View / Background / Show Original Image</b> to see the original image") << "</li>\n";
  str << "<li>" << tr ("Select menu option <b>View / Background / Show Filtered Image</b> to see the image from <b>Color Filter</b>") << "</li>\n";
  str << "</ul>\n";
  str << TAG_DIV_BACKGROUND_END;

  return html;
}
Пример #10
0
bool RSFImporter::import (
	ImporterContext &context
) {
	QTextStream stream (&(context.getStream ()));
	QString line, graphname="Graph";

	GraphOperations graphOp (context.getGraph ());
	ReadNodesStore readNodes;
	bool edgeOrientedDefault = false;
	bool edgeOrientedDefaultForce = false;
	Data::Type *edgeType = NULL;
	Data::Type *nodeType = NULL;
	context.getGraph ().setName (graphname);
	(void)graphOp.addDefaultTypes (edgeType, nodeType);
	
	int i = 0;
	while ( !stream.atEnd() ) {
		line = stream.readLine();
		QStringList words;
		words = line.split (QRegExp (QString ("[ \t]+")));
		int size = words.size ();
		Data::Type *newNodeType = NULL;
		osg::ref_ptr<Data::Node> node1, node2;
		osg::ref_ptr<Data::Edge> edge;
		if (size!=3){
			printf("%d",size);
			context.getInfoHandler ().reportError ("Zvoleny subor nie je validny RSF subor.");
			return false;
		}
		else{
			if (words[0]=="tagged")
			{
				//printf("%s %s\n",words[1], words[2]);
			}else
			{
				QString edgeName = words[0];
				QString srcNodeName = words[1];
				QString dstNodeName = words[2];

				// create nodes if not exist

				if (!readNodes.contains(srcNodeName))
				{
					node1 = context.getGraph().addNode(srcNodeName, nodeType);
					readNodes.addNode(srcNodeName, node1);
				} else {
					node1=readNodes.get(srcNodeName);
				}

				if (!readNodes.contains(dstNodeName))
				{
					node2 = context.getGraph ().addNode(dstNodeName, nodeType);
					readNodes.addNode(dstNodeName, node2);
				} else {
					node2=readNodes.get(dstNodeName);
				}
				//create hyperedge
				osg::ref_ptr<Data::Node> hyperEdgeNode;
				QMap<qlonglong, osg::ref_ptr<Data::Edge> > *mapa = context.getGraph().getEdges();

				hyperEdgeNode=RSFImporter().getHyperEdge(srcNodeName,edgeName,mapa);
				if (!hyperEdgeNode.valid ()) {
					hyperEdgeNode = context.getGraph ().addHyperEdge (edgeName);
					context.getGraph ().addEdge (QString (""), node1, hyperEdgeNode, edgeType, true);
				}
				
				context.getGraph ().addEdge (QString (""), hyperEdgeNode, node2, edgeType, true);
			}
		}

	}

	return true;
}
Пример #11
0
bool DeviceSkinParameters::read(QTextStream &ts, ReadMode rm, QString *errorMessage)
{
    QStringList closedAreas;
    QStringList toggleAreas;
    QStringList toggleActiveAreas;
    int nareas = 0;
    screenDepth = 0;
    QString mark;
    ts >> mark;
    hasMouseHover = true; // historical default
    if ( mark == QLatin1String("[SkinFile]") ) {
        const QString UpKey = QLatin1String("Up");
        const QString DownKey = QLatin1String("Down");
        const QString ClosedKey = QLatin1String("Closed");
        const QString ClosedAreasKey = QLatin1String("ClosedAreas");
        const QString ScreenKey = QLatin1String("Screen");
        const QString ScreenDepthKey = QLatin1String("ScreenDepth");
        const QString BackScreenKey = QLatin1String("BackScreen");
        const QString ClosedScreenKey = QLatin1String("ClosedScreen");
        const QString CursorKey = QLatin1String("Cursor");
        const QString AreasKey = QLatin1String("Areas");
        const QString ToggleAreasKey = QLatin1String("ToggleAreas");
        const QString ToggleActiveAreasKey = QLatin1String("ToggleActiveAreas");
        const QString HasMouseHoverKey = QLatin1String("HasMouseHover");
        // New
        while (!nareas) {
            QString line = ts.readLine();
            if ( line.isNull() )
                break;
            if ( line[0] != QLatin1Char('#') && !line.isEmpty() ) {
                int eq = line.indexOf(QLatin1Char('='));
                if ( eq >= 0 ) {
                    const QString key = line.left(eq);
                    eq++;
                    while (eq<line.length()-1 && line[eq].isSpace())
                        eq++;
                    const QString value = line.mid(eq);
                    if ( key == UpKey ) {
                        skinImageUpFileName = value;
                    } else if ( key == DownKey ) {
                        skinImageDownFileName = value;
                    } else if ( key ==  ClosedKey ) {
                        skinImageClosedFileName = value;
                    } else if ( key == ClosedAreasKey ) {
                        closedAreas = value.split(QLatin1Char(' '));
                    } else if ( key == ScreenKey ) {
                        parseRect( value, &screenRect);
                    } else if ( key == ScreenDepthKey ) {
                        screenDepth = value.toInt();
                    } else if ( key == BackScreenKey ) {
                        parseRect(value, &backScreenRect);
                    } else if ( key == ClosedScreenKey ) {
                        parseRect( value, &closedScreenRect );
                    } else if ( key == CursorKey ) {
                        QStringList l = value.split(QLatin1Char(' '));
                        skinCursorFileName = l[0];
                        cursorHot = QPoint(l[1].toInt(),l[2].toInt());
                    } else if ( key == AreasKey ) {
                        nareas = value.toInt();
                    } else if ( key == ToggleAreasKey ) {
                        toggleAreas = value.split(QLatin1Char(' '));
                    } else if ( key == ToggleActiveAreasKey ) {
                        toggleActiveAreas = value.split(QLatin1Char(' '));
                    } else if ( key == HasMouseHoverKey ) {
                        hasMouseHover = value == QLatin1String("true") || value == QLatin1String("1");
                    }
                } else {
                    *errorMessage =  DeviceSkin::tr("Syntax error: %1").arg(line);
                    return false;
                }
            }
        }
    } else {
        // Old
        skinImageUpFileName = mark;
        QString s;
        int x,y,w,h,na;
        ts >> s >> x >> y >> w >> h >> na;
        skinImageDownFileName = s;
        screenRect.setRect(x, y, w, h);
        nareas = na;
    }
    // Done for short mode
    if (rm ==  ReadSizeOnly)
        return true;
    //  verify skin files exist
    skinImageUpFileName.insert(0, prefix);
    if (!QFile(skinImageUpFileName).exists()) {
        *errorMessage =  DeviceSkin::tr("The skin \"up\" image file '%1' does not exist.").arg(skinImageUpFileName);
        return false;
    }
    if (!skinImageUp.load(skinImageUpFileName)) {
        *errorMessage = msgImageNotLoaded(skinImageUpFileName);
        return false;
    }

    skinImageDownFileName.insert(0, prefix);
    if (!QFile(skinImageDownFileName).exists()) {
        *errorMessage =  DeviceSkin::tr("The skin \"down\" image file '%1' does not exist.").arg(skinImageDownFileName);
        return false;
    }
    if (!skinImageDown.load(skinImageDownFileName)) {
        *errorMessage = msgImageNotLoaded(skinImageDownFileName);
        return false;
    }

    if (!skinImageClosedFileName.isEmpty()) {
        skinImageClosedFileName.insert(0, prefix);
        if (!QFile(skinImageClosedFileName).exists()) {
            *errorMessage =  DeviceSkin::tr("The skin \"closed\" image file '%1' does not exist.").arg(skinImageClosedFileName);
            return false;
        }
        if (!skinImageClosed.load(skinImageClosedFileName)) {
            *errorMessage = msgImageNotLoaded(skinImageClosedFileName);
            return false;
        }
    }

    if (!skinCursorFileName.isEmpty()) {
        skinCursorFileName.insert(0, prefix);
        if (!QFile(skinCursorFileName).exists()) {
            *errorMessage =  DeviceSkin::tr("The skin cursor image file '%1' does not exist.").arg(skinCursorFileName);
            return false;
        }
        if (!skinCursor.load(skinCursorFileName)) {
            *errorMessage = msgImageNotLoaded(skinCursorFileName);
            return false;
        }
    }

    // read areas
    if (!nareas)
        return true;
    buttonAreas.reserve(nareas);

    int i = 0;
    ts.readLine(); // eol
    joystick = -1;
    const QString Joystick = QLatin1String("Joystick");
    while (i < nareas && !ts.atEnd() ) {
        buttonAreas.push_back(DeviceSkinButtonArea());
        DeviceSkinButtonArea &area = buttonAreas.back();
        const QString line = ts.readLine();
        if ( !line.isEmpty() && line[0] != QLatin1Char('#') ) {
            const QStringList tok = line.split(QRegExp(QLatin1String("[ \t][ \t]*")));
            if ( tok.count()<6 ) {
                *errorMessage =  DeviceSkin::tr("Syntax error in area definition: %1").arg(line);
                return false;
            } else {
                area.name = tok[0];
                QString k = tok[1];
                if ( k.left(2).toLower() == QLatin1String("0x")) {
                    area.keyCode = k.mid(2).toInt(0,16);
                } else {
                    area.keyCode = k.toInt();
                }

                int p=0;
                for (int j=2; j < tok.count() - 1; ) {
                    const int x = tok[j++].toInt();
                    const int y = tok[j++].toInt();
                    area.area.putPoints(p++,1,x,y);
                }

                const QChar doubleQuote = QLatin1Char('"');
                if ( area.name[0] == doubleQuote && area.name.endsWith(doubleQuote)) {
                    area.name.truncate(area.name.size() - 1);
                    area.name.remove(0, 1);
                }
                if ( area.name.length() == 1 )
                    area.text = area.name;
                if ( area.name == Joystick)
                    joystick = i;
                area.activeWhenClosed = closedAreas.contains(area.name)
                    || area.keyCode == Qt::Key_Flip; // must be to work
		area.toggleArea = toggleAreas.contains(area.name);
		area.toggleActiveArea = toggleActiveAreas.contains(area.name);
		if ( area.toggleArea )
		    toggleAreaList += i;
                i++;
            }
        }
    }
    if (i != nareas) {
        qWarning() << DeviceSkin::tr("Mismatch in number of areas, expected %1, got %2.")
                      .arg(nareas).arg(i);
    }
    if (debugDeviceSkin)
	qDebug() << *this;
    return true;
}
Пример #12
0
// TODO: rewrite this function
void MainServer::parceCmdLine( const QStringList& arguments )
{
    for( int i = 1; i < arguments.count(); i++ )
    {
        if(
            arguments.at( i ).compare( "--port" ) == 0 &&
            i < arguments.count() - 1
        )
        {
            bool ok;
            this->port = arguments.at( i + 1 ).toInt( &ok );

            if( !ok )
            {
                this->port = DEFAULT_PORT;
                continue;
            }

            i++;
            continue;
        }

        if(
            arguments.at( i ).compare( "--address" ) == 0 &&
            i < arguments.count() - 1
        )
        {
            this->address.setAddress( arguments.at(i + 1) );
            i++;
            continue;
        }

        if(
            arguments.at( i ).compare( "--authfile" ) == 0 &&
            i < arguments.count() - 1
        )
        {
            if( QFile::exists(arguments.at(i + 1)) )
            {
                this->authFile = arguments.at( i + 1 );
                i++;
                continue;
            }
            this->authFile.clear();
            continue;
        }

        if(
            arguments.at( i ).compare( "--statfile" ) == 0 &&
            i < arguments.count() - 1
        )
        {
            if( QFile::exists(arguments.at(i + 1)) )
            {
                this->statFile = arguments.at( i + 1 );
                i++;
                continue;
            }
            this->statFile.clear();
            continue;
        }
    }
}
Пример #13
0
bool SvgFileSplitter::splitString(QString & contents, const QString & elementID)
{
	m_byteArray.clear();

	// gets rid of some crap inserted by illustrator which can screw up polygons and paths
	contents.replace('\t', ' ');
	contents.replace('\n', ' ');
	contents.replace('\r', ' ');

	// get rid of inkscape stuff too
	TextUtils::cleanSodipodi(contents);

	QString errorStr;
	int errorLine;
	int errorColumn;

	if (!m_domDocument.setContent(contents, true, &errorStr, &errorLine, &errorColumn)) {
        //DebugDialog::debug(QString("parse error: %1 l:%2 c:%3\n\n%4").arg(errorStr).arg(errorLine).arg(errorColumn).arg(contents));
		return false;
	}

	QDomElement root = m_domDocument.documentElement();
	if (root.isNull()) {
		return false;
	}

	if (root.tagName() != "svg") {
		return false;
	}

	root.removeAttribute("space");

	QDomElement element = TextUtils::findElementWithAttribute(root, "id", elementID);
	if (element.isNull()) {
		return false;
	}

	QStringList superTransforms;
	QDomNode parent = element.parentNode();
	while (!parent.isNull()) {
		QDomElement e = parent.toElement();
		if (!e.isNull()) {
			QString transform = e.attribute("transform");
			if (!transform.isEmpty()) {
				superTransforms.append(transform);
			}
		}
		parent = parent.parentNode();
	}

	if (!superTransforms.isEmpty()) {
		element.removeAttribute("id");
	}

	QDomDocument document;
	QDomNode node = document.importNode(element, true);
	document.appendChild(node);
	QString elementText = document.toString();

	if (!superTransforms.isEmpty()) {
		for (int i = 0; i < superTransforms.count() - 1; i++) {
			elementText = QString("<g transform='%1'>%2</g>").arg(superTransforms[i]).arg(elementText);
		}
		elementText = QString("<g id='%1' transform='%2'>%3</g>")
			.arg(elementID)
			.arg(superTransforms[superTransforms.count() - 1])
			.arg(elementText);
	}

	while (!root.firstChild().isNull()) {
		root.removeChild(root.firstChild());
	}

	// at this point the document should contain only the <svg> element and possibly svg info strings
	QString svgOnly = m_domDocument.toString();
	int ix = svgOnly.lastIndexOf("/>");
	if (ix < 0) return false;

	svgOnly[ix] = ' ';
	svgOnly += elementText;
	svgOnly += "</svg>";

	if (!m_domDocument.setContent(svgOnly, true, &errorStr, &errorLine, &errorColumn)) {
		return false;
	}

	m_byteArray = m_domDocument.toByteArray();

	//QString s = m_domDocument.toString();
	//DebugDialog::debug(s);

	return true;
}
static bool convertStudents(QString csvFilePath, int offset = 0) {
  QFile studentsCsv(csvFilePath);
  QTextStream studentsStream;
  QString insertStudentQueryString;
  QSqlQuery query;
  QString student;
  QStringList splittedStudent;
  NameMorpher nameMorpher;
  NameMorpher::MorphedName morphedName;
  studentsStream.setDevice(&studentsCsv);
  studentsStream.setCodec("UTF-8");
  if (!studentsCsv.open(QIODevice::ReadOnly)) {
    return false;
  }
  insertStudentQueryString = "INSERT INTO student"
      " (lastname, firstname, middlename,"
      "  lastname_datum, firstname_datum, middlename_datum,"
      "  lastname_accusative, firstname_accusative, middlename_accusative,"
      "  dob, university_group_id, decree_enrollment_number,"
      "  decree_expulsion_number, expulsion_reason_id,"
      "  expulsed_from_id)"
      " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
  query.prepare(insertStudentQueryString);
  while (!studentsStream.atEnd()) {
    student = studentsStream.readLine()
        .replace("не сданы зачеты ТП, УАТ; 17 пропусков занятий",
                 "не сданы зачеты ТП, УАТ. 17 пропусков занятий")
        .replace("не сдан зачет по УАТ; 45 пропусков занятий",
                 "не сдан зачет по УАТ. 45 пропусков занятий")
        .replace("Не сдал зачеты по УАТ, ТП; пропустил 102 ч занятий",
                 "Не сдал зачеты по УАТ, ТП. пропустил 102 ч занятий")
        .replace("Не сдал зачеты УАТ, ТП; пропустил 52 ч занятий",
                 "Не сдал зачеты УАТ, ТП. пропустил 52 ч занятий")
        .replace("Не сдал зачеты ТП, УАТ; пропущено 96 ч. Занятий",
                 "Не сдал зачеты ТП, УАТ. пропущено 96 ч. Занятий")
        .replace("Не сдал зачеты УАТ,ТП; пропустил 98 часов занятий",
                 "Не сдал зачеты УАТ,ТП. пропустил 98 часов занятий");
    if (student.isEmpty()) {
      continue;
    }
    splittedStudent = student.split(';');
    query.addBindValue(splittedStudent.at(offset + 2));
    query.addBindValue(splittedStudent.at(offset + 3));
    query.addBindValue(splittedStudent.at(offset + 4));
    morphedName = nameMorpher.getMorphedName(
          splittedStudent.at(offset + 2), splittedStudent.at(offset + 3),
          splittedStudent.at(offset + 4),
          true); // TODO: remove "true" in production
    query.addBindValue(morphedName.lastnameDatum);
    query.addBindValue(morphedName.firstnameDatum);
    query.addBindValue(morphedName.middlenameDatum);
    query.addBindValue(morphedName.lastnameAccusative);
    query.addBindValue(morphedName.firstnameAccusative);
    query.addBindValue(morphedName.middlenameAccusative);
    query.addBindValue(QVariant());
    if (splittedStudent.at(offset + 12) == "2007") {
      qDebug() << "WOWOWOW, I'VE CATCHED HIM!";
      return false;
    }
    int groupId = CSVOldFormatConverter::getGroupId(
          splittedStudent.at(offset + 5), splittedStudent.at(offset + 10),
          splittedStudent.at(offset + 12),
          offset == 0 ? splittedStudent.at(1) : QString(),
          splittedStudent.at(offset + 6), splittedStudent.at(offset + 11));
    query.addBindValue(groupId);
    query.addBindValue(splittedStudent.at(offset + 6));
    query.addBindValue(QVariant());
    query.addBindValue(QVariant());
    query.addBindValue(QVariant());
    if (!query.exec()) {
      qDebug() << query.lastError().text();
      return false;
    }
    int studentId = query.lastInsertId().toInt();
    if (!fillMarks(splittedStudent, studentId, groupId, offset)) {
      return false;
    }
  }
  return true;
}
static int getEvaluationId(QString subject, QString controlType,
                           QString teacher, int groupId, QString date) {
//  qDebug() << groupId;
  QSqlQuery query;
  query.prepare("SELECT id FROM control_type WHERE type = ?");
  query.addBindValue(controlType);
  if (!execAndNextQuery(query)) {
    qDebug() << "unknown control type" << controlType;
    return 0;
  }
  int controlTypeId = query.record().value("id").toInt();
  query.prepare("SELECT troop_id FROM university_group WHERE id = ?");
  query.addBindValue(groupId);
  if (!execAndNextQuery(query)) {
    return 0;
  }
  QVariant troopId = query.record().value("troop_id");
  query.prepare("SELECT id FROM subject WHERE name = ?");
  query.addBindValue(subject);
  if (!execAndNextQuery(query)) {
    qDebug() << "unknown subject" << subject;
    return 0;
  }
  int subjectId = query.record().value("id").toInt();
  teacher = teacher.simplified();
  int teacherId = 0;
  if (!teacher.isEmpty()) {
    query.prepare("SELECT id FROM teacher WHERE name = ?");
    query.addBindValue(teacher);
    if (!execAndNextQuery(query)) {
      QStringList splittedTeacher = teacher.split(" ");
      query.prepare("SELECT id FROM teacher WHERE name LIKE '%" +
                    splittedTeacher.at(splittedTeacher.length() - 2) + " " +
                    splittedTeacher.last() + "'");
      if (!execAndNextQuery(query)) {
        query.prepare("INSERT INTO teacher (name) VALUES (?)");
        query.addBindValue(teacher);
        if (!execQuery(query)) {
          qDebug() << "teacher insertion error";
          return 0;
        } else {
          teacherId = query.lastInsertId().toInt();
        }
      }
    }
    if (!teacherId) {
      teacherId = query.record().value("id").toInt();
    }
  }
  date = date.simplified();
  QDate oDate = QDate(1970, 1, 1);
  if (!date.isEmpty()) {
    oDate = QDate::fromString(date.split(" ").at(0), "dd.MM.yyyy");
  }
  query.prepare("SELECT id FROM evaluation WHERE subject_id = ? AND"
                " control_type_id = ? AND troop_id = ? AND date = ?");
  query.addBindValue(subjectId);
  query.addBindValue(controlTypeId);
  query.addBindValue(troopId);
  query.addBindValue(oDate);
  if (!execQuery(query)) {
    qDebug() << "ALARMEEEE";
    return 0;
  }
  if (query.next()) {
    return query.record().value("id").toInt();
  }
  query.prepare("INSERT INTO evaluation (subject_id, control_type_id,"
                " teacher_id, troop_id, date) VALUES (?, ?, ?, ?, ?)");
  query.addBindValue(subjectId);
  query.addBindValue(controlTypeId);
  query.addBindValue(teacherId ? teacherId : QVariant());
  query.addBindValue(troopId);
  query.addBindValue(oDate);
  if (!execQuery(query)) {
    qDebug() << "OPA ZHOPA STYLE";
    return 0;
  }
  return query.lastInsertId().toInt();
}
Пример #16
0
bool FileServerHandler::HandleAnnounce(MythSocket *socket,
                  QStringList &commands, QStringList &slist)
{
    if (commands[1] == "FileServer")
    {
        if (slist.size() >= 3)
        {
            SocketHandler *handler =
                new SocketHandler(socket, m_parent, commands[2]);

            handler->BlockShutdown(true);
            handler->AllowStandardEvents(true);
            handler->AllowSystemEvents(true);

            QWriteLocker wlock(&m_fsLock);
            m_fsMap.insert(commands[2], handler);
            m_parent->AddSocketHandler(handler);

            slist.clear();
            slist << "OK";
            handler->SendStringList(slist);
            return true;
        }
        return false;
    }

    if (commands[1] != "FileTransfer")
        return false;

    if (slist.size() < 3)
        return false;

    if ((commands.size() < 3) || (commands.size() > 6))
        return false;

    FileTransfer *ft    = NULL;
    QString hostname    = "";
    QString filename    = "";
    bool writemode      = false;
    bool usereadahead   = true;
    int timeout_ms      = 2000;
    switch (commands.size())
    {
      case 6:
        timeout_ms      = commands[5].toInt();
      case 5:
        usereadahead    = commands[4].toInt();
      case 4:
        writemode       = commands[3].toInt();
      default:
        hostname        = commands[2];
    }

    QStringList::const_iterator it = slist.begin();
    QUrl qurl           = *(++it);
    QString wantgroup   = *(++it);

    QStringList checkfiles;
    while (++it != slist.end())
        checkfiles += *(it);

    slist.clear();

    LOG(VB_GENERAL, LOG_DEBUG, "FileServerHandler::HandleAnnounce");
    LOG(VB_GENERAL, LOG_INFO, QString("adding: %1 as remote file transfer")
                            .arg(hostname));

    if (writemode)
    {
        if (wantgroup.isEmpty())
            wantgroup = "Default";

        StorageGroup sgroup(wantgroup, gCoreContext->GetHostName(), false);
        QString dir = sgroup.FindNextDirMostFree();
        if (dir.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, "Unable to determine directory "
                    "to write to in FileTransfer write command");

            slist << "ERROR" << "filetransfer_directory_not_found";
            socket->writeStringList(slist);
            return true;
        }

        QString basename = qurl.path();
        if (basename.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
                    "filename is empty in url '%1'.")
                    .arg(qurl.toString()));

            slist << "ERROR" << "filetransfer_filename_empty";
            socket->writeStringList(slist);
            return true;
        }

        if ((basename.contains("/../")) ||
            (basename.startsWith("../")))
        {
            LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
                    "filename '%1' does not pass sanity checks.")
                    .arg(basename));

            slist << "ERROR" << "filetransfer_filename_dangerous";
            socket->writeStringList(slist);
            return true;
        }

        filename = dir + "/" + basename;
    }
    else
        filename = LocalFilePath(qurl, wantgroup);

    QFileInfo finfo(filename);
    if (finfo.isDir())
    {
        LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer filename "
                "'%1' is actually a directory, cannot transfer.")
                .arg(filename));

        slist << "ERROR" << "filetransfer_filename_is_a_directory";
        socket->writeStringList(slist);
        return true;
    }

    if (writemode)
    {
        QString dirPath = finfo.absolutePath();
        QDir qdir(dirPath);
        if (!qdir.exists())
        {
            if (!qdir.mkpath(dirPath))
            {
                LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer "
                        "filename '%1' is in a subdirectory which does "
                        "not exist, but can not be created.")
                        .arg(filename));

                slist << "ERROR" << "filetransfer_unable_to_create_subdirectory";
                socket->writeStringList(slist);
                return true;
            }
        }

        ft = new FileTransfer(filename, socket, m_parent, writemode);
    }
    else
        ft = new FileTransfer(filename, socket, m_parent, usereadahead, timeout_ms);

    ft->BlockShutdown(true);

    {
        QWriteLocker wlock(&m_ftLock);
        m_ftMap.insert(socket->socket(), ft);
    }

    slist << "OK"
          << QString::number(socket->socket())
          << QString::number(ft->GetFileSize());

    if (checkfiles.size())
    {
        QFileInfo fi(filename);
        QDir dir = fi.absoluteDir();
        for (it = checkfiles.begin(); it != checkfiles.end(); ++it)
        {
            if (dir.exists(*it) &&
                QFileInfo(dir, *it).size() >= kReadTestSize)
                    slist << *it;
        }
    }

    socket->writeStringList(slist);
    m_parent->AddSocketHandler(ft);
    return true;
}
Пример #17
0
//------------------------------------------------------------------------------
void Logical::loadFromFile(QString fileName) {
    QFile lifeFile(fileName);
    if (!lifeFile.open(QIODevice::ReadOnly)) {
        QMessageBox::critical(0, tr("Error"),
                              tr("Can't load file"));
        return;
    } else {
        QTextStream lifeStream(&lifeFile);
        
        //Очистка буфера
        for (int i = 0; i < useHeight; ++i) {
            for (int j = 0; j < useWidth; ++j)
                lBuffer[i][j] = 0;
        }
        
        int lineCounter = 0;
        int positionI = 0;
        int positionJ = 0;
        int positionLastJ = 0;
        
        while (!lifeStream.atEnd()) {
            QString line = lifeStream.readLine();
            
            if (lineCounter == 0) {
                //Сделать проверку первой строки формата
                if (line.indexOf("#Life 1.05") == -1) {
                    QMessageBox::critical(0, tr("Error"),
                                          tr("Format isn't supported"));
                    return;
                }
            }
            
            if (
                    (line[0] == '.')
                    ||
                    (line[0] == '*')) {
                //Заполнять поле
                for (int i = 0; i < line.length(); ++i) {
                    if (line[i] == '.') {
                        lBuffer[positionI][positionJ] = 0;
                        positionJ++;
                    } else if (line[i] == '*') {
                        lBuffer[positionI][positionJ] = 1;
                        positionJ++;
                    }
                }
                positionI++;
            }
            
            QStringList splitted = line.split(' ');
            if (splitted[0] == "#P") {
                //Сменить начальную позицию
                //Размерность поделить на двое, чтобы получить -x 0 +x
                positionLastJ = (useWidth / 2) + splitted.at(1).toInt();
                positionI = (useHeight / 2) + splitted.at(2).toInt();
            }
            
            positionJ = positionLastJ;
            lineCounter++;
        }
        
        lifeFile.close();
        //Перенести буферное поле в реальное, а перед этим сделать очистку
        for (int i = 0; i < useHeight; ++i) {
            for (int j = 0; j < useWidth; ++j)
                lPole[i][j] = lBuffer[i][j];
        }
        
    }
}
Пример #18
0
QWidget *PartWidgetFactory::create(const QModelIndex &partIndex, int recursionDepth, const PartLoadingMode loadingMode)
{
    using namespace Imap::Mailbox;
    Q_ASSERT(partIndex.isValid());

    if (recursionDepth > 1000) {
        return new QLabel(tr("This message contains too deep nesting of MIME message parts.\n"
                             "To prevent stack exhaustion and your head from exploding, only\n"
                             "the top-most thousand items or so are shown."), 0);
    }

    bool userPrefersPlaintext = QSettings().value(Common::SettingsNames::guiPreferPlaintextRendering, QVariant(true)).toBool();

    QString mimeType = partIndex.data(Imap::Mailbox::RolePartMimeType).toString();
    if (mimeType.startsWith(QLatin1String("multipart/"))) {
        // it's a compound part
        if (mimeType == QLatin1String("multipart/alternative")) {
            return new MultipartAlternativeWidget(0, this, partIndex, recursionDepth,
                                                  userPrefersPlaintext ?
                                                      QLatin1String("text/plain") :
                                                      QLatin1String("text/html"));
        } else if (mimeType == QLatin1String("multipart/signed")) {
            return new MultipartSignedWidget(0, this, partIndex, recursionDepth);
        } else if (mimeType == QLatin1String("multipart/related")) {
            // The purpose of this section is to find a text/html e-mail, along with its associated body parts, and hide
            // everything else than the HTML widget.

            // At this point, it might be interesting to somehow respect the user's preference about using text/plain
            // instead of text/html. However, things are a bit complicated; the widget used at this point really wants
            // to either show just a single part or alternatively all of them in a sequence.
            // Furthermore, if someone sends a text/plain and a text/html together inside a multipart/related, they're
            // just wrong.

            // Let's see if we know what the root part is
            QModelIndex mainPartIndex;
            QVariant mainPartCID = partIndex.data(RolePartMultipartRelatedMainCid);
            if (mainPartCID.isValid()) {
                const Imap::Mailbox::Model *constModel = 0;
                Imap::Mailbox::TreeItemPart *part = dynamic_cast<Imap::Mailbox::TreeItemPart *>(Imap::Mailbox::Model::realTreeItem(partIndex, &constModel));
                Imap::Mailbox::Model *model = const_cast<Imap::Mailbox::Model *>(constModel);
                Imap::Mailbox::TreeItemPart *mainPartPtr = Imap::Network::MsgPartNetAccessManager::cidToPart(mainPartCID.toByteArray(), model, part);
                if (mainPartPtr) {
                    mainPartIndex = mainPartPtr->toIndex(model);
                }
            }

            if (!mainPartIndex.isValid()) {
                // The Content-Type-based start parameter was not terribly useful. Let's find the HTML part manually.
                QModelIndex candidate = partIndex.child(0, 0);
                while (candidate.isValid()) {
                    if (candidate.data(RolePartMimeType).toString() == QLatin1String("text/html")) {
                        mainPartIndex = candidate;
                        break;
                    }
                    candidate = candidate.sibling(candidate.row() + 1, 0);
                }
            }

            if (mainPartIndex.isValid()) {
                if (mainPartIndex.data(RolePartMimeType).toString() == QLatin1String("text/html")) {
                    return PartWidgetFactory::create(mainPartIndex, recursionDepth+1);
                } else {
                    // Sorry, but anything else than text/html is by definition suspicious here. Better than picking some random
                    // choice, let's just show everything.
                    return new GenericMultipartWidget(0, this, partIndex, recursionDepth);
                }
            } else {
                // The RFC2387's wording is clear that in absence of an explicit START argument, the first part is the starting one.
                // On the other hand, I've seen real-world messages whose first part is some utter garbage (an image sent as
                // application/octet-stream, for example) and some *other* part is an HTML text. In that case (and if we somehow
                // failed to pick the HTML part by a heuristic), it's better to show everything.
                return new GenericMultipartWidget(0, this, partIndex, recursionDepth);
            }
        } else {
            return new GenericMultipartWidget(0, this, partIndex, recursionDepth);
        }
    } else if (mimeType == QLatin1String("message/rfc822")) {
        return new Message822Widget(0, this, partIndex, recursionDepth);
    } else {
        QStringList allowedMimeTypes;
        allowedMimeTypes << "text/html" << "text/plain" << "image/jpeg" <<
                         "image/jpg" << "image/pjpeg" << "image/png" << "image/gif";
        // The problem is that some nasty MUAs (hint hint Thunderbird) would
        // happily attach a .tar.gz and call it "inline"
        bool showInline = partIndex.data(Imap::Mailbox::RolePartBodyDisposition).toByteArray().toLower() != "attachment" &&
                          allowedMimeTypes.contains(mimeType);

        if (showInline) {
            const Imap::Mailbox::Model *constModel = 0;
            Imap::Mailbox::TreeItemPart *part = dynamic_cast<Imap::Mailbox::TreeItemPart *>(Imap::Mailbox::Model::realTreeItem(partIndex, &constModel));
            Imap::Mailbox::Model *model = const_cast<Imap::Mailbox::Model *>(constModel);
            Q_ASSERT(model);
            Q_ASSERT(part);
            part->fetchFromCache(model);

            bool showDirectly = loadingMode == LOAD_IMMEDIATELY;
            if (!part->fetched())
                showDirectly &= model->isNetworkOnline() || part->octets() <= ExpensiveFetchThreshold;

            QWidget *widget = 0;
            if (showDirectly) {
                widget = new SimplePartWidget(0, manager, partIndex, m_messageView);
            } else if (model->isNetworkAvailable() || part->fetched()) {
                widget = new LoadablePartWidget(0, manager, partIndex, m_messageView,
                                                loadingMode == LOAD_ON_SHOW && part->octets() <= ExpensiveFetchThreshold ?
                                                    LoadablePartWidget::LOAD_ON_SHOW :
                                                    LoadablePartWidget::LOAD_ON_CLICK);
            } else {
                widget = new QLabel(tr("Offline"), 0);
            }
            return widget;
        } else {
            return new AttachmentView(0, manager, partIndex);
        }
    }
    QLabel *lbl = new QLabel(mimeType, 0);
    return lbl;
}
Пример #19
0
QString Client::parseCommand(QString buffer) {
    QStringList token = buffer.split(QRegExp(" "));
    if(token[0]=="attach") {
        if(token.count()>=2) {
            rx=token[1];
            return server->attach(rx.toInt(),this);
        } else {
            return "Invalid attach command";
        }
    } else if(token[0]=="start") {
        if(token.count()>=3) {
            if(token[1]=="iq") {
                iq_port=token[2].toInt();
            } else if(token[1]=="bandscope") {
                bandscope_port=token[2].toInt();
            } else {
                return "Invalid start command";
            }
        } else {
            return "Invalid start command";
        }
    } else if(token[0]=="stop") {
        if(token.count()>=3) {
            if(token[1]=="iq") {
                iq_port=-1;
            } else if(token[1]=="bandscope") {
                bandscope_port=-1;
            } else {
                return "Invalid stop command";
            }
        } else {
            return "Invalid stop command";
        }
    } else if(token[0]=="frequency") {
        if(token.count()>=2) {
            frequency=token[1].toLong();
            server->setFrequency(rx.toInt(),frequency);
        } else {
            return "Invalid frequency command";
        }
    } else if(token[0]=="preamp") {
        if(token.count()>=2) {
            preamp=(token[1]=="on");
        } else {
            return "Invalid preamp command";
        }
    } else if(token[0]=="mox") {
        if(token.count()>=2) {
            mox=(token[1]=="1");
            server->setMox(mox);
            qDebug()<<"mox"<<token[1]<<mox;
        } else {
            return "Invalid mox command";
        }
    } else if(token[0]=="ocoutput") {
        if(token.count()>=2) {
            ocoutput=token[1].toInt();
        } else {
            return "Invalid ocoutput command";
        }
    } else if(token[0]=="record") {
        if(token.count()>=2) {
            record=(token[1]=="on");
        } else {
            return "Invalid record command";
        }
    }
    return "OK";
}
Пример #20
0
QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *parent, Qt::WFlags fl )
    : QDialog( parent, fl ), mMapCanvas( mapCanvas )
{
  setupUi( this );
  connect( buttonBox, SIGNAL( accepted() ), this, SLOT( accept() ) );
  connect( buttonBox, SIGNAL( rejected() ), this, SLOT( reject() ) );
  connect( buttonBox->button( QDialogButtonBox::Apply ), SIGNAL( clicked() ), this, SLOT( apply() ) );
  connect( this, SIGNAL( accepted() ), this, SLOT( apply() ) );
  connect( projectionSelector, SIGNAL( sridSelected( QString ) ), this, SLOT( setMapUnitsToCurrentProjection() ) );

  ///////////////////////////////////////////////////////////
  // Properties stored in map canvas's QgsMapRenderer
  // these ones are propagated to QgsProject by a signal

  QgsMapRenderer* myRenderer = mMapCanvas->mapRenderer();
  QGis::UnitType myUnit = myRenderer->mapUnits();
  setMapUnits( myUnit );

  //see if the user wants on the fly projection enabled
  bool myProjectionEnabled = myRenderer->hasCrsTransformEnabled();
  cbxProjectionEnabled->setChecked( myProjectionEnabled );
  btnGrpMapUnits->setEnabled( !myProjectionEnabled );

  long myCRSID = myRenderer->destinationCrs().srsid();
  QgsDebugMsg( "Read project CRSID: " + QString::number( myCRSID ) );
  projectionSelector->setSelectedCrsId( myCRSID );

  ///////////////////////////////////////////////////////////
  // Properties stored in QgsProject

  title( QgsProject::instance()->title() );

  // get the manner in which the number of decimal places in the mouse
  // position display is set (manual or automatic)
  bool automaticPrecision = QgsProject::instance()->readBoolEntry( "PositionPrecision", "/Automatic" );
  if ( automaticPrecision )
  {
    radAutomatic->setChecked( true );
    spinBoxDP->setDisabled( true );
    labelDP->setDisabled( true );
  }
  else
  {
    radManual->setChecked( true );
  }

  cbxAbsolutePath->setCurrentIndex( QgsProject::instance()->readBoolEntry( "Paths", "/Absolute", true ) ? 0 : 1 );

  int dp = QgsProject::instance()->readNumEntry( "PositionPrecision", "/DecimalPlaces" );
  spinBoxDP->setValue( dp );

  //get the color selections and set the button color accordingly
  int myRedInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorRedPart", 255 );
  int myGreenInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorGreenPart", 255 );
  int myBlueInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorBluePart", 0 );
  int myAlphaInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorAlphaPart", 255 );
  QColor myColor = QColor( myRedInt, myGreenInt, myBlueInt, myAlphaInt );
  pbnSelectionColor->setColor( myColor );

  //get the color for map canvas background and set button color accordingly (default white)
  myRedInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorRedPart", 255 );
  myGreenInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorGreenPart", 255 );
  myBlueInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorBluePart", 255 );
  myColor = QColor( myRedInt, myGreenInt, myBlueInt );
  pbnCanvasColor->setColor( myColor );

  QgsMapLayer* currentLayer = 0;

  QStringList noIdentifyLayerIdList = QgsProject::instance()->readListEntry( "Identify", "/disabledLayers" );

  const QMap<QString, QgsMapLayer*> &mapLayers = QgsMapLayerRegistry::instance()->mapLayers();

  twIdentifyLayers->setColumnCount( 3 );
  twIdentifyLayers->horizontalHeader()->setVisible( true );
  twIdentifyLayers->setHorizontalHeaderItem( 0, new QTableWidgetItem( tr( "Layer" ) ) );
  twIdentifyLayers->setHorizontalHeaderItem( 1, new QTableWidgetItem( tr( "Type" ) ) );
  twIdentifyLayers->setHorizontalHeaderItem( 2, new QTableWidgetItem( tr( "Identifiable" ) ) );
  twIdentifyLayers->setRowCount( mapLayers.size() );
  twIdentifyLayers->verticalHeader()->setResizeMode( QHeaderView::ResizeToContents );

  int i = 0;
  for ( QMap<QString, QgsMapLayer*>::const_iterator it = mapLayers.constBegin(); it != mapLayers.constEnd(); it++, i++ )
  {
    currentLayer = it.value();

    QTableWidgetItem *twi = new QTableWidgetItem( QString::number( i ) );
    twIdentifyLayers->setVerticalHeaderItem( i, twi );

    twi = new QTableWidgetItem( currentLayer->name() );
    twi->setData( Qt::UserRole, it.key() );
    twi->setFlags( twi->flags() & ~Qt::ItemIsEditable );
    twIdentifyLayers->setItem( i, 0, twi );

    QString type;
    if ( currentLayer->type() == QgsMapLayer::VectorLayer )
    {
      type = tr( "Vector" );
    }
    else if ( currentLayer->type() == QgsMapLayer::RasterLayer )
    {
      QgsRasterLayer *rl = qobject_cast<QgsRasterLayer *>( currentLayer );

      if ( rl && rl->providerKey() == "wms" )
      {
        type = tr( "WMS" );
      }
      else
      {
        type = tr( "Raster" );
      }
    }

    twi = new QTableWidgetItem( type );
    twi->setFlags( twi->flags() & ~Qt::ItemIsEditable );
    twIdentifyLayers->setItem( i, 1, twi );

    QCheckBox *cb = new QCheckBox();
    cb->setChecked( !noIdentifyLayerIdList.contains( currentLayer->id() ) );
    twIdentifyLayers->setCellWidget( i, 2, cb );
  }

  grpWMSServiceCapabilities->setChecked( QgsProject::instance()->readBoolEntry( "WMSServiceCapabilities", "/", false ) );
  mWMSTitle->setText( QgsProject::instance()->readEntry( "WMSServiceTitle", "/" ) );
  mWMSContactOrganization->setText( QgsProject::instance()->readEntry( "WMSContactOrganization", "/", "" ) );
  mWMSContactPerson->setText( QgsProject::instance()->readEntry( "WMSContactPerson", "/", "" ) );
  mWMSContactMail->setText( QgsProject::instance()->readEntry( "WMSContactMail", "/", "" ) );
  mWMSContactPhone->setText( QgsProject::instance()->readEntry( "WMSContactPhone", "/", "" ) );
  mWMSAbstract->setPlainText( QgsProject::instance()->readEntry( "WMSServiceAbstract", "/", "" ) );

  bool ok;
  QStringList values;

  mWMSExtMinX->setValidator( new QDoubleValidator( mWMSExtMinX ) );
  mWMSExtMinY->setValidator( new QDoubleValidator( mWMSExtMinY ) );
  mWMSExtMaxX->setValidator( new QDoubleValidator( mWMSExtMaxX ) );
  mWMSExtMaxY->setValidator( new QDoubleValidator( mWMSExtMaxY ) );

  values = QgsProject::instance()->readListEntry( "WMSExtent", "/", &ok );
  grpWMSExt->setChecked( ok && values.size() == 4 );
  if ( grpWMSExt->isChecked() )
  {
    mWMSExtMinX->setText( values[0] );
    mWMSExtMinY->setText( values[1] );
    mWMSExtMaxX->setText( values[2] );
    mWMSExtMaxY->setText( values[3] );
  }

  values = QgsProject::instance()->readListEntry( "WMSCrsList", "/", &ok );
  grpWMSList->setChecked( ok && values.size() > 0 );
  if ( grpWMSList->isChecked() )
  {
    mWMSList->addItems( values );
  }
  else
  {
    values = QgsProject::instance()->readListEntry( "WMSEpsgList", "/", &ok );
    grpWMSList->setChecked( ok && values.size() > 0 );
    if ( grpWMSList->isChecked() )
    {
      QStringList list;
      foreach( QString value, values )
      {
        list << QString( "EPSG:%1" ).arg( value );
      }

      mWMSList->addItems( list );
    }
Пример #21
0
  // DescribeLayer is defined for WMS1.1.1/SLD1.0 and in WMS 1.3.0 SLD Extension
  QDomDocument describeLayer( QgsServerInterface *serverIface, const QgsProject *project, const QString &version,
                              const QgsServerRequest &request )
  {
    Q_UNUSED( version );

    QgsServerRequest::Parameters parameters = request.parameters();

    if ( !parameters.contains( QStringLiteral( "SLD_VERSION" ) ) )
    {
      throw QgsServiceException( QStringLiteral( "MissingParameterValue" ),
                                 QStringLiteral( "SLD_VERSION is mandatory for DescribeLayer operation" ), 400 );
    }
    if ( parameters[ QStringLiteral( "SLD_VERSION" )] != QLatin1String( "1.1.0" ) )
    {
      throw QgsServiceException( QStringLiteral( "InvalidParameterValue" ),
                                 QStringLiteral( "SLD_VERSION = %1 is not supported" ).arg( parameters[ QStringLiteral( "SLD_VERSION" )] ), 400 );
    }

    if ( !parameters.contains( QStringLiteral( "LAYERS" ) ) )
    {
      throw QgsServiceException( QStringLiteral( "MissingParameterValue" ),
                                 QStringLiteral( "LAYERS is mandatory for DescribeLayer operation" ), 400 );
    }

    QStringList layersList = parameters[ QStringLiteral( "LAYERS" )].split( ',', QString::SkipEmptyParts );
    if ( layersList.isEmpty() )
    {
      throw QgsServiceException( QStringLiteral( "InvalidParameterValue" ), QStringLiteral( "Layers is empty" ), 400 );
    }
    QDomDocument myDocument = QDomDocument();

    QDomNode header = myDocument.createProcessingInstruction( QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"UTF-8\"" ) );
    myDocument.appendChild( header );

    // Create the root element
    QDomElement root = myDocument.createElementNS( QStringLiteral( "http://www.opengis.net/sld" ), QStringLiteral( "DescribeLayerResponse" ) );
    root.setAttribute( QStringLiteral( "xsi:schemaLocation" ), QStringLiteral( "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/DescribeLayer.xsd" ) );
    root.setAttribute( QStringLiteral( "xmlns:ows" ), QStringLiteral( "http://www.opengis.net/ows" ) );
    root.setAttribute( QStringLiteral( "xmlns:se" ), QStringLiteral( "http://www.opengis.net/se" ) );
    root.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) );
    root.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    myDocument.appendChild( root );

    // store the Version element
    QDomElement versionNode = myDocument.createElement( QStringLiteral( "Version" ) );
    versionNode.appendChild( myDocument.createTextNode( QStringLiteral( "1.1.0" ) ) );
    root.appendChild( versionNode );

    // get the wms service url defined in project or keep the one from the
    // request url
    QString wmsHrefString = serviceUrl( request, project ).toString();

    // get the wfs service url defined in project or take the same as the
    // wms service url
    QString wfsHrefString = QgsServerProjectUtils::wfsServiceUrl( *project );
    if ( wfsHrefString.isEmpty() )
    {
      wfsHrefString = wmsHrefString;
    }

    // get the wcs service url defined in project or take the same as the
    // wms service url
    QString wcsHrefString = QgsServerProjectUtils::wcsServiceUrl( *project );
    if ( wcsHrefString.isEmpty() )
    {
      wcsHrefString = wmsHrefString;
    }

    // access control
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl *accessControl = serverIface->accessControls();
#endif
    // Use layer ids
    bool useLayerIds = QgsServerProjectUtils::wmsUseLayerIds( *project );
    // WMS restricted layers
    QStringList restrictedLayers = QgsServerProjectUtils::wmsRestrictedLayers( *project );
    // WFS layers
    QStringList wfsLayerIds = QgsServerProjectUtils::wfsLayerIds( *project );
    // WCS layers
    QStringList wcsLayerIds = QgsServerProjectUtils::wcsLayerIds( *project );

    for ( QgsMapLayer *layer : project->mapLayers() )
    {
      QString name = layer->name();
      if ( useLayerIds )
        name = layer->id();
      else if ( !layer->shortName().isEmpty() )
        name = layer->shortName();

      if ( !layersList.contains( name ) )
      {
        continue;
      }

      //unpublished layer
      if ( restrictedLayers.contains( layer->name() ) )
      {
        throw QgsSecurityException( QStringLiteral( "You are not allowed to access to this layer" ) );
      }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
      if ( accessControl && !accessControl->layerReadPermission( layer ) )
      {
        throw QgsSecurityException( QStringLiteral( "You are not allowed to access to this layer" ) );
      }
#endif

      // Create the NamedLayer element
      QDomElement layerNode = myDocument.createElement( QStringLiteral( "LayerDescription" ) );
      root.appendChild( layerNode );

      // store the owsType element
      QDomElement typeNode = myDocument.createElement( QStringLiteral( "owsType" ) );
      // store the se:OnlineResource element
      QDomElement oResNode = myDocument.createElement( QStringLiteral( "se:OnlineResource" ) );
      oResNode.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) );
      // store the TypeName element
      QDomElement nameNode = myDocument.createElement( QStringLiteral( "TypeName" ) );
      switch ( layer->type() )
      {
        case QgsMapLayer::VectorLayer:
        {
          typeNode.appendChild( myDocument.createTextNode( QStringLiteral( "wfs" ) ) );

          if ( wfsLayerIds.indexOf( layer->id() ) != -1 )
          {
            oResNode.setAttribute( QStringLiteral( "xlink:href" ), wfsHrefString );
          }

          // store the se:FeatureTypeName element
          QDomElement typeNameNode = myDocument.createElement( QStringLiteral( "se:FeatureTypeName" ) );
          typeNameNode.appendChild( myDocument.createTextNode( name ) );
          nameNode.appendChild( typeNameNode );
          break;
        }
        case QgsMapLayer::RasterLayer:
        {
          typeNode.appendChild( myDocument.createTextNode( QStringLiteral( "wcs" ) ) );

          if ( wcsLayerIds.indexOf( layer->id() ) != -1 )
          {
            oResNode.setAttribute( QStringLiteral( "xlink:href" ), wcsHrefString );
          }

          // store the se:CoverageTypeName element
          QDomElement typeNameNode = myDocument.createElement( QStringLiteral( "se:CoverageTypeName" ) );
          typeNameNode.appendChild( myDocument.createTextNode( name ) );
          nameNode.appendChild( typeNameNode );
          break;
        }

        case QgsMapLayer::MeshLayer:
        case QgsMapLayer::PluginLayer:
          break;
      }
      layerNode.appendChild( typeNode );
      layerNode.appendChild( oResNode );
      layerNode.appendChild( nameNode );
    }

    return myDocument;
  }
Пример #22
0
CKongQi::CKongQi(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CKongQi)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);

    QStringList header;
    header.append(trUtf8("MAC地址"));
    header.append(trUtf8("短地址"));
    ui->tableWidget->setColumnCount(2);
    ui->tableWidget->setColumnWidth(0, 236);
    ui->tableWidget->setColumnWidth(1, 0);
    ui->tableWidget->setHorizontalHeaderLabels(header);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);

    header.clear();
    header.append(trUtf8("节点名称"));
    header.append(trUtf8("短地址"));
    header.append(trUtf8("MAC地址"));
    header.append(trUtf8("节点位置"));
    header.append(trUtf8("功能"));
    ui->tableWidget_2->setColumnCount(5);
    ui->tableWidget_2->setColumnWidth(0, 120);
    ui->tableWidget_2->setColumnWidth(1, 128);
    ui->tableWidget_2->setColumnWidth(2, 128);
    ui->tableWidget_2->setColumnWidth(3, 128);
    ui->tableWidget_2->setColumnWidth(4, 128);
    ui->tableWidget_2->setHorizontalHeaderLabels(header);
    ui->tableWidget_2->setSelectionMode(QAbstractItemView::SingleSelection);
    SelectGuanXianAddr();

    header.clear();
    header.append(trUtf8("主控名称"));
    header.append(trUtf8("主控短地址"));
    header.append(trUtf8("主控MAC地址"));
    header.append(trUtf8("主控位置"));
    header.append(trUtf8("被控名称"));
    header.append(trUtf8("被控短地址"));
    header.append(trUtf8("被控MAC地址"));
    header.append(trUtf8("被控位置"));
    header.append(trUtf8("功能"));
    header.append(trUtf8("实际功能"));
    ui->tableWidget_3->setColumnCount(10);
    ui->tableWidget_3->setColumnWidth(0, 100);
    ui->tableWidget_3->setColumnWidth(1, 100);
    ui->tableWidget_3->setColumnWidth(2, 268);
    ui->tableWidget_3->setColumnWidth(3, 100);
    ui->tableWidget_3->setColumnWidth(4, 110);
    ui->tableWidget_3->setColumnWidth(5, 100);
    ui->tableWidget_3->setColumnWidth(6, 248);
    ui->tableWidget_3->setColumnWidth(7, 148);
    ui->tableWidget_3->setColumnWidth(9, 148);
    ui->tableWidget_3->setColumnWidth(10, 148);
    ui->tableWidget_3->setHorizontalHeaderLabels(header);
    ui->tableWidget_3->setSelectionMode(QAbstractItemView::SingleSelection);
    SelectGuanXianControl();
    readtable();

    ui->comboBox->insertItem(0,QIcon(":/images/1.png"),trUtf8("开"));
    ui->comboBox->insertItem(1,QIcon(":/images/2.png"),trUtf8("关"));
    ui->comboBox->setCurrentIndex(0);

    tablerow1=-1;
    tablerow2=-1;
    tablerow3=-1;
}
Пример #23
0
RecoveryWidget::RecoveryWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecoveryWidget)
{
    ui->setupUi(this);

    this->setLayout(this->ui->layoutRecovery);

    QSettings settings;
    this->sdk=settings.value("sdkPath").toString();
    this->dialog = NULL;
    this->recoverySDmounted=false;

    QProcess *nandroid = new QProcess;
    QString output, tmp;
    QStringList tmpLines;
    nandroid->start("\"" + sdk + "\"adb shell su -c 'find /sbin -name nandroid-mobile*.sh'");
    nandroid->waitForFinished(-1);
    output = nandroid->readAll();
    tmpLines = output.split("\n", QString::SkipEmptyParts);
    this->nandroidScript.clear();
    while (tmpLines.size() > 0)
    {
        tmp = tmpLines.takeFirst();
        if (tmp.contains("find"))
        {
            continue;
        }
        else
        {
            this->nandroidScript = tmp;
        }
    }

    if (this->nandroidScript.isEmpty())
    {
        this->ui->buttonNandroidBackup->setDisabled(true);
        this->ui->buttonNandroidRestore->setDisabled(true);
    }
    else
    {
        this->ui->buttonNandroidBackup->setDisabled(false);
        this->ui->buttonNandroidRestore->setDisabled(false);
    }

    QProcess *process=new QProcess();

    process->start("\""+sdk+"\"adb shell su -c 'ls /sbin/wipe'");
    process->waitForFinished(-1);
    tmp = process->readAll();
    if (tmp.contains("No such file"))
        this->ui->buttonClearBattery->setDisabled(true);
    else
        this->ui->buttonClearBattery->setEnabled(true);
    process->terminate();
    delete process;
    process=new QProcess();
    process->start("\""+sdk+"\"adb shell su -c 'ls /sbin/ums_toggle'");
    process->waitForFinished(-1);
    tmp = process->readAll();
    if (tmp.contains("No such file"))
        this->ui->buttonMountSD->setDisabled(true);
    else
        this->ui->buttonMountSD->setEnabled(true);
    process->terminate();
    delete process;

    process=new QProcess();
    process->start("\""+sdk+"\"adb shell su -c 'ls /sbin/fix_permissions'");
    process->waitForFinished(-1);
    tmp = process->readAll();
    if (tmp.contains("No such file"))
        this->ui->buttonFixUID->setDisabled(true);
    else
        this->ui->buttonFixUID->setEnabled(true);
    process->terminate();
    delete process;

    this->ui->stackedRecovery->setCurrentWidget(this->ui->pageRecoveryStart);
    ui->pageWipeData->setLayout(ui->layoutWipeData);
    ui->pageFixUID->setLayout(ui->layoutFixUID);
    ui->pageFlashZIP->setLayout(ui->layoutFlashZIP);
    ui->pageNandroidBackup->setLayout(ui->layoutNandroidBackup);
    ui->pageNandroidRestore->setLayout(ui->layoutNandroidRestore);
    ui->pageRecoveryStart->setLayout(ui->layoutRecoveryStart);


    connect(this->ui->buttonClearBattery, SIGNAL(clicked()), this, SLOT(wipeBattery()));
    connect(this->ui->buttonFixUID, SIGNAL(clicked()), this, SLOT(fixUID()));
    connect(this->ui->buttonMountSD, SIGNAL(clicked()), this, SLOT(mountSDcard()));
    connect(this->ui->buttonNandroidBackup, SIGNAL(clicked()), this, SLOT(nandroidBackupPage()));
    connect(this->ui->buttonNandroidRestore, SIGNAL(clicked()), this, SLOT(nandroidRestorePage()));
    connect(this->ui->checkNandroidBackupPath, SIGNAL(toggled(bool)), this, SLOT(nandroidBackupEdit()));
    connect(this->ui->checkNandroidBackupString, SIGNAL(toggled(bool)), this, SLOT(nandroidBackupEdit()));
    connect(this->ui->buttonNandroidBackupStart, SIGNAL(clicked()), this, SLOT(nandroidBackup()));
    connect(this->ui->buttonNandroidRestoreStart, SIGNAL(clicked()), this, SLOT(nandroidRestore()));
    connect(this->ui->comboNandroidRestore, SIGNAL(currentIndexChanged(QString)), this, SLOT(nandroidRestoreCombo()));
    connect(this->ui->buttonWipeData, SIGNAL(clicked()), this, SLOT(wipeData()));
}
Пример #24
0
bool QgsMapLayer::readXML( const QDomNode& layer_node )
{
  QgsCoordinateReferenceSystem savedCRS;
  CUSTOM_CRS_VALIDATION savedValidation;
  bool layerError;

  QDomElement element = layer_node.toElement();

  QDomNode mnl;
  QDomElement mne;

  // read provider
  QString provider;
  mnl = layer_node.namedItem( "provider" );
  mne = mnl.toElement();
  provider = mne.text();

  // set data source
  mnl = layer_node.namedItem( "datasource" );
  mne = mnl.toElement();
  mDataSource = mne.text();

  // TODO: this should go to providers
  if ( provider == "spatialite" )
  {
    QgsDataSourceURI uri( mDataSource );
    uri.setDatabase( QgsProject::instance()->readPath( uri.database() ) );
    mDataSource = uri.uri();
  }
  else if ( provider == "ogr" )
  {
    QStringList theURIParts = mDataSource.split( "|" );
    theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] );
    mDataSource = theURIParts.join( "|" );
  }
  else if ( provider == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( mDataSource.toAscii() );

    if ( !mDataSource.startsWith( "file:" ) )
    {
      QUrl file = QUrl::fromLocalFile( mDataSource.left( mDataSource.indexOf( "?" ) ) );
      urlSource.setScheme( "file" );
      urlSource.setPath( file.path() );
    }

    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->readPath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    mDataSource = QString::fromAscii( urlDest.toEncoded() );
  }
  else if ( provider == "wms" )
  {
    // >>> BACKWARD COMPATIBILITY < 1.9
    // For project file backward compatibility we must support old format:
    // 1. mode: <url>
    //    example: http://example.org/wms?
    // 2. mode: tiled=<width>;<height>;<resolution>;<resolution>...,ignoreUrl=GetMap;GetFeatureInfo,featureCount=<count>,username=<name>,password=<password>,url=<url>
    //    example: tiled=256;256;0.703;0.351,url=http://example.org/tilecache?
    //    example: featureCount=10,http://example.org/wms?
    //    example: ignoreUrl=GetMap;GetFeatureInfo,username=cimrman,password=jara,url=http://example.org/wms?
    // This is modified version of old QgsWmsProvider::parseUri
    // The new format has always params crs,format,layers,styles and that params
    // should not appear in old format url -> use them to identify version
    if ( !mDataSource.contains( "crs=" ) && !mDataSource.contains( "format=" ) )
    {
      QgsDebugMsg( "Old WMS URI format detected -> converting to new format" );
      QgsDataSourceURI uri;
      if ( !mDataSource.startsWith( "http:" ) )
      {
        QStringList parts = mDataSource.split( "," );
        QStringListIterator iter( parts );
        while ( iter.hasNext() )
        {
          QString item = iter.next();
          if ( item.startsWith( "username="******"username", item.mid( 9 ) );
          }
          else if ( item.startsWith( "password="******"password", item.mid( 9 ) );
          }
          else if ( item.startsWith( "tiled=" ) )
          {
            // in < 1.9 tiled= may apper in to variants:
            // tiled=width;height - non tiled mode, specifies max width and max height
            // tiled=width;height;resolutions-1;resolution2;... - tile mode

            QStringList params = item.mid( 6 ).split( ";" );

            if ( params.size() == 2 ) // non tiled mode
            {
              uri.setParam( "maxWidth", params.takeFirst() );
              uri.setParam( "maxHeight", params.takeFirst() );
            }
            else if ( params.size() > 2 ) // tiled mode
            {
              // resolutions are no more needed and size limit is not used for tiles
              // we have to tell to the provider however that it is tiled
              uri.setParam( "tileMatrixSet", "" );
            }
          }
          else if ( item.startsWith( "featureCount=" ) )
          {
            uri.setParam( "featureCount", item.mid( 13 ) );
          }
          else if ( item.startsWith( "url=" ) )
          {
            uri.setParam( "url", item.mid( 4 ) );
          }
          else if ( item.startsWith( "ignoreUrl=" ) )
          {
            uri.setParam( "ignoreUrl", item.mid( 10 ).split( ";" ) );
          }
        }
      }
      else
      {
        uri.setParam( "url", mDataSource );
      }
      mDataSource = uri.encodedUri();
      // At this point, the URI is obviously incomplete, we add additional params
      // in QgsRasterLayer::readXml
    }
    // <<< BACKWARD COMPATIBILITY < 1.9
  }
  else
  {
    mDataSource = QgsProject::instance()->readPath( mDataSource );
  }

  // Set the CRS from project file, asking the user if necessary.
  // Make it the saved CRS to have WMS layer projected correctly.
  // We will still overwrite whatever GDAL etc picks up anyway
  // further down this function.
  mnl = layer_node.namedItem( "layername" );
  mne = mnl.toElement();

  QDomNode srsNode = layer_node.namedItem( "srs" );
  mCRS->readXML( srsNode );
  mCRS->setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) );
  mCRS->validate();
  savedCRS = *mCRS;

  // Do not validate any projections in children, they will be overwritten anyway.
  // No need to ask the user for a projections when it is overwritten, is there?
  savedValidation = QgsCoordinateReferenceSystem::customSrsValidation();
  QgsCoordinateReferenceSystem::setCustomSrsValidation( NULL );

  // now let the children grab what they need from the Dom node.
  layerError = !readXml( layer_node );

  // overwrite CRS with what we read from project file before the raster/vector
  // file readnig functions changed it. They will if projections is specfied in the file.
  // FIXME: is this necessary?
  QgsCoordinateReferenceSystem::setCustomSrsValidation( savedValidation );
  *mCRS = savedCRS;

  // Abort if any error in layer, such as not found.
  if ( layerError )
  {
    return false;
  }

  // the internal name is just the data source basename
  //QFileInfo dataSourceFileInfo( mDataSource );
  //internalName = dataSourceFileInfo.baseName();

  // set ID
  mnl = layer_node.namedItem( "id" );
  if ( ! mnl.isNull() )
  {
    mne = mnl.toElement();
    if ( ! mne.isNull() && mne.text().length() > 10 ) // should be at least 17 (yyyyMMddhhmmsszzz)
    {
      mID = mne.text();
    }
  }

  // use scale dependent visibility flag
  toggleScaleBasedVisibility( element.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 );
  setMinimumScale( element.attribute( "minimumScale" ).toFloat() );
  setMaximumScale( element.attribute( "maximumScale" ).toFloat() );

  // set name
  mnl = layer_node.namedItem( "layername" );
  mne = mnl.toElement();
  setLayerName( mne.text() );

  //title
  QDomElement titleElem = layer_node.firstChildElement( "title" );
  if ( !titleElem.isNull() )
  {
    mTitle = titleElem.text();
  }

  //abstract
  QDomElement abstractElem = layer_node.firstChildElement( "abstract" );
  if ( !abstractElem.isNull() )
  {
    mAbstract = abstractElem.text();
  }

  //read transparency level
  QDomNode transparencyNode = layer_node.namedItem( "transparencyLevelInt" );
  if ( ! transparencyNode.isNull() )
  {
    // set transparency level only if it's in project
    // (otherwise it sets the layer transparent)
    QDomElement myElement = transparencyNode.toElement();
    setTransparency( myElement.text().toInt() );
  }

  readCustomProperties( layer_node );

  return true;
} // void QgsMapLayer::readXML
void EMailThread::send() {
  QStringList listTo;
  QString mQuery;
  KIO::MetaData slaveConfig;
  KURL destination;
  int i, count;

  _sendOk = false;

  KIO::Scheduler::connect(SIGNAL(slaveError(KIO::Slave *, int, const QString &)), this,
                            SLOT(slaveError(KIO::Slave *, int, const QString &)));

  _strBody.insert( 0, QString("Subject:%1\n\n").arg(_strSubject).latin1());
  _strBody.insert( 0, QString("To:%1\n").arg(_strTo).latin1());

  _bodyOffset = 0;
  _bodyLength = _strBody.length();

  mQuery  = "headers=0&from=";
  mQuery += KURL::encode_string(_strFrom);
  listTo = QStringList::split(QRegExp("[ ,;]"), _strTo);
  count = listTo.count();
  if (count > 0) {
    for (i=0; i<count; i++) {
      mQuery += "&to=";
      mQuery += KURL::encode_string(listTo[i]);
    }
  } else {
    mQuery += "&to=";
    mQuery += KURL::encode_string(_strTo);
  }

  mQuery += "&size=";
  mQuery += QString::number(_bodyLength);

  if (_encryption == EMailEncryptionSSL) {
    destination.setProtocol("smtps");
  } else {
    destination.setProtocol("smtp");
  }
  destination.setHost(_strSMTPServer);
  destination.setPort((short)_iPort);
  destination.setPath("/send");
  destination.setQuery(mQuery);

  if (_useAuthentication) {
    destination.setUser(_strUsername);
    destination.setPass(_strPassword);
  }

  if (_encryption == EMailEncryptionTLS) {
    slaveConfig.insert("tls", "on");
  } else {
    slaveConfig.insert("tls", "off");
  }
  if (_useAuthentication) {
    switch (_authentication) {
      case EMailAuthenticationPLAIN:
        slaveConfig.insert("sasl", "PLAIN");
        break;
      case EMailAuthenticationLOGIN:
        slaveConfig.insert("sasl", "LOGIN");
        break;
      case EMailAuthenticationCRAMMD5:
        slaveConfig.insert("sasl", "CRAM-MD5");
        break;
      case EMailAuthenticationDIGESTMD5:
        slaveConfig.insert("sasl", "DIGEST-MD5");
        break;
      default:
        slaveConfig.insert("sasl", "PLAIN");
        break;
    }
  }
  _slave = KIO::Scheduler::getConnectedSlave(destination, slaveConfig);
  if (_slave) {
    _job = KIO::put(destination, -1, false, false, false);
    if (_job) {
      _job->addMetaData("lf2crlf+dotstuff", "slave");
      connect(_job, SIGNAL(result(KIO::Job *)), this, SLOT(result(KIO::Job *)));
      connect(_job, SIGNAL(dataReq(KIO::Job *, QByteArray &)), this, SLOT(dataReq(KIO::Job *, QByteArray &)));
      KIO::Scheduler::assignJobToSlave(_slave, _job);
      _sendOk = true;
    }
  }
}
Пример #26
0
bool QgsMapLayer::writeXML( QDomNode & layer_node, QDomDocument & document )
{
  // general layer metadata
  QDomElement maplayer = document.createElement( "maplayer" );

  // use scale dependent visibility flag
  maplayer.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 );
  maplayer.setAttribute( "minimumScale", QString::number( minimumScale() ) );
  maplayer.setAttribute( "maximumScale", QString::number( maximumScale() ) );

  // ID
  QDomElement layerId = document.createElement( "id" );
  QDomText layerIdText = document.createTextNode( id() );
  layerId.appendChild( layerIdText );

  maplayer.appendChild( layerId );

  // data source
  QDomElement dataSource = document.createElement( "datasource" );

  QString src = source();

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  // TODO: what about postgres, mysql and others, they should not go through writePath()
  if ( vlayer && vlayer->providerType() == "spatialite" )
  {
    QgsDataSourceURI uri( src );
    QString database = QgsProject::instance()->writePath( uri.database() );
    uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() );
    src = uri.uri();
  }
  else if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = src.split( "|" );
    theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0] );
    src = theURIParts.join( "|" );
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( src.toAscii() );
    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    src = QString::fromAscii( urlDest.toEncoded() );
  }
  else
  {
    src = QgsProject::instance()->writePath( src );
  }

  QDomText dataSourceText = document.createTextNode( src );
  dataSource.appendChild( dataSourceText );

  maplayer.appendChild( dataSource );


  // layer name
  QDomElement layerName = document.createElement( "layername" );
  QDomText layerNameText = document.createTextNode( name() );
  layerName.appendChild( layerNameText );

  // layer title
  QDomElement layerTitle = document.createElement( "title" ) ;
  QDomText layerTitleText = document.createTextNode( title() );
  layerTitle.appendChild( layerTitleText );

  // layer abstract
  QDomElement layerAbstract = document.createElement( "abstract" );
  QDomText layerAbstractText = document.createTextNode( abstract() );
  layerAbstract.appendChild( layerAbstractText );

  maplayer.appendChild( layerName );
  maplayer.appendChild( layerTitle );
  maplayer.appendChild( layerAbstract );

  // timestamp if supported
  if ( timestamp() > QDateTime() )
  {
    QDomElement stamp = document.createElement( "timestamp" );
    QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) );
    stamp.appendChild( stampText );
    maplayer.appendChild( stamp );
  }

  maplayer.appendChild( layerName );

  // zorder
  // This is no longer stored in the project file. It is superfluous since the layers
  // are written and read in the proper order.

  // spatial reference system id
  QDomElement mySrsElement = document.createElement( "srs" );
  mCRS->writeXML( mySrsElement, document );
  maplayer.appendChild( mySrsElement );

  // <transparencyLevelInt>
  QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" );
  QDomText    transparencyLevelIntText    = document.createTextNode( QString::number( getTransparency() ) );
  transparencyLevelIntElement.appendChild( transparencyLevelIntText );
  maplayer.appendChild( transparencyLevelIntElement );
  // now append layer node to map layer node

  layer_node.appendChild( maplayer );

  writeCustomProperties( maplayer, document );

  return writeXml( maplayer, document );

} // bool QgsMapLayer::writeXML
static bool fillSubject(QStringList splittedStudent, int studentId, int groupId,
                        int offset, QString subject) {
  bool ok = true;
  if (!splittedStudent.at(offset).simplified().isEmpty()) {
    // fill first attestation
    int evaluationId = getEvaluationId(subject, "Аттестация", QString(),
                                       groupId, QString());
    ok = fillMark(evaluationId, studentId,
                  getMark(splittedStudent.at(offset).simplified(),
                          splittedStudent.at(0) + "FA"),
                  0, QString());
  }
  if (ok && !splittedStudent.at(offset + 1).simplified().isEmpty()) {
    // fill second attestation
    // custom date to differ it from first attestation
    int evaluationId = getEvaluationId(subject, "Аттестация", QString(),
                                       groupId, "02.01.1970");
    ok = fillMark(evaluationId, studentId,
                  getMark(splittedStudent.at(offset + 1).simplified(),
                          splittedStudent.at(0) + "SA"),
                  0, QString());
  }
  if (ok && !splittedStudent.at(offset + 2).simplified().isEmpty()) {
    // fill exam
    // or main attestation
    int evaluationId = getEvaluationId(subject, "Экзамен",
                                       splittedStudent.at(offset + 3),
                                       groupId, splittedStudent.at(offset + 4));
    ok = fillMark(evaluationId, studentId,
                  getMark(splittedStudent.at(offset + 2).simplified(),
                          splittedStudent.at(0) + "MA"),
                  0, QString());
  }
  if (ok && (splittedStudent.at(offset + 5).simplified() == "True" ||
             splittedStudent.at(offset + 5).simplified() == "1") &&
      !splittedStudent.at(offset + 2).simplified().isEmpty()) {
    // fill exam retaking
    int evaluationId = getEvaluationId(subject, "Экзамен",
                                       splittedStudent.at(offset + 7),
                                       groupId,
                                       splittedStudent.at(offset + 6));
    ok = fillMark(evaluationId, studentId,
                  getMark(splittedStudent.at(offset + 2).simplified(),
                          splittedStudent.at(0) + "ER"),
                  0, QString());
  }
  return ok;
}
QStringList Vehicle::getResources()
{
	QStringList resources;
	resources.append(bgmInfo.location);
	return resources;
}
Пример #29
0
MtpFilter::~MtpFilter() {

    if(!obsolete) {
	QDomElement child = DomUtil::elementByPath(*m_dom,"/filters");
	if(!child.isNull()) child.parentNode().removeChild(child);
    }

    QStringList filters;

    for (std::vector<GlobalFilter*>::iterator it = global.begin(); it != global.end(); ++it) {
	if(!obsolete) {
	    QString name((*it)->getName());
	    DomUtil::writeBoolEntry(*m_dom,"/filters/" + name + "/active",(*it)->isEnabled());
	    DomUtil::writeIntEntry(*m_dom,"/filters/" + name + "/policy",(*it)->policy());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/result",(*it)->getResultPattern());
	    filters << name;
	}
        delete *it;
    }
    if(!obsolete) {
	DomUtil::writeListEntry(*m_dom,"/general/filters/global","filter",filters);
	filters.clear();
    }

    for (std::vector<BlockFilter*>::iterator it = block.begin(); it != block.end(); ++it) {
	if(!obsolete) {
	    QString name((*it)->getName());
	    DomUtil::writeBoolEntry(*m_dom,"/filters/" + name + "/active",(*it)->isEnabled());
	    DomUtil::writeIntEntry(*m_dom,"/filters/" + name + "/policy",(*it)->policy());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/result",(*it)->getResultPattern());
        DomUtil::writeEntry(*m_dom,"/filters/" + name + "/beginresult",(*it)->getBeginPattern());
        DomUtil::writeEntry(*m_dom,"/filters/" + name + "/endresult",(*it)->getEndPattern());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/begin",(*it)->getBeginRegExp());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/main",(*it)->getMainRegExp());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/end",(*it)->getEndRegExp());
	    if((*it)->getInputDependency())
		DomUtil::writeEntry(*m_dom,"/filters/" + name + "/depend",(*it)->getInputDependency()->getName());
	    filters << name;
	}
        delete *it;
    }
    if(!obsolete) {
	DomUtil::writeListEntry(*m_dom,"/general/filters/block","filter",filters);
	filters.clear();
    }

    for (std::vector<LineFilter*>::iterator it = line.begin(); it != line.end(); ++it) {
	if(!obsolete) {
	    QString name((*it)->getName());
	    DomUtil::writeBoolEntry(*m_dom,"/filters/" + name + "/active",(*it)->isEnabled());
	    DomUtil::writeIntEntry(*m_dom,"/filters/" + name + "/policy",(*it)->policy());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/result",(*it)->getResultPattern());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/regexp",(*it)->getRegExp());
	    filters << name;
	}
        delete *it;
    }
    if(!obsolete) {
	DomUtil::writeListEntry(*m_dom,"/general/filters/line","filter",filters);
	filters.clear();
    }

    for (std::vector<ItemFilter*>::iterator it = item.begin(); it != item.end(); ++it) {
	if(!obsolete) {
	    QString name((*it)->getName());
	    DomUtil::writeBoolEntry(*m_dom,"/filters/" + name + "/active",(*it)->isEnabled());
	    DomUtil::writeIntEntry(*m_dom,"/filters/" + name + "/policy",(*it)->policy());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/result",(*it)->getResultPattern());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/regexp",(*it)->getRegExp());
	    filters << name;
	}
        delete *it;
    }
    if(!obsolete) {
	DomUtil::writeListEntry(*m_dom,"/general/filters/item","filter",filters);
	filters.clear();
    }

    for (std::vector<InputFilter*>::iterator it = input.begin(); it != input.end(); ++it) {
	if(!obsolete) {
	    QString name((*it)->getName());
	    DomUtil::writeBoolEntry(*m_dom,"/filters/" + name + "/active",(*it)->isEnabled());
	    DomUtil::writeIntEntry(*m_dom,"/filters/" + name + "/policy",(*it)->policy());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/result",(*it)->getResultPattern());
	    DomUtil::writeEntry(*m_dom,"/filters/" + name + "/regexp",(*it)->getRegExp());
	    DomUtil::writeBoolEntry(*m_dom,"/filters/" + name + "/memorize",(*it)->memorize());
	    filters << name;
	}
        delete *it;
    }
    if(!obsolete) {
	DomUtil::writeListEntry(*m_dom,"/general/filters/input","filter",filters);
	filters.clear();
    }
}
Пример #30
-1
bool FileServerHandler::HandleDownloadFile(SocketHandler *socket,
                                           QStringList &slist)
{
    QStringList res;

    if (slist.size() != 4)
    {
        res << "ERROR" << QString("Bad %1 command").arg(slist[0]);
        socket->SendStringList(res);
        return true;
    }

    bool synchronous = (slist[0] == "DOWNLOAD_FILE_NOW");
    QString srcURL = slist[1];
    QString storageGroup = slist[2];
    QString filename = slist[3];
    StorageGroup sgroup(storageGroup, gCoreContext->GetHostName(), false);
    QString outDir = sgroup.FindNextDirMostFree();
    QString outFile;
    QStringList retlist;

    if (filename.isEmpty())
    {
        QFileInfo finfo(srcURL);
        filename = finfo.fileName();
    }

    if (outDir.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Unable to determine directory "
                "to write to in %1 write command").arg(slist[0]));
        res << "ERROR" << "downloadfile_directory_not_found";
        socket->SendStringList(res);
        return true;
    }

    if ((filename.contains("/../")) ||
        (filename.startsWith("../")))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("ERROR: %1 write "
                "filename '%2' does not pass sanity checks.")
                .arg(slist[0]).arg(filename));
        res << "ERROR" << "downloadfile_filename_dangerous";
        socket->SendStringList(res);
        return true;
    }

    outFile = outDir + "/" + filename;

    if (synchronous)
    {
        if (GetMythDownloadManager()->download(srcURL, outFile))
        {
            res << "OK"
                << gCoreContext->GetMasterHostPrefix(storageGroup)
                       + filename;
        }
        else
            res << "ERROR";
    }
    else
    {
        QMutexLocker locker(&m_downloadURLsLock);
        m_downloadURLs[outFile] =
            gCoreContext->GetMasterHostPrefix(storageGroup) +
            StorageGroup::GetRelativePathname(outFile);

        GetMythDownloadManager()->queueDownload(srcURL, outFile, this);
        res << "OK"
            << gCoreContext->GetMasterHostPrefix(storageGroup) + filename;
    }

    socket->SendStringList(res);
    return true;
}