Esempio n. 1
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;

    //citanie vstupneho suboru
    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")
            {

            } else
            {
                QString edgeName = words[0];
                QString srcNodeName = words[1];
                QString dstNodeName = words[2];

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

                //vytvorenie koncoveho uzla
                if (!readNodes.contains(dstNodeName))
                {
                    node2 = context.getGraph ().addNode(dstNodeName, nodeType);
                    readNodes.addNode(dstNodeName, node2);
                } else {
                    node2=readNodes.get(dstNodeName);
                }
                //vytvorenie celej hyperhrany
                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);
                }

                //pridanie hyperhrany do grafu
                context.getGraph ().addEdge (QString (""), hyperEdgeNode, node2, edgeType, true);
            }
        }

    }

    return true;
}
Esempio n. 2
0
// This function will be called only once.
static const FontSets &getPreferedFontSets() {
  static FontSets font_sets;
  const QString &res_path = getPath(RESOURCE);

  QString filename = res_path + "default_font.conf";

  if (!QFile::exists(filename)) {
    filename = res_path + "/dict/" + "default_font.conf";
  }


  QFile file(filename);
  if (!file.open(QIODevice::ReadOnly)) {
    FQ_TRACE("font", 0) << "Failed to open the default font configurations file:"
                        << filename;
    return font_sets;
  }

  QTextStream is;
  is.setDevice(&file);
  is.setCodec(QTextCodec::codecForName("UTF-8"));

#if defined(WIN32)
  QString expected_section = "Windows";
#elif defined(__APPLE__)
  QString expected_section = "Apple";
#else
  QString expected_section = "Linux";
#endif

  QString line;

  QString current_section;
  while (!is.atEnd()) {
    line = is.readLine().trimmed();
    if (line.isEmpty() || line[0] == '#') {
      continue;
    }

    if (line.left(1) == "[" && line.right(1) == "]") {
      current_section = line.mid(1, line.length() - 2);
      continue;
    }

    if (current_section == expected_section) {
      QString en_font = line.section('=', 0, 0).trimmed().toLower();
      QString fonts_for_lang = line.section('=', 1).trimmed();

      map<Font::Language, QStringList> &font_set = font_sets[en_font];

      QString lang = fonts_for_lang.section(":", 0, 0).trimmed();
      QString fonts = fonts_for_lang.section(":", 1).trimmed();

      QStringList font_list = fonts.split(",", QString::SkipEmptyParts);

      for (int i = 0; i < font_list.size(); ++i) {
        font_list[i] = font_list[i].trimmed();
      }

      font_set[Font::getLanguageByName(lang)] = font_list;
    }
  }

  return font_sets;
}
bool FASTADocParser::parse(DesignerModelComponent* model, QTextStream& fin)
{
    QScriptValue FASTAs=model->getEngine()->newArray();
    model->getEngine()->globalObject().setProperty("model",FASTAs);
    int c=0,p=0;


        QScriptValue content;
        QScriptValue newFASTA;
        QScriptValue partregisty;
        QString tsq="";


        while(!fin.atEnd())
        {
            QString line=fin.readLine();
            if(line.startsWith(">"))
            {
                if(newFASTA.property("part_name").toString()!="")
                {
                    partregisty.setProperty("partsequence",DesignerPartDocParser::generateSequence(tsq));                    
                    newFASTA.setProperty("part_length",DesignerPartDocParser::generateSequence(tsq).length());
                    newFASTA.setProperty("content",content);
                    FASTAs.setProperty(p,partregisty);
                    partregisty.setProperty("*partsregistry.org*",newFASTA);
                    p++;
                }
                newFASTA = model->getEngine()->newObject();
                partregisty=model->getEngine()->newObject();
                content=model->getEngine()->newArray();
                tsq="";c=0;

                {
                    int t=line.indexOf("acc=",0);
                    if(t>0)
                        newFASTA.setProperty("part_name",line.mid(t+4,line.indexOf("|",t)-t-4).trimmed());
                    t=line.indexOf("descr=",0);
                    if(t>0)
                        newFASTA.setProperty("part_descr",line.mid(t+6,line.indexOf("|",t)-t-6).trimmed());
                    t=line.indexOf("type=",0);
                    if(t>0)
                        newFASTA.setProperty("part_type",line.mid(t+5,line.indexOf("|",t)-t-5).trimmed());
                    else if(t==-1)
                        newFASTA.setProperty("part_type","other");
                }
                if(line.indexOf("=")==-1)
                {
                    int t=1;
                    newFASTA.setProperty("part_name",this->readWord(line,t));
                    newFASTA.setProperty("part_status",this->readWord(line,t));
                    newFASTA.setProperty("part_id",this->readWord(line,t));
                    newFASTA.setProperty("part_type",this->readWord(line,t));
                    t=line.indexOf('"');
                    newFASTA.setProperty("part_descr",line.mid(t+1,line.indexOf('"',t+1)-t-1).trimmed());
                }
            }
            else
                tsq+=line;
            if(fin.atEnd())
            {
                if(!newFASTA.isNull())
                {                    
                    partregisty.setProperty("partsequence",DesignerPartDocParser::generateSequence(tsq));                    
                    newFASTA.setProperty("part_length",DesignerPartDocParser::generateSequence(tsq).length());
                    newFASTA.setProperty("content",content);
                    FASTAs.setProperty(p,partregisty);
                    partregisty.setProperty("*partsregistry.org*",newFASTA);
                }
            }
            if(!line.isEmpty())
            {
                content.setProperty(c,line);
                c++;
            }
        }


        if(FASTAs.property("length").toInteger()==0)
            return false;
        else
            return true;
}
Esempio n. 4
0
bool Loader::loadGlyphset()
{
    QString glyphsetname = m_fileName.path();
    QFile glyphsetfile( glyphsetname );
    if ( !glyphsetfile.open( QIODevice::ReadOnly ) )
    {
        qCritical( "glyphset file unreadable" );
    }
    QTextStream gts( &glyphsetfile );
    //TODO: Will windows have a problem with this?
    QString trunk = QFileInfo( glyphsetname ).path();

    //glyphsetfile has three lines: 1: nifti (skip), 2: surfaceset(s), 3: connectivity matrix

    //1: TODO: skip nifti for now
    QString gnl = gts.readLine();
    qDebug() << "skipping: " << gnl;

    //2: load surfaceset
    gnl = gts.readLine();
    QStringList datasetNames = gnl.split( " " );
    bool two = ( datasetNames.length() > 1 );
    QString datasetName = datasetNames.at( 0 );

    gnl = gts.readLine();
    QStringList sl2 = gnl.split( " " );

    QString connectivityName;
    if ( sl2.at( 0 ).startsWith( "http" ) )
    {
        connectivityName = sl2.at( 0 );
    }
    else
    {
        connectivityName = trunk + QDir::separator() + sl2.at( 0 );
    }
    float mt = 0.8;
    if ( sl2.length() > 1 )
    {
        mt = sl2.at( 1 ).toFloat();
        qDebug() << "minimum threshold: " << mt;
    }
    else
    {
        qDebug() << "no minimum threshold in glyphset file, default of " << mt << " used.";
    }
    float maxt = 1.0;
    if ( sl2.length() > 2 )
    {
        maxt = sl2.at( 2 ).toFloat();
    }

    DatasetGlyphset* dataset = new DatasetGlyphset( glyphsetname, mt, maxt );

    qDebug() << "loading glyph set: " << datasetName;
    if ( two )
    {
        qDebug() << "...and loading glyph set: " << datasetNames.at( 1 );
        if ( datasetNames.length() > 2 )
        {
            qCritical() << "only two hemispheres supported";
        }
    }

    QFile setfile( trunk + QDir::separator() + datasetName );
    if ( !setfile.open( QIODevice::ReadOnly ) )
    {
        qCritical( "set file unreadable" );
    }
    QTextStream ts( &setfile );
    QString nl;

    QString onl;
    QTextStream* ots;
    std::vector<QString> others;
    if ( two )
    {
        QFile othersetfile( trunk + QDir::separator() + datasetNames.at( 1 ) );
        if ( !othersetfile.open( QIODevice::ReadOnly ) )
        {
            qCritical( "second set file unreadable" );
        }
        ots = new QTextStream( &othersetfile );
        qDebug() << "ots initialized";
        while ( !ots->atEnd() )
        {
            onl = ots->readLine();
            others.push_back( onl );
        }

    }

    int k = 0;
    while ( !ts.atEnd() )
    {
        nl = ts.readLine();
        qDebug() << "!" << nl;
        if ( two )
        {
            onl = others.at( k );
            qDebug() << onl;
            k++;
        }

        //For commenting out stuff in the setfiles
        if ( !nl.startsWith( "#" ) )
        {
            QStringList sl = nl.split( " " );
            QString fullname = trunk + QDir::separator() + sl.at( 0 );

            LoaderFreesurfer lf;

            if ( !lf.loadASC( fullname ) )
            {
                qCritical() << "unable to load: " << fullname;
                return false;
            }

            float x = 0;
            float y = 0;
            float z = 0;
            if ( sl.length() > 1 )
                x = sl.at( 1 ).toFloat();
            if ( sl.length() > 2 )
                y = sl.at( 2 ).toFloat();
            if ( sl.length() > 3 )
                z = sl.at( 3 ).toFloat();
            QVector3D s( x, y, z );
            std::vector<float>* points = lf.getPoints();
            std::vector<int> triangles = lf.getTriangles();
            int numPoints = points->size() / 3;
            int numTriangles = triangles.size() / 3;

            int onumPoints = 0;
            int onumTriangles = 0;
            std::vector<float>* opoints = new std::vector<float>();
            std::vector<int> otriangles;
            QVector3D* os = new QVector3D( 0, 0, 0 );
            LoaderFreesurfer olf;
            if ( two )
            {
                QStringList osl;
                osl = onl.split( " " );
                QString ofullname = trunk + QDir::separator() + osl.at( 0 );

                if ( !olf.loadASC( ofullname ) )
                {
                    qCritical() << "unable to load: " << ofullname;
                    return false;
                }
                float ox = 0;
                float oy = 0;
                float oz = 0;

                if ( osl.length() > 1 )
                    ox = osl.at( 1 ).toFloat();
                if ( osl.length() > 2 )
                    oy = osl.at( 2 ).toFloat();
                if ( osl.length() > 3 )
                    oz = osl.at( 3 ).toFloat();

                os = new QVector3D( ox, oy, oz );
                opoints = olf.getPoints();
                otriangles = olf.getTriangles();
                onumPoints = opoints->size() / 3;
                onumTriangles = otriangles.size() / 3;
            }

            TriangleMesh2* mesh = new TriangleMesh2( numPoints + onumPoints, numTriangles + onumTriangles );

            for ( int i = 0; i < numPoints; ++i )
            {
                mesh->addVertex( points->at( i * 3 ) + s.x(), points->at( i * 3 + 1 ) + s.y(), points->at( i * 3 + 2 ) + s.z() );
            }
            for ( int i = 0; i < numTriangles; ++i )
            {
                //TODO: Check orientation change (0,2,1)...
                mesh->addTriangle( triangles[i * 3], triangles[i * 3 + 2], triangles[i * 3 + 1] );
            }

            if ( two )
            {
                dataset->m_tris_middle = numTriangles;
                dataset->m_points_middle = numPoints;
                dataset->m_is_split = true;

                for ( int i = 0; i < onumPoints; ++i )

                {
                    mesh->addVertex( opoints->at( i * 3 ) + os->x(), opoints->at( i * 3 + 1 ) + os->y(), opoints->at( i * 3 + 2 ) + os->z() );
                }
                for ( int i = 0; i < onumTriangles; ++i )
                {
                    //TODO: Check orientation change (0,2,1)...
                    mesh->addTriangle( otriangles[i * 3] + onumPoints, otriangles[i * 3 + 2] + onumPoints, otriangles[i * 3 + 1] + onumPoints );
                }
            }

            mesh->finalize();

            dataset->addMesh( mesh, sl.at( 0 ) );
        }
    }

    //fourth thing on the line: name of roi...
    //no roi: initialize all nodes true
    dataset->initROI();
    if ( sl2.length() > 3 )
    {

        QString roiname = trunk + QDir::separator() + sl2.at( 3 );
        qDebug() << "loading ROI: " << roiname;
        dataset->loadROI( roiname, dataset->roi );
        if ( sl2.length() > 4 )
        {
            QString roiname2 = trunk + QDir::separator() + sl2.at( 4 );
            qDebug() << "loading ROI2: " << roiname2;
            dataset->loadROI( roiname2, dataset->roi2 );
        }
    }

    //3: load connectivity
    qDebug() << "loading connectivity";
    dataset->readConnectivity( connectivityName );

    //TODO: init conn.-crap...
    //dataset->setMinthresh( mt );

    dataset->setProperties();
    dataset->addSecondSurfaceSelector();
    m_dataset.push_back( dataset );

    return true;
}
Esempio n. 5
0
Mesh *loadOBJ(
    const char * path,
    std::string objectName
){
    Mesh *out = new Mesh();
    qDebug("Loading OBJ file %s", path);

    std::vector<unsigned short> vertexIndices, uvIndices, normalIndices;
	std::vector<glm::vec3> temp_vertices; 
	std::vector<glm::vec2> temp_uvs;
	std::vector<glm::vec3> temp_normals;

    QFile file(path);
    if (!file.open (QIODevice::ReadOnly)) qDebug("File %s not found", path);
    QTextStream stream ( &file );
    char *line;
    char currentObjectName[128] = "";

    bool foundObjectName = !objectName.size()?true:false;
    bool progressObject = !objectName.size()?true:false;

    while( !stream.atEnd() ) {
        line = NoLimitsRenderer::toChar(stream.readLine());
        char lineHeader[128];
        char tmps[128];
        sscanf(line, "%s", &lineHeader);

        if ( objectName.size() && strcmp( lineHeader, "o" ) == 0 ){
            sscanf(line, "%s %s\n", &tmps, &currentObjectName);


            QRegExp rx(objectName.c_str());
            if (rx.indexIn(std::string(currentObjectName).c_str()) < 0) progressObject = false;
            else progressObject = foundObjectName = true;
            continue;
        }

        if ( strcmp( lineHeader, "v" ) == 0 ){
            glm::vec3 vertex;
            sscanf(line, "%s %f %f %f\n", &tmps, &vertex.x, &vertex.y, &vertex.z);
            temp_vertices.push_back(vertex);
        } else if ( strcmp( lineHeader, "vt" ) == 0 ){
            glm::vec2 uv;
            sscanf(line, "%s %f %f\n", &tmps, &uv.x, &uv.y );
            //uv.y = -uv.y; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders.
            temp_uvs.push_back(uv);
        } else if ( strcmp( lineHeader, "vn" ) == 0 ){
            glm::vec3 normal;
            sscanf(line, "%s %f %f %f\n", &tmps, &normal.x, &normal.y, &normal.z );
            temp_normals.push_back(normal);
        }

        if(!progressObject) continue;

        if ( strcmp( lineHeader, "f" ) == 0 ){
            unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
            int matches = sscanf(line, "%s %d/%d/%d %d/%d/%d %d/%d/%d\n", &tmps, &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2] );

            if (matches != 10){
                qDebug("File can't be read by our simple parser :-( Try exporting with other options\n");
                return out;
            }
            vertexIndices.push_back(vertexIndex[0]);
            vertexIndices.push_back(vertexIndex[1]);
            vertexIndices.push_back(vertexIndex[2]);
            uvIndices    .push_back(uvIndex[0]);
            uvIndices    .push_back(uvIndex[1]);
            uvIndices    .push_back(uvIndex[2]);
            normalIndices.push_back(normalIndex[0]);
            normalIndices.push_back(normalIndex[1]);
            normalIndices.push_back(normalIndex[2]);
        }
    }
    file.close(); // when your done.

    if(!foundObjectName) return out;

	// For each vertex of each triangle
    for( unsigned int i=0; i<vertexIndices.size(); i++ ){

		// Get the indices of its attributes
		unsigned int vertexIndex = vertexIndices[i];
		unsigned int uvIndex = uvIndices[i];
		unsigned int normalIndex = normalIndices[i];
		
		// Get the attributes thanks to the index
		glm::vec3 vertex = temp_vertices[ vertexIndex-1 ];
		glm::vec2 uv = temp_uvs[ uvIndex-1 ];
		glm::vec3 normal = temp_normals[ normalIndex-1 ];

        out->addVertex(vertex, normal, uv);
    }

    return out;
}
Esempio n. 6
0
bool kvoctrainDoc::loadFromLex (QTextStream& is)
{

  langs.clear();
  vocabulary.clear();
  QString version,
          info1,
          s_dummy,
          title,
          f_keys,
          ident,
          orgID,
          transID;

  int     i_dummy,
          type,
          f_grade,
          t_grade,
          lesson;

  int lines = 10000000;

  version = is.readLine();
  info1 = is.readLine();
  ident = extract (info1);

  orgID = extract (info1);
  if (orgID.isEmpty())
    orgID = "original";

  transID = extract (info1);
  if (transID.isEmpty())
    transID = "translation";

  if (ident != "LEX" || version != LEX_IDENT_50) {
    errorLex (1, "invalid file format");
    return false;
  }

  // first two chars usually give language code:
  // english  ==> en
  // Deutsch  ==> de
  // italano  ==> it

  langs.push_back (orgID.left(2).lower());
  langs.push_back (transID.left(2).lower());

  QTextStream params (info1, IO_ReadOnly);
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> i_dummy;
  params >> lines;

  s_dummy = is.readLine();  // Font
  s_dummy = is.readLine();  // Font
  title = is.readLine();
  setTitle (title);
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();
  s_dummy = is.readLine();

  if (!loadTypeNameLex (is))
    return false;

  if (!loadLessonLex (is))
    return false;

  f_keys = is.readLine();

  int ent_percent = (int) lines / 100;
  float f_ent_percent = (int) lines / 100.0;
  emit progressChanged(this, 0);

  for (int i = 0; !is.eof() && i < lines; i++) {
    if (ent_percent != 0 && (i % ent_percent) == 0 ) {
      emit progressChanged(this, int(i / f_ent_percent));
    }

    is >> type;
    is >> i_dummy;
    is >> i_dummy;
    is >> i_dummy;
    is >> i_dummy;
    is >> i_dummy;
    is >> i_dummy;
    is >> i_dummy;
    is >> t_grade;
    is >> f_grade;
    is >> lesson;

    QString line = is.readLine();
    QString s;

    QString original = extract (line);
    for (int i = 0; i < 3; i++) {
      s = extract (line);
      if (!s.isEmpty())
        original += ", " +s;
    }

    QString translation = extract (line);
    for (int i = 0; i < 3; i++) {
      s = extract (line);
      if (!s.isEmpty())
        translation += ", " +s;
    }

/*  ignore rest
       >> "||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
       >> "\n";
*/
    kvoctrainExpr kve (original);
    kve.setGrade (1, t_grade, false);
    kve.setGrade (1, f_grade, true);
    kve.setLesson (lesson);
    kve.addTranslation (translation);

// FIXME: convert attribute to word type ?

    vocabulary.push_back(kve);

  }

  setModified (false);
  return is.device()->status() == IO_Ok;
}
/*!
    \internal
 */
void QWebSocketHandshakeRequest::readHandshake(QTextStream &textStream)
{
    m_isValid = false;
    clear();
    if (Q_UNLIKELY(textStream.status() != QTextStream::Ok))
        return;
    const QString requestLine = textStream.readLine();
    const QStringList tokens = requestLine.split(' ', QString::SkipEmptyParts);
    if (Q_UNLIKELY(tokens.length() < 3)) {
        m_isValid = false;
        clear();
        return;
    }
    const QString verb(tokens.at(0));
    const QString resourceName(tokens.at(1));
    const QString httpProtocol(tokens.at(2));
    bool conversionOk = false;
    const float httpVersion = httpProtocol.midRef(5).toFloat(&conversionOk);

    if (Q_UNLIKELY(!conversionOk)) {
        clear();
        m_isValid = false;
        return;
    }
    QString headerLine = textStream.readLine();
    m_headers.clear();
    while (!headerLine.isEmpty()) {
        const QStringList headerField = headerLine.split(QStringLiteral(": "),
                                                         QString::SkipEmptyParts);
        if (Q_UNLIKELY(headerField.length() < 2)) {
            clear();
            return;
        }
        m_headers.insertMulti(headerField.at(0).toLower(), headerField.at(1));
        headerLine = textStream.readLine();
    }

    const QString host = m_headers.value(QStringLiteral("host"), QString());
    m_requestUrl = QUrl::fromEncoded(resourceName.toLatin1());
    if (m_requestUrl.isRelative())
        m_requestUrl.setHost(host);
    if (m_requestUrl.scheme().isEmpty()) {
        const QString scheme =  isSecure() ? QStringLiteral("wss") : QStringLiteral("ws");
        m_requestUrl.setScheme(scheme);
    }

    const QStringList versionLines = m_headers.values(QStringLiteral("sec-websocket-version"));
    for (QStringList::const_iterator v = versionLines.begin(); v != versionLines.end(); ++v) {
        const QStringList versions = (*v).split(QStringLiteral(","), QString::SkipEmptyParts);
        for (QStringList::const_iterator i = versions.begin(); i != versions.end(); ++i) {
            bool ok = false;
            (void)(*i).toUInt(&ok);
            if (!ok) {
                clear();
                return;
            }
            const QWebSocketProtocol::Version ver =
                    QWebSocketProtocol::versionFromString((*i).trimmed());
            m_versions << ver;
        }
    }
    //sort in descending order
    std::sort(m_versions.begin(), m_versions.end(), std::greater<QWebSocketProtocol::Version>());
    m_key = m_headers.value(QStringLiteral("sec-websocket-key"), QString());
    //must contain "Upgrade", case-insensitive
    const QString upgrade = m_headers.value(QStringLiteral("upgrade"), QString());
    //must be equal to "websocket", case-insensitive
    const QString connection = m_headers.value(QStringLiteral("connection"), QString());
    const QStringList connectionLine = connection.split(QStringLiteral(","),
                                                        QString::SkipEmptyParts);
    QStringList connectionValues;
    for (QStringList::const_iterator c = connectionLine.begin(); c != connectionLine.end(); ++c)
        connectionValues << (*c).trimmed();

    //optional headers
    m_origin = m_headers.value(QStringLiteral("sec-websocket-origin"), QString());
    const QStringList protocolLines = m_headers.values(QStringLiteral("sec-websocket-protocol"));
    for (QStringList::const_iterator pl = protocolLines.begin(); pl != protocolLines.end(); ++pl) {
        QStringList protocols = (*pl).split(QStringLiteral(","), QString::SkipEmptyParts);
        for (QStringList::const_iterator p = protocols.begin(); p != protocols.end(); ++p)
            m_protocols << (*p).trimmed();
    }
    const QStringList extensionLines = m_headers.values(QStringLiteral("sec-websocket-extensions"));
    for (QStringList::const_iterator el = extensionLines.begin();
         el != extensionLines.end(); ++el) {
        QStringList extensions = (*el).split(QStringLiteral(","), QString::SkipEmptyParts);
        for (QStringList::const_iterator e = extensions.begin(); e != extensions.end(); ++e)
            m_extensions << (*e).trimmed();
    }

    //TODO: authentication field

    m_isValid = !(host.isEmpty() ||
                  resourceName.isEmpty() ||
                  m_versions.isEmpty() ||
                  m_key.isEmpty() ||
                  (verb != QStringLiteral("GET")) ||
                  (!conversionOk || (httpVersion < 1.1f)) ||
                  (upgrade.toLower() != QStringLiteral("websocket")) ||
                  (!connectionValues.contains(QStringLiteral("upgrade"), Qt::CaseInsensitive)));
    if (Q_UNLIKELY(!m_isValid))
        clear();
}
Esempio n. 8
0
void FindApiThread::run()
{
    QFile f(m_fileName);
    if (!f.open(QFile::ReadOnly)) {
        return;
    }
    QTextStream *stream = new QTextStream(&f);
    QRegExp reg("^pkg\\s([\\w\\-\\.\\/]+)(\\s\\(([\\w\\-]+)\\))?,\\s(\\w+)");
    QRegExp regm("\\(\\*?([\\w\\-]+)\\)\\s*(\\w+)");
    while (!stream->atEnd()) {
        QString line = stream->readLine();
        int pos = reg.indexIn(line);
        if (pos < 0) {
            continue;
        }
        // 1 pkgname
        // 2 ? (system)
        // 3 ? system
        // 4 const|func|method|var|type
        QString pkgName = reg.cap(1);
//        if (!reg.cap(3).isEmpty()) {
//            pkg = reg.cap(2)+"."+pkg;
//        }
//        if (!lastPkg || lastPkg->name != pkgName) {
//            lastPkg = m_pkgs.findPackage(pkgName);
//            if (!lastPkg) {
//                lastPkg = new Package(pkgName);
//                m_pkgs.pkgList.append(lastPkg);
//                lastType = 0;
//            }
//        }
        QString right = line.mid(reg.cap().length()).trimmed();
        QString findText;
        QStringList findUrl;
        QString flag = reg.cap(4);
        if (flag == "var") {
            ///pkg archive/tar, var ErrFieldTooLong error
            int pos = right.indexOf(" ");
            QString name = right.left(pos);
            if (pos != -1) {
                findText = pkgName+"."+name+" "+right.mid(pos+1);
                findUrl << pkgName+"#variables"<< name;
            }
            //if (pos != -1 && lastPkg->findValue(name) == 0) {
            //    lastPkg->valueList.append(new Value(VarApi,name,right.mid(pos+1)));
            //}
        } else if (flag == "const") {
            //pkg syscall (windows-amd64), const ECOMM Errno
            int pos = right.indexOf(" ");
            QString name = right.left(pos);
            if (pos != -1) {
                QString exp = right.mid(pos+1);
                findText = pkgName+"."+name+" "+exp;
                //if (exp.startsWith("ideal-") || exp == "uint16") {
                findUrl << pkgName+"#constants" << name;
//                } else {
//                    findUrl << pkgName+"."+name;
//                }
            }
//            if (pos != -1 && lastPkg->findValue(name) == 0) {
//                lastPkg->valueList.append(new Value(ConstApi,name,right.mid(pos+1)));
//            }
        } else if (flag == "func") {
            //pkg bytes, func FieldsFunc([]byte, func(rune) bool) [][]byte
            int pos = right.indexOf("(");
            QString name = right.left(pos);
            if (pos != -1) {
                findText = pkgName+"."+name+" "+right.mid(pos);
                findUrl << pkgName+"#"+name;
            }
//            if (pos != -1 && lastPkg->findValue(name) == 0) {
//                lastPkg->valueList.append(new Value(FuncApi,name,right.mid(pos)));
//            }
        } else if (flag == "method") {
            //pkg archive/tar, method (*Reader) Next() (*Header, error)
            //pkg archive/zip, method (*File) Open() (io.ReadCloser, error)
            //pkg bufio, method (ReadWriter) Available() int
            int pos = regm.indexIn(right);
            if (pos != -1) {
                QString typeName = regm.cap(1);
                QString name = regm.cap(2);
                QString exp = right.mid(regm.cap().length()).trimmed();
                findText = pkgName+"."+typeName+"."+name+" "+exp;
                findUrl << pkgName+"#"+typeName+"."+name;
//                if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) {
//                    lastType = lastPkg->findType(typeName);
//                    if (!lastType) {
//                        lastType = new Type(StructApi,typeName,"struct");
//                        lastPkg->typeList.append(lastType);
//                    }
//                }
//                if (lastType->findValue(name) == 0) {
//                    lastType->valueList.append(new Value(TypeMethodApi,name,exp));
//                }
            }
        } else if (flag == "type") {
            //pkg go/ast, type ObjKind int
            //pkg archive/tar, type Header struct
            //pkg archive/tar, type Header struct, AccessTime time.Time
            //pkg container/heap, type Interface interface { Len, Less, Pop, Push, Swap }
            //pkg container/heap, type Interface interface, Len() int
            int pos = right.indexOf(" ");
            if (pos != -1) {
                QString typeName = right.left(pos);
                QString exp = right.mid(pos+1);
                if (exp == "struct") {
                    findText = pkgName+"."+typeName+" "+exp;
                    findUrl << pkgName+"#"+typeName;
//                    lastType = lastPkg->findType(typeName);
//                    if (!lastType) {
//                        lastType = new Type(StructApi,typeName,exp);
//                        lastPkg->typeList.append(lastType);
//                    }
                } else if (exp.startsWith("struct,")) {
                    QString last = exp.mid(7).trimmed();
                    int pos2 = last.indexOf(" ");
                    if (pos2 != -1) {
                        findText = pkgName+"."+typeName;
//                        if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) {
//                            lastType = lastPkg->findType(typeName);
//                            if (!lastType) {
//                                lastType = new Type(StructApi,typeName,"struct");
//                                lastPkg->typeList.append(lastType);
//                            }
//                        }
                        QString name = last.left(pos2);
                        if (name == "embedded") {
                            QString emName = last.mid(pos2+1);
                            findText = pkgName+"."+typeName+"."+emName;
                            findUrl << pkgName+"#"+typeName << emName;
//                            if (!lastType->embeddedList.contains(emName)) {
//                                lastType->embeddedList.append(emName);
//                            }
                        } else {
                            findText = pkgName+"."+typeName+"."+name+" "+last.mid(pos2+1);
                            findUrl << pkgName+"#"+typeName << name;
                        }
                        /*else if (lastType->findValue(name) == 0){
                            lastType->valueList.append(new Value(TypeVarApi,name,last.mid(pos2+1)));
                        }*/
                    }
                } else if (exp.startsWith("interface {")) {
                    findText = pkgName+"."+typeName+" "+exp;
                    findUrl << pkgName+"#"+typeName;
//                    lastType = lastPkg->findType(typeName);
//                    if (!lastType) {
//                        lastType = new Type(InterfaceApi,typeName,exp);
//                        lastPkg->typeList.append(lastType);
//                    }
                } else if (exp.startsWith("interface,")) {
                    QString last = exp.mid(10).trimmed();
                    int pos2 = last.indexOf("(");
                    if (pos2 != -1) {

//                        if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) {
//                            lastType = lastPkg->findType(typeName);
//                            if (!lastType) {
//                                lastType = new Type(InterfaceApi,typeName,"struct");
//                                lastPkg->typeList.append(lastType);
//                            }
//                        }
                        QString name = last.left(pos2);
                        //if (lastType->findValue(name) == 0) {
                             findText = pkgName+"."+typeName+"."+name+" "+last.mid(pos2);
                             findUrl << pkgName+"#"+typeName+"."+name;
                             //lastType->valueList.append(new Value(TypeMethodApi,name,last.mid(pos2)));
                        //}
                    }
                } else {
                    findText = pkgName+"."+typeName+" "+exp;
                    findUrl << pkgName+"#"+typeName;
//                    lastType = lastPkg->findType(typeName);
//                    if (!lastType) {
//                        lastType = new Type(TypeApi,typeName,exp);
//                        lastPkg->typeList.append(lastType);
//                    }
                }
            }
        }
        if (findText.indexOf(m_text,0,m_bMatchCase?Qt::CaseSensitive:Qt::CaseInsensitive) >= 0) {
            emit findApiOut(findText,line,findUrl);
        }
    }
}
Esempio n. 9
0
Model::Model()
{
    this->background = new QList<Background *>;
    this->floors = new QList<Floor *>;
    this->safes = new QList<Safe*>;
    this->mushroom = new QList<Mushroom *>;
    this->golds = new QList<Gold *>;
    this->flames = new QList<Flame *>;
    this->splashScreen = new SplashScreen(330, 170, ":images/go2.png");
    this->darkEater=new QList<DarkEater *>;
    this->background = new QList<Background *>;
    this->header = new Header();
    this->compteur = new QList<Brick*> ;
    this->mysticTrees = new QList<MysticTree *>;
    this->mario = new Mario(200, 340);
    this->blood = new Blood(0,0);
    this->shock = new Shock(0,0);
    this->encart = new Encart(0,0, "");
    getEncart()->setType(EncartType::NONE);

    QFile fichier(":ModelMap.txt");

    if(fichier.open(QIODevice::ReadOnly))
    {
        QTextStream in (&fichier);
        while(!in.atEnd())
        {
            QString stock = in.readLine();
            if (stock.left(6)=="LIGNEa")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne1.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEb")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne2.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEc")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne3.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEd")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne4.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEe")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne5.append(stock.at(i));
                    }
                }
            }
            else if (stock.left(6)=="LIGNEf")
            {
                for(int i=0;i<stock.size();++i){
                    if(stock.at(i).isDigit() || stock.at(i).isLetter()){
                        ligne6.append(stock.at(i));
                    }
                }
            }
        }
        fichier.close();
    }

    for (int i=0; i<NbrBrickVisible; i++) {
        Floor *k= new Floor(i*brickSize, Hauteur-brickSize, QString(":images/floor_bottom.jpg"));
        floors->append(k);
        Floor *k2= new Floor(i*brickSize, Hauteur-2*brickSize, QString(":images/floor_grass.png"));
        floors->append(k2);
    }
    for (int i=0; i<NbrBrickVisible; i++) {
        Brick *b=new Brick(i*brickSize,Hauteur+brickSize);
        compteur->append(b);
    }
    for (int i=0; i<2; i++) {
        Background* b = new Background(i*Model::Longueur, 0);
        background->append(b);
    }
}
Esempio n. 10
0
void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, Connection conn, const QString &pgsql_ver, bool ignore_dup, bool simulate)
{
	int type_id;
	QString  version, sql_buf, sql_cmd, lin;
	Connection new_db_conn;
	unsigned i, count;
	ObjectType types[]={OBJ_ROLE, OBJ_TABLESPACE};
	BaseObject *object=nullptr;
	vector<Exception> errors;
	QTextStream ts;
	bool ddl_tk_found=false;

	/* Error codes treated in this method
			42P04 	duplicate_database
			42723 	duplicate_function
			42P06 	duplicate_schema
			42P07 	duplicate_table
			42710 	duplicate_object
			42701   duplicate_column
			42P16   invalid_table_definition

		 Reference:
			http://www.postgresql.org/docs/current/static/errcodes-appendix.html*/
	QString error_codes[]={"42P04", "42723", "42P06", "42P07", "42710", "42701", "42P16"};
	vector<QString> err_codes_vect(error_codes, error_codes + sizeof(error_codes) / sizeof(QString));

	try
	{
		if(!db_model)
			throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		/* If the export is called using ignore duplications and simulation mode at same time
		an error is raised because the simulate mode (mainly used as SQL validation) cannot
		undo column addition (this can be changed in the future) */
		if(simulate && ignore_dup)
			throw Exception(ERR_MIX_INCOMP_EXPORT_OPTS,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		connect(db_model, SIGNAL(s_objectLoaded(int,QString,uint)), this, SLOT(updateProgress(int,QString,uint)));

		export_canceled=false;
		db_created=false;
		progress=sql_gen_progress=0;
		created_objs[OBJ_ROLE]=created_objs[OBJ_TABLESPACE]=-1;
		conn.connect();

		//Retrive the DBMS version in order to generate the correct code
		version=(conn.getPgSQLVersion()).mid(0,3);

		//Overriding the DBMS version case the version is informed on parameter
		if(!pgsql_ver.isEmpty())
		{
			SchemaParser::setPgSQLVersion(pgsql_ver);
			emit s_progressUpdated(progress, trUtf8("PostgreSQL version detection overrided. Using version %1...").arg(pgsql_ver));
		}
		else
		{
			SchemaParser::setPgSQLVersion(version);
			emit s_progressUpdated(progress, trUtf8("PostgreSQL %1 server detected...").arg(version));
		}

		if(ignore_dup)
		{
			emit s_progressUpdated(progress, trUtf8("Ignoring object duplication errors..."));

			//Save the current status for ALTER command generation for table columns/constraints
			saveGenAtlerCmdsStatus(db_model);
		}

		if(simulate)
			emit s_progressUpdated(progress, trUtf8("Simulation mode activated..."));

		//Creates the roles and tablespaces separately from the other objects
		for(type_id=0; type_id < 2 && !export_canceled; type_id++)
		{
			count=db_model->getObjectCount(types[type_id]);

			for(i=0; i < count && !export_canceled; i++)
			{
				object=db_model->getObject(i, types[type_id]);
				progress=((10 * (type_id+1)) + ((i/static_cast<float>(count)) * 10));

				try
				{
					if(!object->isSQLDisabled())
					{
						//Emits a signal indicating that the object is being exported
						emit s_progressUpdated(progress,
																	 trUtf8("Creating object `%1' (%2)...").arg(Utf8String::create(object->getName())).arg(object->getTypeName()),
																	 object->getObjectType());

						sql_cmd=object->getCodeDefinition(SchemaParser::SQL_DEFINITION);
						conn.executeDDLCommand(sql_cmd);
					}
				}
				catch(Exception &e)
				{
					/* Raises an error if the object is duplicated and the ignore duplicity is not set or the error
					returned by the server is other than object duplicity */
					if(!ignore_dup ||
						 (ignore_dup &&
							std::find(err_codes_vect.begin(), err_codes_vect.end(), e.getExtraInfo())==err_codes_vect.end()))
						throw Exception(e.getErrorMessage(),
														e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, sql_cmd);
					else
						//If the object is duplicated store the error on a vector
						errors.push_back(e);
				}

				created_objs[types[type_id]]++;
			}
		}

		try
		{
			if(!db_model->isSQLDisabled() && !export_canceled)
			{
				//Creating the database on the DBMS
				emit s_progressUpdated(progress,
															 trUtf8("Creating database `%1'...").arg(Utf8String::create(db_model->getName())),
															 OBJ_DATABASE);
				sql_cmd=db_model->__getCodeDefinition(SchemaParser::SQL_DEFINITION);
				conn.executeDDLCommand(sql_cmd);
				db_created=true;
			}
		}
		catch(Exception &e)
		{
			/* Raises an error if the object is duplicated and the ignore duplicity is not set or the error
			returned by the server is other than object duplicity */
			if(!ignore_dup ||
				 (ignore_dup &&
					std::find(err_codes_vect.begin(), err_codes_vect.end(), e.getExtraInfo())==err_codes_vect.end()))
				throw Exception(e.getErrorMessage(),
												e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, sql_cmd);
			else
				errors.push_back(e);
		}

		if(!export_canceled)
		{
			//Connects to the new created database to create the other objects
			progress=20;
			new_db_conn=conn;
			new_db_conn.setConnectionParam(Connection::PARAM_DB_NAME, db_model->getName());
			emit s_progressUpdated(progress,
														 trUtf8("Connecting to database `%1'...").arg(Utf8String::create(db_model->getName())));

			new_db_conn.connect();
			progress=30;
			//Creating the other object types
			emit s_progressUpdated(progress, trUtf8("Creating objects on database `%1'...").arg(Utf8String::create(db_model->getName())));

			//Generates the sql from entire model
			sql_buf=db_model->getCodeDefinition(SchemaParser::SQL_DEFINITION, false);

			/* Extract each SQL command from the buffer and execute them separately. This is done
			 to permit the user, in case of error, identify what object is wrongly configured. */
			ts.setString(&sql_buf);
			unsigned aux_prog=0, curr_size=0, buf_size=sql_buf.size();

			progress+=(sql_gen_progress/progress);
			sql_cmd.clear();

			while(!ts.atEnd() && !export_canceled)
			{
				try
				{
					//Cleanup single line comments
					lin=ts.readLine();
					curr_size+=lin.size();
					aux_prog=progress + ((curr_size/static_cast<float>(buf_size)) * 70);

					ddl_tk_found=(lin.indexOf(ParsersAttributes::DDL_END_TOKEN) >= 0);
					lin.remove(QRegExp("^(--)+(.)+$"));

					//If the line isn't empty after cleanup it will be included on sql command
					if(!lin.isEmpty())
						sql_cmd += lin + "\n";

					//If the ddl end token is found
					if(ddl_tk_found || (!sql_cmd.isEmpty() && ts.atEnd()))
					{
						//Regexp used to extract the object being created
						QRegExp reg=QRegExp("(CREATE)(.)+(\n)", Qt::CaseSensitive);

						sql_cmd.simplified();

						//Check if the regex matches the sql command
						if(reg.exactMatch(sql_cmd))
						{
							QString obj_type, obj_name;
							QRegExp reg_aux;
							unsigned obj_id;
							ObjectType obj_types[]={ OBJ_FUNCTION, OBJ_TRIGGER, OBJ_INDEX,
																			 OBJ_RULE,	OBJ_TABLE, OBJ_VIEW, OBJ_DOMAIN,
																			 OBJ_SCHEMA,	OBJ_AGGREGATE, OBJ_OPFAMILY,
																			 OBJ_OPCLASS, OBJ_OPERATOR,  OBJ_SEQUENCE,
																			 OBJ_CONVERSION, OBJ_CAST,	OBJ_LANGUAGE,
																			 OBJ_COLLATION, OBJ_EXTENSION, OBJ_TYPE };
							unsigned count=sizeof(obj_types)/sizeof(ObjectType);
							int pos=0;

							//Get the fisrt line of the sql command, that contains the CREATE ... statement
							lin=sql_cmd.mid(0, sql_cmd.indexOf('\n'));

							for(obj_id=0; obj_id < count; obj_id++)
							{
								//Check if the keyword for the current object exists on string
								reg_aux.setPattern(QString("(CREATE)(.)*(%1)%2")
																	 .arg(BaseObject::getSQLName(obj_types[obj_id]))
																	 .arg(obj_types[obj_id]==OBJ_INDEX ? "( )*(CONCURRENTLY)?" : ""));
								pos=reg_aux.indexIn(lin);

								if(pos >= 0)
								{
									//Extracts from the line the string starting with the object's name
									lin=lin.mid(reg_aux.matchedLength(), sql_cmd.indexOf('\n')).simplified();

									//Stores the object type name
									obj_type=BaseObject::getTypeName(obj_types[obj_id]);

									if(obj_types[obj_id]!=OBJ_CAST)
									{
										//The object name is the first element when splitting the string with space separator
										obj_name=lin.split(' ').at(0);
										obj_name.remove('(');
									}
									else
									{
										obj_name="cast" + lin.replace(" AS ",",");
									}

									obj_name.remove(';');
									break;
								}
							}

							emit s_progressUpdated(aux_prog,
																		 trUtf8("Creating object `%1' (%2)...").arg(obj_name).arg(obj_type),
																		 obj_types[obj_id]);
						}
						else
							//General commands like alter / set aren't explicitly shown
							emit s_progressUpdated(aux_prog, trUtf8("Executing auxiliary command..."));

						//Executes the extracted SQL command
						if(!sql_cmd.isEmpty())
							new_db_conn.executeDDLCommand(sql_cmd);

						sql_cmd.clear();
						ddl_tk_found=false;
					}
				}
				catch(Exception &e)
				{
					if(ddl_tk_found) ddl_tk_found=false;

					if(!ignore_dup ||
						 (ignore_dup &&
							std::find(err_codes_vect.begin(), err_codes_vect.end(), e.getExtraInfo())==err_codes_vect.end()))
						throw Exception(Exception::getErrorMessage(ERR_EXPORT_FAILURE).arg(Utf8String::create(sql_cmd)),
														ERR_EXPORT_FAILURE,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, sql_cmd);
					else
					{
						sql_cmd.clear();
						errors.push_back(e);
						sleepThread(10);
					}
				}
			}
		}

		disconnect(db_model, nullptr, this, nullptr);

		if(ignore_dup)
			restoreGenAtlerCmdsStatus();

		//Closes the new opened connection
		if(new_db_conn.isStablished()) new_db_conn.close();

		/* If the process was a simulation or even canceled undo the export
		removing the created objects */
		if(simulate || export_canceled)
			undoDBMSExport(db_model, conn);

		if(conn.isStablished())
			conn.close();

		if(!export_canceled)
			emit s_exportFinished();
		else
			emit s_exportCanceled();

		sleepThread(20);
	}
	catch(Exception &e)
	{
		disconnect(db_model, nullptr, this, nullptr);

		if(ignore_dup)
			restoreGenAtlerCmdsStatus();

		try
		{
			//Closes the new opened connection
			if(new_db_conn.isStablished()) new_db_conn.close();

			//Undo the export removing the created objects
			undoDBMSExport(db_model, conn);
		}
		catch(Exception &){}

		if(conn.isStablished())	conn.close();

		/* When running in a separated thread (other than the main application thread)
		redirects the error in form of signal */
		if(this->thread() && this->thread()!=qApp->thread())
		{
			errors.push_back(e);
			emit s_exportAborted(Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, errors));
		}
		else
		{
			//Redirects any error to the user
			if(errors.empty())
				throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
			else
			{
				errors.push_back(e);
				throw Exception(e.getErrorMessage(),__PRETTY_FUNCTION__,__FILE__,__LINE__, errors);
			}
		}
	}
}
Esempio n. 11
0
void cleanupXML(QTextStream &input, QTextStream &output) {
	QRegExp
		filenameRegExp("filename=\"[^\"]*\""),
		nameRegExp("name=\"[^\"]*\""),
		tagRegExp("^\\s*<([a-zA-Z]+) "),
		leadingSpaces("^ *"),
		closeTag("^\\s*</");
	bool inComment = false, hasContents = false;

	while (!input.atEnd()) {
		QString line = input.readLine();
		bool startComment = line.contains("<!--");
		bool endComment = line.contains("-->");

		if (startComment)
			inComment = true;
		if (endComment)
			inComment = false;

		if (inComment || endComment) {
			if (startComment) {
				/* Turn leading spaces into tabs */
				if (leadingSpaces.indexIn(line) == 0)
					line = QString('\t').repeated(leadingSpaces.matchedLength()) +
						line.mid(leadingSpaces.matchedLength());
			}
			output << line << endl;
			continue;
		}

		/* Make sure that the name attribute is always the first one */
		int tagMatch = tagRegExp.indexIn(line),
			tagLength = tagRegExp.matchedLength();
		int nameMatch = nameRegExp.indexIn(line),
			filenameMatch = filenameRegExp.indexIn(line),
			nameLength = nameRegExp.matchedLength();

		if (tagMatch != -1 && nameMatch != -1 && filenameMatch == -1) {
			QString a = line.mid(tagLength, nameMatch-tagLength).trimmed(),
				b = line.mid(nameMatch+nameLength).trimmed();
			line = line.left(tagLength) + line.mid(nameMatch, nameLength);
			if (a.length() > 0)
				line += " " + a;
			if (b.length() > 0)
				line += " " + b;
		}

		/* Add an extra newline if this is an object tag, and if there
		   have been siblings before it */
		if (tagMatch != -1) {
			const QString &el = tagRegExp.cap(1);
			bool isObject = true;

			isObject &= (el != "string");
			isObject &= (el != "integer");
			isObject &= (el != "float");
			isObject &= (el != "boolean");
			isObject &= (el != "vector");
			isObject &= (el != "point");
			isObject &= (el != "transform");
			isObject &= (el != "spectrum");
			isObject &= (el != "rgb");
			isObject &= (el != "scale");
			isObject &= (el != "translate");
			isObject &= (el != "rotate");
			isObject &= (el != "lookAt");
			isObject &= (el != "matrix");

			if (isObject && hasContents) {
				output << endl;
				hasContents = false;
			}

			if (!isObject)
				hasContents = true;
		}

		/* Turn leading spaces into tabs */
		if (leadingSpaces.indexIn(line) == 0)
			line = QString('\t').repeated(leadingSpaces.matchedLength()) +
				line.mid(leadingSpaces.matchedLength());

		/* Remove ugly spaces */
		if (line.endsWith("  />")) {
			line = line.left(line.size()-4) + QString("/>");
			hasContents = true;
		} else if (line.endsWith(" />")) {
			line = line.left(line.size()-3) + QString("/>");
			hasContents = true;
		} else if (line.endsWith("/>")) {
			hasContents = true;
		} else if (line.endsWith(" >")) {
			line = line.left(line.size()-2) + QString(">");
		} else if (line.endsWith("?>")) {
			hasContents = true;
		}

		if (closeTag.indexIn(line) == 0)
			hasContents = true;

		output << line << endl;
	}
}
Esempio n. 12
0
bool Wizard::IniSettings::writeFile(const QString &path, QTextStream &stream)
{
    // Look for a square bracket, "'\\["
    // that has one or more "not nothing" in it, "([^]]+)"
    // and is closed with a square bracket, "\\]"
    QRegExp sectionRe(QLatin1String("^\\[([^]]+)\\]"));

    // Find any character(s) that is/are not equal sign(s), "[^=]+"
    // followed by an optional whitespace, an equal sign, and another optional whitespace, "\\s*=\\s*"
    // and one or more periods, "(.+)"
    QRegExp keyRe(QLatin1String("^([^=]+)\\s*=\\s*(.+)$"));

    const QStringList keys(mSettings.keys());

    QString currentSection;
    QString buffer;

    while (!stream.atEnd()) {

        const QString line(stream.readLine());

        if (line.isEmpty() || line.startsWith(QLatin1Char(';'))) {
            buffer.append(line + QLatin1String("\n"));
            continue;
        }

        if (sectionRe.exactMatch(line)) {
            buffer.append(line + QLatin1String("\n"));
            currentSection = sectionRe.cap(1);
        } else  if (keyRe.indexIn(line) != -1) {
            QString key(keyRe.cap(1).trimmed());
            QString lookupKey(key);

            // Append the section, but only if there is one
            if (!currentSection.isEmpty())
                lookupKey = currentSection + QLatin1Char('/') + key;

            buffer.append(key + QLatin1Char('=') + mSettings[lookupKey].toString() + QLatin1String("\n"));
            mSettings.remove(lookupKey);
        }
    }

    // Add the new settings to the buffer
    QHashIterator<QString, QVariant> i(mSettings);
    while (i.hasNext()) {
        i.next();

        QStringList fullKey(i.key().split(QLatin1Char('/')));
        QString section(fullKey.at(0));
        section.prepend(QLatin1Char('['));
        section.append(QLatin1Char(']'));
        QString key(fullKey.at(1));

        int index = buffer.lastIndexOf(section);
        if (index != -1) {
            // Look for the next section
            index = buffer.indexOf(QLatin1Char('['), index + 1);

            if (index == -1 ) {
                // We are at the last section, append it to the bottom of the file
                buffer.append(QString("\n%1=%2").arg(key, i.value().toString()));
                mSettings.remove(i.key());
                continue;
            } else {
                // Not at last section, add the key at the index
                buffer.insert(index - 1, QString("\n%1=%2").arg(key, i.value().toString()));
                mSettings.remove(i.key());
            }

        } else {
            // Add the section to the end of the file, because it's not found
            buffer.append(QString("\n%1\n").arg(section));
            i.previous();
        }
    }

    // Now we reopen the file, this time we write
    QFile file(path);

    if (file.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) {
        QTextStream in(&file);
        in.setCodec(stream.codec());

        // Write the updated buffer to an empty file
        in << buffer;
        file.flush();
        file.close();
    } else {
        return false;
    }

    return true;
}
Esempio n. 13
0
void MindMap::readFromText(QTextStream& in)
{
    clear();
    m_roots.clear();

  //  m_root = nullptr;
    Node* current=nullptr;
    int currentD = 0;
    QList<Node*> m_listOfAncestor;
    Node* parent = nullptr;
    while(!in.atEnd())
    {
        //if(i==90)
         //   return;
        QString line=in.readLine();
        int depth = getDepth(line);
        QString data = line.trimmed();
//        qDebug() << "depth:" <<depth << "data:" <<data << "currentD:" <<currentD << "ancestor count:" <<m_listOfAncestor.size();
        if((depth==0)&&(data.isEmpty()))//&&(currentD==0)
        {
            continue;
        }
        else
        {
            if(nullptr!=current)
            {
                if(depth>currentD)//on level under
                {
                    parent = current;
                    //current = addNodeAt(QPoint(parent->childItems().count()*20,currentD*40));
                    current = addNodeAt(QPoint(currentD*100,parent->childItems().count()*40));
                    m_listOfAncestor.append(current);
                    currentD = depth;
                }
                else if(depth==currentD)// previous d == current d
                {
    //                qDebug() << "$$$$$$$$$$$$$$" << "parent:" << (parent==nullptr ? "null" : parent->getText());
                    m_listOfAncestor.removeLast();
                    //current = addNodeAt(QPoint(parent->childItems().count()*20,currentD*40));
                    current = addNodeAt(QPoint(currentD*100,parent->childItems().count()*40));
                    m_listOfAncestor.append(current);
                }
                else if(depth<currentD)//many level above
                {
                    while(m_listOfAncestor.size()>depth)
                        m_listOfAncestor.removeLast();

                    if(!m_listOfAncestor.isEmpty())
                    {
                        parent = m_listOfAncestor.last();
                    }
                    else
                    {
                        parent = nullptr;
                    }
             //       qDebug() << "////////////////" << "parent:" << (parent==nullptr ? "null" : parent->getText());
                    //current = addNodeAt(QPoint(0,currentD*40));
                    current = addNodeAt(QPoint(currentD*100,currentD*40));

                    if(nullptr==parent)
                    {
                        m_listOfAncestor.clear();
                        m_listOfAncestor.append(current);
                        m_roots.append(current);

                    }
                    m_listOfAncestor.append(current);
                    currentD = depth;
                }
                else
                {
           //         qDebug() << ";;;;;;;;;;;;;;;;;;;;;;;;;";
                }
                current->setText(data);
                linkItem(parent,current);
            }
            else
            {

                current = addNodeAt(QPoint(sceneRect().width()/2,sceneRect().height()/2));
                current->setText(data);
                m_roots.append(current);
                qDebug() << "add roots" << current;

                currentD = depth;
                parent = current;

                m_listOfAncestor.clear();
                m_listOfAncestor.append(current);
            }
        }
    }
}
Esempio n. 14
0
bool Loader_obj::load_model_data(Model& mdl, QString path){

    qDebug("Parsing obj file...");

    QStringList pathlist = path.split("/",QString::KeepEmptyParts); //KeepEmptyParts
    QString model_name = pathlist.last();

    qDebug("Model name: " + model_name.toUtf8());



    //LOAD MESH DATA
    QFile file(path);
    if (!file.open (QIODevice::ReadOnly))
    {
        qDebug("Model import: Error 1: Model file could not be loaded...");
        return false;
    }
    QTextStream stream ( &file );
    QString line;

    QString mtllib;


    QString current_mesh;
    QMap<QString,QVector<int> >mesh_faces;
    QMap<QString,QString> mesh_mtl;
    QMap<QString,Material* > mtln_mtl;
    QVector<Vector3> model_vertices;
    QVector<Vector3> model_vertex_normals;
    QVector<Vector3> model_vertex_texture_coordinates;

    while( !stream.atEnd() ) {
        line = stream.readLine();
        QStringList list = line.split(QRegExp("\\s+"),QString::SkipEmptyParts); //SkipEmptyParts

        if(!list.empty()){
            if(list.first() == "mtllib"){
                mtllib = list.last();
            }

            else if(list.first() == "v"){
                model_vertices.append(Vector3(  list.value(1).toFloat(),
                                                  list.value(2).toFloat(),
                                                  list.value(3).toFloat()));
            }
            else if(list.first() == "vn"){
                model_vertex_normals.append(Vector3(  list.value(1).toFloat(),
                                                        list.value(2).toFloat(),
                                                        list.value(3).toFloat()));
            }
            else if(list.first() == "vt"){
                model_vertex_texture_coordinates.append(Vector3(  list.value(1).toFloat(),
                                                                    list.value(2).toFloat(),
                                                                    list.value(3).toFloat()));
            }
            else if(list.first() == "g"){
                current_mesh = list.value(1);
            }
            else if(list.first() == "usemtl"){
                mesh_mtl[current_mesh] = list.value(1);
            }
            else if(list.first() == "f"){
                QStringList face_part_1_list = list.value(1).split("/",QString::SkipEmptyParts); //SkipEmptyParts
                QStringList face_part_2_list = list.value(2).split("/",QString::SkipEmptyParts); //SkipEmptyParts
                QStringList face_part_3_list = list.value(3).split("/",QString::SkipEmptyParts); //SkipEmptyParts
                mesh_faces[current_mesh].append(face_part_1_list.value(0).toInt());
                mesh_faces[current_mesh].append(face_part_1_list.value(1).toInt());
                mesh_faces[current_mesh].append(face_part_1_list.value(2).toInt());

                mesh_faces[current_mesh].append(face_part_2_list.value(0).toInt());
                mesh_faces[current_mesh].append(face_part_2_list.value(1).toInt());
                mesh_faces[current_mesh].append(face_part_2_list.value(2).toInt());

                mesh_faces[current_mesh].append(face_part_3_list.value(0).toInt());
                mesh_faces[current_mesh].append(face_part_3_list.value(1).toInt());
                mesh_faces[current_mesh].append(face_part_3_list.value(2).toInt());

            }
        }

    }
    file.close();


    //LOAD MTL DATA

    pathlist.removeAt(pathlist.length()-1);
    QString mtl_path = pathlist.join("/") + "/" + mtllib;
    QString tex_path = pathlist.join("/") + "/";

    QFile mtlfile(mtl_path);
    if (!mtlfile.open (QIODevice::ReadOnly))
    {
        qDebug("Model import: Error 2: Model material file could not be loaded...");
        return false;
    }
    QTextStream mtlstream ( &mtlfile );
    QString mtlline;


    QString current_mtl;
    QMap<QString,Vector3> mtl_ambient_c;          //Ka
    QMap<QString,Vector3> mtl_diffuse_c;          //Kd
    QMap<QString,Vector3> mtl_specular_c;         //Ks
    QMap<QString,float>     mtl_specular_ns;        //Ns
    QMap<QString,float>     mtl_transparency_d;     //d
    QMap<QString,float>     mtl_transparency_tr;    //Tr
    QMap<QString,Vector3> mtl_transparency_tf;    //Tf
    QMap<QString,QString>   mtl_ambient_map;        //map_Ka
    QMap<QString,QString>   mtl_diffuse_map;        //map_Kd
    QMap<QString,QString>   mtl_specular_map;       //map_Ks
    QMap<QString,QString>   mtl_bump_map;           //map_bump
    QMap<QString,int>       mtl_illumination;       //illum

    while( !mtlstream.atEnd() ) {
        mtlline = mtlstream.readLine();
        QStringList list = mtlline.split(QRegExp("\\s+"),QString::SkipEmptyParts); //SkipEmptyParts
        if(!list.empty()){
            if(list.first() == "newmtl"){
                current_mtl = list.last();
            }
            else if(list.first() == "Ka"){
                mtl_ambient_c[current_mtl] = Vector3(list.value(1).toFloat(),
                                                       list.value(2).toFloat(),
                                                       list.value(3).toFloat());
            }
            else if(list.first() == "Kd"){
                mtl_diffuse_c[current_mtl] = Vector3(list.value(1).toFloat(),
                                                       list.value(2).toFloat(),
                                                       list.value(3).toFloat());
            }
            else if(list.first() == "Ks"){
                mtl_specular_c[current_mtl] = Vector3(list.value(1).toFloat(),
                                                        list.value(2).toFloat(),
                                                        list.value(3).toFloat());
            }
            else if(list.first() == "Ns"){
                mtl_specular_ns[current_mtl] = list.value(1).toFloat();

            }
            else if(list.first() == "d"){
                mtl_transparency_d[current_mtl] = list.value(1).toFloat();

            }
            else if(list.first() == "Tr"){
                mtl_transparency_tr[current_mtl] = list.value(1).toFloat();

            }
            else if(list.first() == "Tf"){
                mtl_transparency_tf[current_mtl] = Vector3(list.value(1).toFloat(),
                                                             list.value(2).toFloat(),
                                                             list.value(3).toFloat());
            }
            else if(list.first() == "map_Ka"){
                mtl_ambient_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8();
            }
            else if(list.first() == "map_Kd"){
                mtl_diffuse_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8();
            }
            else if(list.first() == "map_Ks"){
                mtl_specular_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8();
            }
            else if((list.first() == "map_bump") || (list.first() == "bump")){
                mtl_bump_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8();
            }
            else if(list.first() == "illum"){
                mtl_illumination[current_mtl] = list.value(1).toInt();
            }
        }

    }


    return true;
}
Esempio n. 15
0
KicadModule2Svg::PadLayer KicadModule2Svg::convertPad(QTextStream & stream, QString & pad, QList<int> & numbers) {
    PadLayer padLayer = UnableToTranslate;

    QStringList padStrings;
    while (true) {
        QString line = stream.readLine();
        if (line.isNull()) {
            throw QObject::tr("unexpected end of file");
        }
        if (line.contains("$EndPAD")) {
            break;
        }

        padStrings.append(line);
    }

    QString shape;
    QString drill;
    QString attributes;
    QString position;

    foreach (QString string, padStrings) {
        if (string.startsWith("Sh")) {
            shape = string;
        }
        else if (string.startsWith("Po")) {
            position = string;
        }
        else if (string.startsWith("At")) {
            attributes = string;
        }
        else if (string.startsWith("Dr")) {
            drill = string;
        }
    }

    if (drill.isEmpty()) {
        throw QObject::tr("pad missing drill");
    }
    if (attributes.isEmpty()) {
        throw QObject::tr("pad missing attributes");
    }
    if (position.isEmpty()) {
        throw QObject::tr("pad missing position");
    }
    if (shape.isEmpty()) {
        throw QObject::tr("pad missing shape");
    }

    QStringList positionStrings = position.split(" ");
    if (positionStrings.count() < 3) {
        throw QObject::tr("position missing params");
    }

    int posX = positionStrings.at(1).toInt();
    int posY = positionStrings.at(2).toInt();

    QStringList drillStrings = drill.split(" ");
    if (drillStrings.count() < 4) {
        throw QObject::tr("drill missing params");
    }

    int drillX = drillStrings.at(1).toInt();
    int drillXOffset = drillStrings.at(2).toInt();
    int drillYOffset = drillStrings.at(3).toInt();
    int drillY = drillX;

    if (drillXOffset != 0 || drillYOffset != 0) {
        throw QObject::tr("drill offset not implemented");
    }

    if (drillStrings.count() > 4) {
        if (drillStrings.at(4) == "O") {
            if (drillStrings.count() < 7) {
                throw QObject::tr("drill missing ellipse params");
            }
            drillY = drillStrings.at(6).toInt();
        }
    }

    QStringList attributeStrings = attributes.split(" ");
    if (attributeStrings.count() < 4) {
        throw QObject::tr("attributes missing params");
    }

    bool ok;
    int layerMask = attributeStrings.at(3).toInt(&ok, 16);
    if (!ok) {
        throw QObject::tr("bad layer mask parameter");
    }

    QString padType = attributeStrings.at(1);
    if (padType == "MECA") {
        // seems to be the same thing
        padType = "STD";
    }

    if (padType == "STD") {
        padLayer = ToCopper0;
    }
    else if (padType == "SMD") {
        padLayer = ToCopper1;
    }
    else if (padType == "CONN") {
        if (layerMask & 1) {
            padLayer = ToCopper0;
        }
        else {
            padLayer = ToCopper1;
        }
    }
    else if (padType == "HOLE") {
        padLayer = ToCopper0;
    }
    else {
        throw QObject::tr("Sorry, can't handle pad type %1").arg(padType);
    }

    QStringList shapeStrings = shape.split(" ");
    if (shapeStrings.count() < 8) {
        throw QObject::tr("pad shape missing params");
    }

    QString padName = unquote(shapeStrings.at(1));
    int padNumber = padName.toInt(&ok) - 1;
    if (!ok) {
        padNumber = padName.isEmpty() ? -1 : numbers.takeFirst();
        //DebugDialog::debug(QString("name:%1 padnumber %2").arg(padName).arg(padNumber));
    }
    else {
        numbers.removeOne(padNumber);
    }


    QString shapeIdentifier = shapeStrings.at(2);
    int xSize = shapeStrings.at(3).toInt();
    int ySize = shapeStrings.at(4).toInt();
    if (ySize <= 0) {
        DebugDialog::debug(QString("ySize is zero %1").arg(padName));
        ySize = xSize;
    }
    if (xSize <= 0) {
        throw QObject::tr("pad shape size is invalid");
    }

    int xDelta = shapeStrings.at(5).toInt();
    int yDelta = shapeStrings.at(6).toInt();
    int orientation = shapeStrings.at(7).toInt();

    if (shapeIdentifier == "T") {
        throw QObject::tr("trapezoidal pads not implemented");
        // eventually polygon?
    }

    if (xDelta != 0 || yDelta != 0) {
        // note: so far, all cases of non-zero delta go with shape "T"
        throw QObject::tr("shape delta not implemented");
    }

    if (padType == "HOLE") {
        if (shapeIdentifier != "C") {
            throw QObject::tr("non-circular holes not implemented");
        }

        if (drillX == xSize) {
            throw QObject::tr("non-copper holes not implemented");
        }
    }

    if (shapeIdentifier == "C") {
        checkLimits(posX, xSize, posY, ySize);
        pad += drawCPad(posX, posY, xSize, ySize, drillX, drillY, padName, padNumber, padType, padLayer);
    }
    else if (shapeIdentifier == "R") {
        checkLimits(posX, xSize, posY, ySize);
        pad += drawRPad(posX, posY, xSize, ySize, drillX, drillY, padName, padNumber, padType, padLayer);
    }
    else if (shapeIdentifier == "O") {
        checkLimits(posX, xSize, posY, ySize);
        QString id = getID(padNumber, padLayer);
        pad += QString("<g %1 connectorname='%2'>")
               .arg(id).arg(padName)
               + drawOblong(posX, posY, xSize, ySize, drillX, drillY, padType, padLayer)
               + "</g>";
    }
    else {
        throw QObject::tr("unable to handle pad shape %1").arg(shapeIdentifier);
    }

    if (orientation != 0) {
        if (orientation < 0) {
            orientation = (orientation % 3600) + 3600;
        }
        orientation = 3600 - (orientation % 3600);
        QTransform t = QTransform().translate(-posX, -posY) *
                       QTransform().rotate(orientation / 10.0) *
                       QTransform().translate(posX, posY);
        pad = TextUtils::svgTransform(pad, t, true, QString("_x='%1' _y='%2' _r='%3'").arg(posX).arg(posY).arg(orientation / 10.0));
    }

    return padLayer;
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QCoreApplication::setApplicationName("gbash");
    QCoreApplication::setApplicationVersion("1.0");

    bool qs = true;

    QString user_str;
    QTextStream stream (stdin);
    QTextStream out (stdout);

    out << "                          Welcome to the gBash terminal" << endl;
    out<<"                 (-t) Tutorial   (-m, n) Missions  (-f) Freeplay  " << endl << endl << endl;


    QString program = "D:/Cpp/qt/build-BashGUI-Desktop_Qt_5_5_0_MinGW_32bit-Debug/debug/BashGUI";
    QStringList arguments;

    QProcess *myProcess = new QProcess;

    // Open common file
    // if quit
    QFile modeFile("D:/Cpp/qt/build-BashGUI-Desktop_Qt_5_5_0_MinGW_32bit-Debug/commonfile.txt");
    if(!modeFile.open(QIODevice::ReadWrite) )
        ;
    while(!modeFile.atEnd()) {
        QByteArray line = modeFile.readLine();
        if(line.startsWith("g : quit")) {
            //end process
            out << "Process stopped";
            myProcess->close();
        }
    }

    do {
        printf("$ ");
        user_str = stream.readLine();
        if(user_str.contains("exit"))
        {
            qs = false; //quit statement
            out << "Thank You\n";
            break;
        }
        else if(!(user_str.startsWith("freeplay")||user_str.startsWith("-f")) && (user_str.startsWith("Tutorial")||user_str.startsWith("-t")||user_str.startsWith("mission")||user_str.startsWith("-m") )) {

            myProcess->start(program, arguments);
            // write t to file
        }



        else if(user_str.startsWith("echo ")) {  // extra space to prevent echosdfsfd from working.
            echo e(user_str);   // make this dynamic if possible.

        }

        else if(user_str.startsWith("ls")) {
            ls l(user_str);
        }

        else if (user_str.startsWith("pwd")) {
            pwd *p = new pwd;
            p->output_path();
        }

        else if(user_str.startsWith("clear"))
            system("cls");

        else if(user_str.startsWith("mkdir ")) {
            mkdir m(user_str);
        }

        else if(user_str.startsWith("rm ")) {
            rm r(user_str);
        }

        else if(user_str.startsWith("touch ")) {
            touch t(user_str);
        }

        else if(user_str.startsWith("cat ")) {
            cat c(user_str);
        }

        else if(user_str.startsWith("cd "))
            cd c(user_str);

        else
            qWarning("Command not found\n");

    } while(qs);

    modeFile.close();

    return 0;

    return a.exec();

}
Esempio n. 17
0
void modCalcVlsr::processLines( QTextStream &istream ) {

    // we open the output file

    //	QTextStream istream(&fIn);
    QString outputFileName;
    outputFileName = OutputFileBoxBatch->url().toLocalFile();
    QFile fOut( outputFileName );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);

    QString line;
    QChar space = ' ';
    int i = 0;
    long double jd0;
    SkyPoint spB;
    double sra, cra, sdc, cdc;
    dms raB, decB, latB, longB;
    QString epoch0B;
    double vhB, vgB, vtB, vlsrB, heightB;
    double vtopo[3];
    QTime utB;
    QDate dtB;
    KStarsDateTime dt0B;

    while ( ! istream.atEnd() ) {
        line = istream.readLine();
        line.trimmed();

        //Go through the line, looking for parameters

        QStringList fields = line.split( ' ' );

        i = 0;

        // Read Ut and write in ostream if corresponds

        if(UTCheckBatch->isChecked() ) {
            utB = QTime::fromString( fields[i] );
            i++;
        } else
            utB = UTBoxBatch->time();

        if ( AllRadioBatch->isChecked() )
            ostream << QLocale().toString( utB ) << space;
        else
            if(UTCheckBatch->isChecked() )
                ostream << QLocale().toString( utB ) << space;

        // Read date and write in ostream if corresponds

        if(DateCheckBatch->isChecked() ) {
            dtB = QDate::fromString( fields[i] );
            i++;
        } else
            dtB = DateBoxBatch->date();
        if ( AllRadioBatch->isChecked() )
            ostream << QLocale().toString( dtB, QLocale::LongFormat ).append(space);
        else
            if(DateCheckBatch->isChecked() )
                ostream << QLocale().toString( dtB, QLocale::LongFormat ).append(space);

        // Read RA and write in ostream if corresponds

        if(RACheckBatch->isChecked() ) {
            raB = dms::fromString( fields[i],false);
            i++;
        } else
            raB = RABoxBatch->createDms(false);

        if ( AllRadioBatch->isChecked() )
            ostream << raB.toHMSString() << space;
        else
            if(RACheckBatch->isChecked() )
                ostream << raB.toHMSString() << space;

        // Read DEC and write in ostream if corresponds

        if(DecCheckBatch->isChecked() ) {
            decB = dms::fromString( fields[i], true);
            i++;
        } else
            decB = DecBoxBatch->createDms();

        if ( AllRadioBatch->isChecked() )
            ostream << decB.toDMSString() << space;
        else
            if(DecCheckBatch->isChecked() )
                ostream << decB.toDMSString() << space;

        // Read Epoch and write in ostream if corresponds

        if(EpochCheckBatch->isChecked() ) {
            epoch0B = fields[i];
            i++;
        } else
            epoch0B = EpochBoxBatch->text();

        if ( AllRadioBatch->isChecked() )
            ostream << epoch0B << space;
        else
            if(EpochCheckBatch->isChecked() )
                ostream << epoch0B << space;

        // Read vlsr and write in ostream if corresponds

        if(InputVelocityCheckBatch->isChecked() ) {
            vlsrB = fields[i].toDouble();
            i++;
        } else
            vlsrB = InputVelocityComboBatch->currentText().toDouble();

        if ( AllRadioBatch->isChecked() )
            ostream << vlsrB << space;
        else
            if(InputVelocityCheckBatch->isChecked() )
                ostream << vlsrB << space;

        // Read Longitude and write in ostream if corresponds

        if (LongCheckBatch->isChecked() ) {
            longB = dms::fromString( fields[i],true);
            i++;
        } else
            longB = LongitudeBoxBatch->createDms(true);

        if ( AllRadioBatch->isChecked() )
            ostream << longB.toDMSString() << space;
        else
            if (LongCheckBatch->isChecked() )
                ostream << longB.toDMSString() << space;

        // Read Latitude


        if (LatCheckBatch->isChecked() ) {
            latB = dms::fromString( fields[i], true);
            i++;
        } else
            latB = LatitudeBoxBatch->createDms(true);
        if ( AllRadioBatch->isChecked() )
            ostream << latB.toDMSString() << space;
        else
            if (LatCheckBatch->isChecked() )
                ostream << latB.toDMSString() << space;

        // Read height and write in ostream if corresponds

        if(ElevationCheckBatch->isChecked() ) {
            heightB = fields[i].toDouble();
            i++;
        } else
            heightB = ElevationBoxBatch->text().toDouble();

        if ( AllRadioBatch->isChecked() )
            ostream << heightB << space;
        else
            if(ElevationCheckBatch->isChecked() )
                ostream << heightB << space;

        // We make the first calculations

        spB = SkyPoint (raB, decB);
        dt0B.setFromEpoch(epoch0B);
        vhB = spB.vHeliocentric(vlsrB, dt0B.djd());
        jd0 = KStarsDateTime(dtB,utB).djd();
        vgB = spB.vGeocentric(vlsrB, jd0);
        geoPlace->setLong( longB );
        geoPlace->setLat(  latB );
        geoPlace->setHeight( heightB );
        dms gsidt = KStarsDateTime(dtB,utB).gst();
        geoPlace->TopocentricVelocity(vtopo, gsidt);
        spB.ra().SinCos(sra, cra);
        spB.dec().SinCos(sdc, cdc);
        vtB = vgB - (vtopo[0]*cdc*cra + vtopo[1]*cdc*sra + vtopo[2]*sdc);

        ostream << vhB << space << vgB << space << vtB << endl;

    }


    fOut.close();
}
Esempio n. 18
0
void MibEditor::ExtractMIBfromRFC(void)
{
    QRegExp module_regexp("^[ \t]*([A-Za-z0-9-]*) *(PIB-)?DEFINITIONS *(::=)? *(BEGIN)? *$");
    QRegExp page_regexp("\\[[pP]age [iv0-9]*\\] *");
    QRegExp macro_regexp("^[ \t]*[A-Za-z0-9-]* *MACRO *::=");
    QRegExp end_regexp("^[ \t]*END[ \t]*$");
    QRegExp blankline_regexp("^[ \t]*$");
    QRegExp blank_regexp("[^ \t]");
    QRegExp leadingspaces_regexp("^([ ]*)");
    QRegExp draft_regexp("^[ ]*Internet[ \\-]Draft");

    QFile file_in("empty");
    QFile file_tmpout("empty");
    QFile file_out("empty");
    QTextStream in(&file_in);
    QTextStream tmpout; 
    QTextStream out; 

    QString line;
    QString module;
    QStringList modules;

    QString dir = NULL, filename = NULL;
    int skipmibfile = 0, skip = 0, skipped = 0, macro = 0, n = 0;

    // Open RFC file
    filename = QFileDialog::getOpenFileName(s->MainUI()->MIBFile,
                                        tr("Open RFC file"), "", 
                                        "RFC files (*.txt);;All Files (*.*)");

    if (!filename.isEmpty())
    {
        file_in.setFileName(filename);
        if (!file_in.open(QFile::ReadOnly | QFile::Text))
        {
            QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                                 tr("Cannot read file %1: %2\n")
                                 .arg(file_in.fileName())
                                 .arg(file_in.errorString()));
            return;
        }
    }
    else
        return;

    // Ask for directory where to save MIB files 
    dir = QFileDialog::getExistingDirectory(s->MainUI()->MIBFile,
                           tr("Select destination folder for MIB files"), "");

    if (dir.isEmpty())
    {
        QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                             tr("No directory selected. Aborting.\n"));
        file_in.close();
        return;
    }

    if (!QFileInfo(dir).isWritable())
    {
        QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                tr("Directory not writable by this user. Aborting.\n"));
        file_in.close();
        return;
    }

    // Extract & save each modules ...

    // Process each line
    while (in.atEnd() != true)
    {
        line = in.readLine();

        if (draft_regexp.indexIn(line) != -1)
            continue;

        // Start of module
        if (module_regexp.indexIn(line) != -1)
        {
            module = module_regexp.cap(1); 
            skip = 9;
            skipped = -1;
            macro = 0;
            n = 0;

            // Create temporary output file
            file_tmpout.setFileName(QDir::tempPath()+"/"+module+".tmp");
            file_tmpout.remove();
            if (!file_tmpout.open(QFile::ReadWrite | QFile::Text))
            {
                QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                                     tr("Cannot create file %1: %2. Abort.\n")
                                     .arg(file_tmpout.fileName())
                                     .arg(file_tmpout.errorString()));
                file_in.close();
                return;
            }

            tmpout.setDevice(&file_tmpout); 

            // Create output file
            file_out.setFileName(dir+"/"+module);
            if (file_out.exists())
            {
                QMessageBox mb(QMessageBox::Question, 
                               tr("SnmpB: Extract MIB from RFC"), 
                               tr("The file %1 already exist.\n")
                               .arg(file_out.fileName()));
                QPushButton *ob = mb.addButton(tr("Overwrite"), 
                                               QMessageBox::YesRole);
                QPushButton *sb = mb.addButton(tr("Skip"), 
                                               QMessageBox::NoRole);
                mb.exec();

                if (mb.clickedButton() == ob)
                {
                    // overwrite 
                    skipmibfile = 0;
                }
                else if (mb.clickedButton() == sb)
                {
                    // skip 
                    skipmibfile = 1;
                }
            }
            else
                skipmibfile = 0;

            if (!skipmibfile)
            {
                file_out.remove();
                if (!file_out.open(QFile::ReadWrite | QFile::Text))
                {
                    QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                                         tr("Cannot create file %1: %2. Skipping.\n")
                                         .arg(file_out.fileName())
                                         .arg(file_out.errorString()));
                    skipmibfile = 1;
                }
                else
                    out.setDevice(&file_out);
            }
        }

        // At the end of a page we start the counter skipped to skip the
        // next few lines.
        if (page_regexp.indexIn(line) != -1)
            skipped = 0;

        // If we are skipping...
        if (skipped >= 0)
        {
            skipped++;

            // If we have skipped enough lines to the top of the next page...
            if (skipped >= skip)
            {
                skipped = -1;
            }
            else
            {
                // Finish skipping, if we find a non-empty line, but not before
                // we have skipped four lines. remember the miminum of lines
                // we have ever skipped to keep empty lines in a modules that
                // appear near the top of a page.
                if ((skipped >= 4) && (blank_regexp.indexIn(line) != -1))
                {
                    if (skipped < skip)
                        skip = skipped;

                    skipped = -1;
                }   
            }
        }

        // So, if we are not skipping and inside a module, remember the line.
        if ((skipped == -1) && (module.length() > 0))
        {
            n++;
            tmpout << line << endl;
        }

        // Remember when we enter a macro definition
        if (macro_regexp.indexIn(line) != -1)
            macro = 1;

        // End of module
        if (end_regexp.indexIn(line) != -1)
        {
            if (macro == 0)
            {
                tmpout.flush(); 
                tmpout.seek(0);

                int strip = 99, p = 0;

                while (tmpout.atEnd() != true)
                {
                    line = tmpout.readLine();

                    // Find the minimum column that contains non-blank
                    // characters in order to cut a blank prefix off.
                    // Ignore lines that only contain white spaces.
                    if (blankline_regexp.indexIn(line) == -1)
                    {
                        if (leadingspaces_regexp.indexIn(line) != -1)
                        {
                            p = leadingspaces_regexp.cap(1).length(); 
                            if ((p < strip) && (line.length() > p))
                                strip = p;
                        }
                    }
                }

                tmpout.seek(0);

                if (!skipmibfile)
                {
                    int num_bl = 0;

                    while (tmpout.atEnd() != true)
                    {
                        line = tmpout.readLine();
                        // For each block of consecutive blank lines,
                        // remove all lines but one.
                        if (blankline_regexp.indexIn(line) != -1)
                        {
                            num_bl++;
                            continue;
                        }
                        else
                        {
                            if (num_bl > 0)
                                out << endl;
                            num_bl = 0;
                        }

                        out << line.remove(0, strip) << endl;
                    }

                    out.flush(); 
                    file_out.close();

                    modules << module;
                }

                file_tmpout.remove();

                module = "";
            }
            else
            {
                macro = 0;
            }
        }
    }

    file_in.close();
 
    if(modules.size() > 0)
    {
        QString module_list;
        for (int i = 0; i < modules.size(); i++)
        {
            module_list += "\n\t";
            module_list +=  modules[i];
        }

        QMessageBox::information(NULL, tr("SnmpB: Extract MIB from RFC"),
                                 tr("%1 MIB module(s) have been extracted. \
The following MIB file(s) were created: %2")
                                 .arg(modules.size())
                                 .arg(module_list));
    }
Esempio n. 19
0
void ModelExportHelper::exportToDBMS(DatabaseModel *db_model, DBConnection &conn, const QString &pgsql_ver, bool ignore_dup, bool simulate)
{
	int type_id;
	QString  version, sql_buf, sql_cmd, lin;
	DBConnection new_db_conn;
	unsigned i, count;
	ObjectType types[]={OBJ_ROLE, OBJ_TABLESPACE};
	BaseObject *object=nullptr;
	vector<Exception> errors;
	QTextStream ts;
	bool ddl_tk_found=false;

	/* Error codes treated in this method
			42P04 	duplicate_database
			42723 	duplicate_function
			42P06 	duplicate_schema
			42P07 	duplicate_table
			42710 	duplicate_object

		 Reference:
			http://www.postgresql.org/docs/current/static/errcodes-appendix.html*/
	QString error_codes[]={"42P04", "42723", "42P06", "42P07", "42710"};
	vector<QString> err_codes_vect(error_codes, error_codes + sizeof(error_codes) / sizeof(QString));

	if(!db_model)
		throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__);

	connect(db_model, SIGNAL(s_objectLoaded(int,QString,uint)), this, SLOT(updateProgress(int,QString,uint)));

	try
	{
		db_created=false;
		progress=sql_gen_progress=0;
		created_objs[OBJ_ROLE]=created_objs[OBJ_TABLESPACE]=-1;
		conn.connect();

		//Retrive the DBMS version in order to generate the correct code
		version=(conn.getDBMSVersion()).mid(0,3);

		//Overriding the DBMS version case the version is informed on parameter
		if(!pgsql_ver.isEmpty())
		{
			SchemaParser::setPgSQLVersion(pgsql_ver);
			emit s_progressUpdated(progress, trUtf8("PostgreSQL version detection overrided. Using version %1...").arg(pgsql_ver));
		}
		else
		{
			SchemaParser::setPgSQLVersion(version);
			emit s_progressUpdated(progress, trUtf8("PostgreSQL %1 server detected...").arg(version));
		}

		if(ignore_dup)
			emit s_progressUpdated(progress, trUtf8("Ignoring object duplication error..."));

		//Creates the roles and tablespaces separately from the other objects
		for(type_id=0; type_id < 2; type_id++)
		{
			count=db_model->getObjectCount(types[type_id]);

			for(i=0; i < count; i++)
			{
				object=db_model->getObject(i, types[type_id]);
				progress=((10 * (type_id+1)) + ((i/static_cast<float>(count)) * 10));

				//Emits a signal indicating that the object is being exported
				emit s_progressUpdated(progress,
															 trUtf8("Creating object `%1' (%2)...").arg(Utf8String::create(object->getName())).arg(object->getTypeName()));

				try
				{
					if(!object->isSQLDisabled())
					{
						sql_cmd=object->getCodeDefinition(SchemaParser::SQL_DEFINITION);
						conn.executeDDLCommand(sql_cmd);
					}
				}
				catch(Exception &e)
				{
					/* Raises an error if the object is duplicated and the ignore duplicity is not set or the error
					returned by the server is other than object duplicity */
					if(!ignore_dup ||
						 (ignore_dup &&
							std::find(err_codes_vect.begin(), err_codes_vect.end(), e.getExtraInfo())==err_codes_vect.end()))
						throw Exception(e.getErrorMessage(),
														e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, sql_cmd);
					else
						//If the object is duplicated store the error on a vector
						errors.push_back(e);
				}

				created_objs[types[type_id]]++;
			}
		}

		try
		{
			if(!db_model->isSQLDisabled())
			{
				//Creating the database on the DBMS
				emit s_progressUpdated(progress, trUtf8("Creating database `%1'...").arg(Utf8String::create(db_model->getName())));
				sql_cmd=db_model->__getCodeDefinition(SchemaParser::SQL_DEFINITION);
				conn.executeDDLCommand(sql_cmd);
				db_created=true;
			}
		}
		catch(Exception &e)
		{
			/* Raises an error if the object is duplicated and the ignore duplicity is not set or the error
			returned by the server is other than object duplicity */
			if(!ignore_dup ||
				 (ignore_dup &&
					std::find(err_codes_vect.begin(), err_codes_vect.end(), e.getExtraInfo())==err_codes_vect.end()))
				throw Exception(e.getErrorMessage(),
												e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, sql_cmd);
			else
				errors.push_back(e);
		}

		//Connects to the new created database to create the other objects
		progress=30;
		new_db_conn=conn;
		new_db_conn.setConnectionParam(DBConnection::PARAM_DB_NAME, db_model->getName());
		emit s_progressUpdated(progress, trUtf8("Connecting to database `%1'...").arg(Utf8String::create(db_model->getName())));

		new_db_conn.connect();
		progress=50;
		//Creating the other object types
		emit s_progressUpdated(progress, trUtf8("Creating objects on database `%1'...").arg(Utf8String::create(db_model->getName())));

		//Generates the sql from entire model
		sql_buf=db_model->getCodeDefinition(SchemaParser::SQL_DEFINITION, false);

		/* Extract each SQL command from the buffer and execute them separately. This is done
			 to permit the user, in case of error, identify what object is wrongly configured. */
		ts.setString(&sql_buf);
		i=1;
		progress+=(sql_gen_progress/progress);
		sql_cmd.clear();

		while(!ts.atEnd())
		{
			try
			{
				//Cleanup single line comments
				lin=ts.readLine();
				ddl_tk_found=(lin.indexOf(ParsersAttributes::DDL_END_TOKEN) >= 0);
				lin.remove(QRegExp("^(--)+(.)+$"));

				//If the line isn't empty after cleanup it will be included on sql command
				if(!lin.isEmpty())
					sql_cmd += lin + "\n";

				//If the ddl end token is found
				if(ddl_tk_found)
				{
					//Regexp used to extract the object being created
					QRegExp reg=QRegExp("(CREATE)(.)+(\n)", Qt::CaseSensitive);

					sql_cmd.simplified();

					//Check if the regex matches the sql command
					if(reg.exactMatch(sql_cmd))
					{
						QString obj_type, obj_name;
						ObjectType obj_types[]={ OBJ_FUNCTION, OBJ_TRIGGER, OBJ_INDEX,
																		 OBJ_RULE,	OBJ_TABLE, OBJ_VIEW, OBJ_DOMAIN,
																		 OBJ_SCHEMA,	OBJ_AGGREGATE, OBJ_OPFAMILY,
																		 OBJ_OPCLASS, OBJ_OPERATOR,  OBJ_SEQUENCE,
																		 OBJ_CONVERSION, OBJ_CAST,	OBJ_LANGUAGE,
																		 OBJ_COLLATION, OBJ_EXTENSION, OBJ_TYPE };
						unsigned count=sizeof(obj_types)/sizeof(ObjectType);
						int pos=0;

						for(unsigned i=0; i < count; i++)
						{
							//Check if the keyword for the current object exists on string
							pos=sql_cmd.indexOf(BaseObject::getSQLName(obj_types[i]));

							if(pos >= 0)
							{
								//Extracts from the line the string starting with the object's name
								lin=sql_cmd.mid(pos + BaseObject::getSQLName(obj_types[i]).size(),
																sql_cmd.indexOf('\n')).simplified();

								//Stores the object type name
								obj_type=BaseObject::getTypeName(obj_types[i]);

								//Special case of indexes, removes the "concurrently" keyword that cames after INDEX keyword
								if(obj_types[i]==OBJ_INDEX)
									lin.replace("CONCURRENTLY","");

								//The object name is the first element when splitting the string with space separator
								obj_name=lin.split(' ').at(0);
								obj_name.remove('(');
								obj_name.remove(';');
								break;
							}
						}

						emit s_progressUpdated(progress + (i/progress), trUtf8("Creating object `%1' (%2)...")
																	 .arg(obj_name)
																	 .arg(obj_type));
					}
					else
						//General commands like alter / set aren't explicitly shown
						emit s_progressUpdated(progress + (i/progress), trUtf8("Executing auxiliary command..."));

					//Executes the extracted SQL command
					if(!sql_cmd.isEmpty())
						new_db_conn.executeDDLCommand(sql_cmd);

					ddl_tk_found=false;
					sql_cmd.clear();
					i++;
				}
			}
			catch(Exception &e)
			{
				if(!ignore_dup ||
					 (ignore_dup &&
						std::find(err_codes_vect.begin(), err_codes_vect.end(), e.getExtraInfo())==err_codes_vect.end()))
					throw Exception(Exception::getErrorMessage(ERR_EXPORT_FAILURE).arg(Utf8String::create(sql_cmd)),
													ERR_EXPORT_FAILURE,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e, sql_cmd);
				else
					errors.push_back(e);
			}
		}

		disconnect(db_model, nullptr, this, nullptr);

		//Closes the new opened connection
		if(new_db_conn.isStablished()) new_db_conn.close();

		/* If the process was a simulation undo the export
		removing the created objects */
		if(simulate)
			undoDBMSExport(db_model, conn);
	}
	catch(Exception &e)
	{
		disconnect(db_model, nullptr, this, nullptr);

		//Closes the new opened connection
		if(new_db_conn.isStablished()) new_db_conn.close();

		//Undo the export removing the created objects
		undoDBMSExport(db_model, conn);

		//Redirects any error to the user
		if(errors.empty())
			throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
		else
		{
			errors.push_back(e);
			throw Exception(e.getErrorMessage(),__PRETTY_FUNCTION__,__FILE__,__LINE__, errors);
		}
	}
}
Esempio n. 20
0
void modCalcSidTime::processLines( QTextStream &istream ) {
    QFile fOut( OutputFileBatch->url().toLocalFile() );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);

    QString line;
    dms LST;
    QTime inTime, outTime;
    QDate dt;

    if ( ! DateCheckBatch->isChecked() )
        dt = DateBatch->date();

    while ( ! istream.atEnd() ) {
        line = istream.readLine();
        line = line.trimmed();

        QStringList fields = line.split( ' ', QString::SkipEmptyParts );

        //Find and parse the location string
        if (LocationCheckBatch->isChecked() ) {
            //First, look for a pair of quotation marks, and parse the string between them
            QChar q = '\"';
            if ( line.indexOf(q) == -1 ) q = '\'';
            if ( line.count(q)==2  ) {
                int iStart = line.indexOf(q);
                int iEnd = line.indexOf(q, iStart+1);
                QString locationString = line.mid(iStart, iEnd-iStart+1);
                line.remove( locationString );
                fields = line.split( ' ', QString::SkipEmptyParts );
                locationString.remove( q );

                QStringList locationFields = locationString.split( ',', QString::SkipEmptyParts );
                for (int i=0; i<locationFields.size(); i++)
                    locationFields[i] = locationFields[i].trimmed();

                if ( locationFields.size() == 1 ) locationFields.insert( 1, "" );
                if ( locationFields.size() == 2 ) locationFields.insert( 1, "" );
                if ( locationFields.size() != 3 ) {
                    qDebug() << "Error: could not parse location string: " << locationString;
                    continue;
                }

                geoBatch = KStarsData::Instance()->locationNamed( locationFields[0], locationFields[1], locationFields[2] );
                if ( ! geoBatch ) {
                    qDebug() << "Error: location not found in database: " << locationString;
                    continue;
                }
            }
        }

        if ( DateCheckBatch->isChecked() ) {
            //Parse one of the fields as the date
            foreach ( const QString &s, fields ) {
                dt = QDate::fromString( s );
                if ( dt.isValid() ) break;
            }
            if ( ! dt.isValid() ) {
                qDebug() << "Error: did not find a valid date string in: " << line;
                continue;
            }
        }
Esempio n. 21
0
// FIXME: Does the logic in this routine actually work correctly? For example,
// on non-Solaris systems which do not use /etc/timezone?
void Tzone::save()
{
    QStringList selectedZones(tzonelist->selection());

    if (selectedZones.count() > 0)
    {
      // Find untranslated selected zone
      QString selectedzone(selectedZones[0]);

#if defined(USE_SOLARIS)	// MARCO

        KTempFile tf( locateLocal( "tmp", "kde-tzone" ) );
        tf.setAutoDelete( true );
        QTextStream *ts = tf.textStream();

# ifndef INITFILE
#  define INITFILE	"/etc/default/init"
# endif

        QFile fTimezoneFile(INITFILE);
        bool updatedFile = false;

        if (tf.status() == 0 && fTimezoneFile.open(IO_ReadOnly))
        {
            bool found = false;

            QTextStream is(&fTimezoneFile);

            for (QString line = is.readLine(); !line.isNull();
                 line = is.readLine())
            {
                if (line.find("TZ=") == 0)
                {
                    *ts << "TZ=" << selectedzone << endl;
                    found = true;
                }
                else
                {
                    *ts << line << endl;
                }
            }

            if (!found)
            {
                *ts << "TZ=" << selectedzone << endl;
            }

            updatedFile = true;
            fTimezoneFile.close();
        }

        if (updatedFile)
        {
            ts->device()->reset();
            fTimezoneFile.remove();

            if (fTimezoneFile.open(IO_WriteOnly | IO_Truncate))
            {
                QTextStream os(&fTimezoneFile);

                for (QString line = ts->readLine(); !line.isNull();
                     line = ts->readLine())
                {
                    os << line << endl;
                }

                fchmod(fTimezoneFile.handle(),
                       S_IXUSR | S_IRUSR | S_IRGRP | S_IXGRP |
                       S_IROTH | S_IXOTH);
                fTimezoneFile.close();
            }
        }


        QString val = selectedzone;
#else
        QFile fTimezoneFile("/etc/timezone");

        if (fTimezoneFile.open(IO_WriteOnly | IO_Truncate) )
        {
            QTextStream t(&fTimezoneFile);
            t << selectedzone;
            fTimezoneFile.close();
        }

        QString tz = "/usr/share/zoneinfo/" + selectedzone;

        kdDebug() << "Set time zone " << tz << endl;

	if (!QFile::remove("/etc/localtime"))
	{
		//After the KDE 3.2 release, need to add an error message
	}
	else
		if (!KIO::NetAccess::file_copy(KURL(tz),KURL("/etc/localtime")))
			KMessageBox::error( 0,  i18n("Error setting new timezone."),
                        		    i18n("Timezone Error"));

        QString val = ":" + tz;
#endif // !USE_SOLARIS

        setenv("TZ", val.ascii(), 1);
        tzset();

    } else {
#if !defined(USE_SOLARIS) // Do not update the System!
        unlink( "/etc/timezone" );
        unlink( "/etc/localtime" );

        setenv("TZ", "", 1);
        tzset();
#endif // !USE SOLARIS
    }

    currentZone();
}
Esempio n. 22
0
/**
 * \brief Loads the file from the given path
 * \author Peter Grasch
 *
 * @fixme This function assumes the system-charset to be ISO-8859-1 and WILL destroy special characters if it isn't
 *
 * @param path If the path is empty the path set by the constructor is used
 */
void BOMPDict::load(QString path, QString encodingName)
{
    emit progress(0);

    QIODevice *dict = KFilterDev::deviceForFile(path,
                      KMimeType::findByFileContent(path)->name());
    if (!dict)
        return;
    if (!dict->open(QIODevice::ReadOnly)) {
        dict->deleteLater();
        return;
    }

    int maxProg=0;

    KMimeType::Ptr mimeType = KMimeType::findByFileContent(path);
    if (mimeType->is("text/plain")) {               //not compressed
        QFileInfo info;
        QFile f(path);
        info.setFile(f);
        maxProg = info.size();
    }

    int currentProg = 0;

    QTextStream *dictStream = new QTextStream(dict);
    dictStream->setCodec(QTextCodec::codecForName(encodingName.toAscii()));
    emit loaded();

    QString line, xsp, category;
    int wordend, termend;
    line = dictStream->readLine(1000);

    QString filteredXsp;
    QString xspFertig;
    QString currentPhoneme;
    QString currentCategory;
    QString currentFinalXsp;
    QString currentWord;
    while (!line.isNull()) {
        wordend = line.indexOf("\t");
        termend = line.indexOf("\t", wordend+1);

        xsp = line.mid(termend).trimmed();

        //		xsp.remove(QRegExp("^'*?*"));
        xsp.remove('\'');
        xsp.remove('|');
        xsp.remove(',');
        currentFinalXsp = segmentSampa(adaptToSimonPhonemeSet(xsp));

        currentWord = line.left(wordend);
        currentCategory = line.mid(wordend,
                                   termend-wordend).trimmed();

        QStringList currentCategories = currentCategory.split(':', QString::SkipEmptyParts);
        QStringList currentCategoriesUnique;

        if (currentCategories.isEmpty()) {
            line = dictStream->readLine(1000);
            continue;
        }

        QString currentCategoryStr = currentCategories[0];
        currentCategoriesUnique << currentCategoryStr;
        words << currentWord;
        categories << currentCategoryStr;
        pronunciations << currentFinalXsp;

        for (int k=1; k < currentCategories.count(); k++) {
            currentCategoryStr = currentCategories[k];
            if (!currentCategoriesUnique.contains(currentCategoryStr)) {
                currentCategoriesUnique << currentCategoryStr;

                words << currentWord;
                categories << currentCategoryStr;
                pronunciations << currentFinalXsp;
            }
        }

        currentProg += line.length();

        if (maxProg != 0)
            emit progress((int) (((((double)currentProg) /
                                   ((double)maxProg)))*1000));
        else emit progress(-1);
        line = dictStream->readLine(1000);
    }
    delete dictStream;
    dict->close();
    delete dict;
}
Esempio n. 23
0
void modCalcJD::processLines( QTextStream &istream, int inputData ) {
    QFile fOut( OutputFileBatch->url().toLocalFile() );
    fOut.open(QIODevice::WriteOnly);
    QTextStream ostream(&fOut);

    QString line;
    long double jd(0);
    double mjd(0);
    KStarsDateTime dt;

    while ( ! istream.atEnd() ) {
        line = istream.readLine();
        line = line.trimmed();
        QStringList data = line.split( ' ', QString::SkipEmptyParts );

        if ( inputData == 0 ) { //Parse date & time
            //Is the first field parseable as a date or date&time?
            if ( data[0].length() > 10 )
                dt = KStarsDateTime::fromString( data[0] );
            else
                dt = KStarsDateTime( QDate::fromString( data[0] ), QTime(0,0,0) );

            //DEBUG
            kDebug() << data[0];
            if ( dt.isValid() ) kDebug() << dt.toString();

            if ( dt.isValid() ) {
                //Try to parse the second field as a time
                if ( data.size() > 1 ) {
                    QString s = data[1];
                    if ( s.length() == 4 ) s = '0'+s;
                    QTime t = QTime::fromString( s );
                    if ( t.isValid() ) dt.setTime( t );
                }

            } else { //Did not parse the first field as a date; try it as a time
                QTime t = QTime::fromString( data[0] );
                if ( t.isValid() ) {
                    dt.setTime( t );
                    //Now try the second field as a date
                    if ( data.size() > 1 ) {
                        QDate d = QDate::fromString( data[1] );
                        if ( d.isValid() ) dt.setDate( d );
                        else dt.setDate( QDate::currentDate() );
                    }
                }
            }

            if ( dt.isValid() ) {
                //Compute JD and MJD
                jd = dt.djd();
                mjd = jd - MJD0;
            }

        } else if ( inputData == 1 ) {//Parse Julian day
            bool ok(false);
            jd = data[0].toDouble(&ok);
            if ( ok ) {
                dt.setDJD( jd );
                mjd = jd - MJD0;
            }
        } else if ( inputData == 2 ) {//Parse Modified Julian day
            bool ok(false);
            mjd = data[0].toDouble(&ok);
            if ( ok ) {
                jd = mjd + MJD0;
                dt.setDJD( jd );
            }
        }

        //Write to output file
        ostream << KGlobal::locale()->formatDateTime( dt, KLocale::LongDate ) << "  "
                << QString::number( jd, 'f', 2 ) << "  "
                << QString::number( mjd, 'f', 2 ) << endl;

    }

    fOut.close();
}
Esempio n. 24
0
void NYCGenericImporter::importNYCGeneric( QTextStream &stream )
{
	kapp->processEvents(); //don't want the user to think its frozen... especially for files with thousands of recipes

	QString current;

	stream.skipWhiteSpace();

	//title
	while ( !( current = stream.readLine() ).isEmpty() && !stream.atEnd() )
		m_recipe.title = current;

	//categories
	while ( !( current = stream.readLine() ).isEmpty() && !stream.atEnd() ) {
		if ( current[ 0 ].isNumber() ) {
			loadIngredientLine( current );
			break;
		} //oops, this is really an ingredient line (there was no category line)

		QStringList categories = current.split( ',', QString::SkipEmptyParts );

		if ( categories.count() > 0 && categories[ 0 ].toUpper() == "none" )  //there are no categories
			break;

		for ( QStringList::const_iterator it = categories.constBegin(); it != categories.constEnd(); ++it ) {
			Element new_cat( QString( *it ).trimmed() );
			kDebug() << "Found category: " << new_cat.name ;
			m_recipe.categoryList.append( new_cat );
		}
	}

	//ingredients
	while ( !( current = stream.readLine() ).isEmpty() && !stream.atEnd() )
		loadIngredientLine( current );

	//everything else is the instructions with optional "contributor", "prep time" and "yield"
	bool found_next;
	while ( !( found_next = ( current = stream.readLine() ).startsWith( "@@@@@" ) ) && !stream.atEnd() ) {
		if ( current.startsWith( "Contributor:" ) ) {
			Element new_author( current.mid( current.indexOf( ':' ) + 1, current.length() ).trimmed() );
			kDebug() << "Found author: " << new_author.name ;
			m_recipe.authorList.append( new_author );
		}
		else if ( current.startsWith( "Preparation Time:" ) ) {
			m_recipe.prepTime = QTime::fromString( current.mid( current.indexOf( ':' ), current.length() ) );
		}
		else if ( current.startsWith( "Yield:" ) ) {
			int colon_index = current.indexOf( ':' );
			int amount_type_sep_index = current.indexOf(" ",colon_index+1);

			m_recipe.yield.setAmount(current.mid( colon_index+2, amount_type_sep_index-colon_index ).toDouble());
			m_recipe.yield.setType(current.mid( amount_type_sep_index+3, current.length() ));
		}
		else if ( current.startsWith( "NYC Nutrition Analysis (per serving or yield unit):" ) ) {
			//m_recipe.instructions += current + '\n';
		}
		else if ( current.startsWith( "NYC Nutrilink:" ) ) {
			//m_recipe.instructions += current + '\n';
		}
		else if ( !current.trimmed().isEmpty() && !current.startsWith("** Exported from Now You're Cooking!") ) {
			m_recipe.instructions += current + '\n';
		}
	}

	m_recipe.instructions = m_recipe.instructions.trimmed();
	putDataInRecipe();

	if ( found_next )
		importNYCGeneric( stream );
}
Esempio n. 25
0
void Global::initDatabase(QString filename)
{
  GASSERT(_db == NULL, "Cannot initialize database twice");

  QFile fd (filename);
  if (!fd.open(QIODevice::ReadOnly))
    GEXITDIALOG("Could not open project file for reading " + filename);
  QTextStream file (&fd);

  // The first five lines contain the following information
  // VERSION=%s
  // IMAGE_PATH=%s
  // QUESTIONS_PER_STUDENT=%d
  // PAGES_PER_STUDENT=%d
  // TOTAL_STUDENTS=%d
  // SAVE_DATE_TIME=%s
  // NUM_IMAGES=%d
  struct _keyvalue { QString key; QString string; size_t number; };
  _keyvalue intro[7];
  QString header_names[7] = { "VERSION", "IMAGE_PATH", "QUESTIONS_PER_STUDENT", "PAGES_PER_STUDENT", "TOTAL_STUDENTS", "SAVE_DATE_TIME", "NUM_IMAGES" };
  bool expect_numbers[7] = { false, false, true, true, true, false, true };
  for (size_t i = 0; i < 7; i++)
  {
    if (file.atEnd())
      GEXITDIALOG(QString("Encountered end of file reading line %1").arg(i));
    QString in = file.readLine();
    QStringList fields = in.split("=");
    if (fields.size() != 2)
      GEXITDIALOG(QString("Could not find key/value pair separated by = in [%1] reading line %2").arg(in).arg(i));
    intro[i].key = fields.at(0);
    if (header_names[i] != fields.at(0))
      GEXITDIALOG(QString("Line %1 header was not [%2] but found instead [%3]").arg(i).arg(header_names[i]).arg(intro[i].key));
    intro[i].string = fields.at(1);
    if (fields.at(0).size() == 0)
      GEXITDIALOG(QString("Key in [%1] was empty reading line %2").arg(in).arg(i));
    if (fields.at(1).size() == 0)
      GEXITDIALOG(QString("Value in [%1] was empty reading line %2").arg(in).arg(i));
    intro[i].number = -1;
    if (expect_numbers[i])
    {
      bool ok;
      int num = fields.at(1).toInt(&ok);
      if (!ok)
        GEXITDIALOG(QString("Value [%1] in [%2] was not an integer").arg(fields.at(1)).arg(in));
      if (num <= 0)
        GEXITDIALOG(QString("Value [%1] in [%2] was not a positive integer").arg(fields.at(1)).arg(in));
      intro[i].number = num;
    }
    if (expect_numbers[i])
      GDEBUG ("Parsed key [%s] = number [%zu]", qPrintable(intro[i].key), intro[i].number);
    else
      GDEBUG ("Parsed key [%s] = string [%s]", qPrintable(intro[i].key), qPrintable(intro[i].string));
  }

  QString version = intro[0].string;
  QString image_path = intro[1].string;
  size_t numQuestions = intro[2].number;
  size_t numPagesPerStudent = intro[3].number;
  size_t numStudents = intro[4].number;
  QString unused_date_time = intro[5].string;
  size_t numImages = intro[6].number;

  // Initialize the database since we know all the dimensions now
  initDatabase(numStudents, numQuestions, numPagesPerStudent);

  // Check the version is what we are expecting
  if (version != DB_VERSION)
    GEXITDIALOG(QString("Found version [%1] when only version [%2] is supported").arg(version).arg(DB_VERSION));

  // Image paths should always be . right now, nothing else is supported
  if (image_path != ".")
    GEXITDIALOG("Non-empty path found for image loading");
  int slash = filename.lastIndexOf("/");
  if (slash < 0)
    GEXITDIALOG("Could not find ending slash in file name");
  QString full_image_path = filename.left(slash);
  GDEBUG("Using image path [%s] from input file [%s]", qPrintable(full_image_path), qPrintable(filename));

  initPages(full_image_path);

  // Check that the number of images loaded matches what we are expecting
  GDEBUG ("Loaded in %zu images from [%s], input file says %zu images", getPages()->size(), qPrintable(image_path), numImages);
  if (getPages()->size() != numImages)
    GEXITDIALOG(QString("Found different number of images than was used for the save"));

  // Now populate the database. Each entry is of the following form:
  // IDNUM,STUDENTID,STUDENTNAME,TOTAL,Q0,Q1,..,QN,Feed0,Feed1,..,FeedN
  // All fields will contain something except for Feed0..FeedN
  for (int student = -2; student < (int)numStudents; student++)
  {
    if (file.atEnd())
      GEXITDIALOG(QString("Encountered end of file reading student %1 of %2").arg(student+1).arg(numStudents));
    QString in = file.readLine();
    QStringList fields = in.split("\t");
    if (fields.size() != (2*(int)numQuestions + 4))
      GEXITDIALOG(QString("Found only %1 columns in [%2] for student %3 of %4 when expected 2x%5+4 columns").arg(fields.size()).arg(in).arg(student+1).arg(numStudents).arg(numQuestions));
    for (size_t col = 4; col < numQuestions+4; col++) // Do not search student id/name, or any feedback, since these can be empty
      if (fields.at(col) == "")
        GEXITDIALOG(QString("Found empty column %1 for student %3 of %4").arg(col+1).arg(student+1).arg(numStudents));
    bool ok;
    {
      int num = fields.at(0).toInt(&ok);
      if ((!ok) || (num != student))
        GEXITDIALOG(QString("Expected row number %1 but found [%2] instead for student %3 of %4").arg(student).arg(fields.at(0)).arg(student+1).arg(numStudents));
    }

    if (student == -2)
    {
      if ((fields.at(1) != "PAGE") && (fields.at(2) != "PAGE"))
        GEXITDIALOG(QString("Expected PAGE headers for first row of data, but found [%1] [%2] instead").arg(fields.at(1).arg(fields.at(2))));
      for (size_t q = 0; q < numQuestions; q++)
      {
        int page = fields.at(q+4).toInt(&ok);
        if ((!ok) || (page < -1))
          GEXITDIALOG(QString("Page value [%1] for question %2 was not valid for maximum values").arg(fields.at(q+4)).arg(q+1));
        Global::db()->setQuestionPage(q, page, false);
      }
      int total = fields.at(3).toInt(&ok);
      if ((!ok) || (total != -1))
        GEXITDIALOG(QString("Page total in file [%1] was not -1").arg(fields.at(3)));
    }
    else if (student == -1)
    {
      if ((fields.at(1) != "MAX") && (fields.at(2) != "MAX"))
        GEXITDIALOG(QString("Expected MAX headers for first row of data, but found [%1] [%2] instead").arg(fields.at(1).arg(fields.at(2))));
      for (size_t q = 0; q < numQuestions; q++)
      {
        int score = fields.at(q+4).toInt(&ok);
        if ((!ok) || (score < -1))
          GEXITDIALOG(QString("Score value [%1] for question %2 was not valid for maximum values").arg(fields.at(q+4)).arg(q+1));
        Global::db()->setQuestionMaximum(q, score, false);
      }
      int total = fields.at(3).toInt(&ok);
      if ((!ok) || (total != Global::db()->getTotalMaximum()))
        GEXITDIALOG(QString("Maximum total in file [%1] did not match calculated maximum total %2").arg(fields.at(3)).arg(Global::db()->getTotalMaximum()));
    }
    else
    {
      Student &entry = Global::db()->getStudent(student);
      entry.setStudentId(fields.at(1), false);
      entry.setStudentName(fields.at(2), false);
      for (size_t q = 0; q < numQuestions; q++)
      {
        int score = fields.at(q+4).toInt(&ok);
        if ((!ok) || (score < -1) || (score > Global::db()->getQuestionMaximum(q)))
          GEXITDIALOG(QString("Score value [%1] for question %2 was not valid student %3 of %4").arg(fields.at(q+4)).arg(q+1).arg(student+1).arg(numStudents));
        entry.setGrade(q, score, false);
      }
      for (size_t q = 0; q < numQuestions; q++)
        entry.setFeedback(q, fields.at(q+4+numQuestions), false);
      int total = fields.at(3).toInt(&ok);
      if ((!ok) || (total != entry.getTotal()))
        GEXITDIALOG(QString("Total in file [%1] did not match calculated total %2").arg(fields.at(3)).arg(entry.getTotal()));
    }
  }
}
Esempio n. 26
0
bool Translator::updateSettings()
{
    QTextStream in;
    QFile channelSetupFile(QDir::currentPath() + CHANNEL_SETTINGS_FILE_PATH);

    if (channelSetupFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Reading channelsetup file";
        in.setDevice(&channelSetupFile);
    } else {
        qDebug() << "Error opening channelsetup file";
        return false;
    }

    // Reading the settings into local variables
    QString samplingRateStr, numberOfChannelsStr, captionStr, channelEnabledStr, parameterStr, mStr, cStr;
    bool ok;

    samplingRateStr = in.readLine();
    numberOfChannelsStr = in.readLine();
    captionStr = in.readLine();
    channelEnabledStr = in.readLine();
    parameterStr = in.readLine();
    mStr = in.readLine();
    cStr = in.readLine();

    channelSetupFile.close();

    // Default values
    samplingRate = 100;
    numberOfChannels = 16;
    for (int i = 0; i < 16; i++) {
        channelCaption[i] = "Channel" + QString::number(i);
    }
    for (int i = 0; i < 16; i++) {
        channelEnabled[i] = 1;
    }
    for (int i = 0; i < 16; i++) {
        channelParameter[i] = 'V';
    }
    for (int i = 0; i < 16; i++) {
        channelM[i] = 1;
    }
    for (int i = 0; i < 16; i++) {
        channelC[i] = 0;
    }

    // Extracting values from settings file
    samplingRate = samplingRateStr.toInt(&ok);
    numberOfChannels = numberOfChannelsStr.toInt(&ok);

    QStringList captionValues = captionStr.split(',');
    for (int i = 0; i < captionValues.size(); ++i) {
        channelCaption[i] = captionValues.at(i);
    }

    QStringList channelEnabledValues = channelEnabledStr.split(',');
    for (int i = 0; i < channelEnabledValues.size(); ++i) {
        channelEnabled[i] = channelEnabledValues.at(i).toInt(&ok);
    }

    QStringList parameterValues = parameterStr.split(',');
    for (int i = 0; i < parameterValues.size(); ++i) {
        if (parameterValues.at(i) == "V")
            channelParameter[i] = 'V';
        else
            channelParameter[i] = 'T';
    }

    QStringList mValues = mStr.split(',');
    for (int i = 0; i < mValues.size(); ++i) {
        channelM[i] = mValues.at(i).toDouble(&ok);
    }

    QStringList cValues = cStr.split(',');
    for (int i = 0; i < cValues.size(); ++i) {
        channelC[i] = cValues.at(i).toDouble(&ok);
    }

    return true;
}
Esempio n. 27
0
void modCalcAzel::processLines( QTextStream &istream ) {

	// we open the output file

//	QTextStream istream(&fIn);
	QString outputFileName;
	outputFileName = OutputLineEditBatch->text();
	QFile fOut( outputFileName );
	fOut.open(IO_WriteOnly);
	QTextStream ostream(&fOut);

	QString line;
	QString space = " ";
	int i = 0;
	long double jd0, jdf;
	dms LST;
	SkyPoint sp;
	dms raB, decB, latB, longB, azB, elB;
	double epoch0B;
	QTime utB;
	ExtDate dtB;

	while ( ! istream.eof() ) {
		line = istream.readLine();
		line.stripWhiteSpace();

		//Go through the line, looking for parameters

		QStringList fields = QStringList::split( " ", line );

		i = 0;

		// Read Ut and write in ostream if corresponds
		
		if(utCheckBatch->isChecked() ) {
			utB = QTime::fromString( fields[i] );
			i++;
		} else
			utB = utBoxBatch->time();
		
		if ( allRadioBatch->isChecked() )
			ostream << utB.toString() << space;
		else
			if(utCheckBatch->isChecked() )
				ostream << utB.toString() << space;
			
		// Read date and write in ostream if corresponds
		
		if(dateCheckBatch->isChecked() ) {
			 dtB = ExtDate::fromString( fields[i] );
			 i++;
		} else
			dtB = dateBoxBatch->date();
		if ( allRadioBatch->isChecked() )
			ostream << dtB.toString().append(space);
		else
			if(dateCheckBatch->isChecked() )
			 	ostream << dtB.toString().append(space);
		
		// Read Longitude and write in ostream if corresponds
		
		if (longCheckBatch->isChecked() ) {
			longB = dms::fromString( fields[i],TRUE);
			i++;
		} else
			longB = longBoxBatch->createDms(TRUE);
		
		if ( allRadioBatch->isChecked() )
			ostream << longB.toDMSString() << space;
		else
			if (longCheckBatch->isChecked() )
				ostream << longB.toDMSString() << space;
		
		// Read Latitude


		if (latCheckBatch->isChecked() ) {
			latB = dms::fromString( fields[i], TRUE);
			i++;
		} else
			latB = latBoxBatch->createDms(TRUE);
		if ( allRadioBatch->isChecked() )
			ostream << latB.toDMSString() << space;
		else
			if (latCheckBatch->isChecked() )
				ostream << latB.toDMSString() << space;
		
		// Read Epoch and write in ostream if corresponds
	
		if(epochCheckBatch->isChecked() ) {
			epoch0B = fields[i].toDouble();
			i++;
		} else
			epoch0B = getEpoch( epochBoxBatch->text() );

		if ( allRadioBatch->isChecked() )
			ostream << epoch0B << space;
		else
			if(epochCheckBatch->isChecked() )
				ostream << epoch0B << space;

		// We make the first calculations
		KStarsDateTime dt;
		dt.setFromEpoch( epoch0B );
		jdf = KStarsDateTime(dtB,utB).djd();
		jd0 = dt.djd();

		LST = KStarsDateTime(dtB,utB).gst().Degrees() + longB.Degrees();
		
		// Equatorial coordinates are the input coords.
		if (!horInputCoords) {
		// Read RA and write in ostream if corresponds

			if(raCheckBatch->isChecked() ) {
				raB = dms::fromString( fields[i],FALSE);
				i++;
			} else
				raB = raBoxBatch->createDms(FALSE);

			if ( allRadioBatch->isChecked() )
				ostream << raB.toHMSString() << space;
			else
				if(raCheckBatch->isChecked() )
					ostream << raB.toHMSString() << space;

			// Read DEC and write in ostream if corresponds

			if(decCheckBatch->isChecked() ) {
				decB = dms::fromString( fields[i], TRUE);
				i++;
			} else
				decB = decBoxBatch->createDms();

			if ( allRadioBatch->isChecked() )
				ostream << decB.toDMSString() << space;
			else
				if(decCheckBatch->isChecked() )
					ostream << decB.toDMSString() << space;

			sp = SkyPoint (raB, decB);
			sp.apparentCoord(jd0, jdf);
			sp.EquatorialToHorizontal( &LST, &latB );
			ostream << sp.az()->toDMSString() << space << sp.alt()->toDMSString() << endl;

		// Input coords are horizontal coordinates
		
		} else {
			if(azCheckBatch->isChecked() ) {
				azB = dms::fromString( fields[i],FALSE);
				i++;
			} else
				azB = azBoxBatch->createDms();

			if ( allRadioBatch->isChecked() )
				ostream << azB.toHMSString() << space;
			else
				if(raCheckBatch->isChecked() )
					ostream << azB.toHMSString() << space;

			// Read DEC and write in ostream if corresponds

			if(elCheckBatch->isChecked() ) {
				elB = dms::fromString( fields[i], TRUE);
				i++;
			} else
				elB = decBoxBatch->createDms();

			if ( allRadioBatch->isChecked() )
				ostream << elB.toDMSString() << space;
			else
				if(elCheckBatch->isChecked() )
					ostream << elB.toDMSString() << space;

			sp.setAz(azB);
			sp.setAlt(elB);
			sp.HorizontalToEquatorial( &LST, &latB );
			ostream << sp.ra()->toHMSString() << space << sp.dec()->toDMSString() << endl;
		}

	}


	fOut.close();
}
Esempio n. 28
0
int Visualizer::ObjectLoader(QFile *filename)
{

    if(!filename->open(QIODevice::ReadOnly))
    {
        qDebug() << "error opening file: " << filename->error();
        return 0;
    }
    QList<QVector3D> SceneObjectPoints;
    QList<QVector4D> ObjectFaceVertices;
    QList<QVector3D> SceneObjectNormals;
    QList<QVector3D> colors;
    QVector<QVector3D> SceneObjectVertices;
    QVector<QVector3D> SceneObjectColors;
    QVector<QVector3D> SceneObjectFaceNormals;
    QVector<QVector2D> MaterialAssigner;
    QList<QString> tmpFullText;
    QTextStream *in = new QTextStream(filename);
    while(!in->atEnd())
    {
        tmpFullText.append(in->readLine());
    }
    filename->close();
    float tmpx,tmpy,tmpz;
    int a,b,c,d,faceMaterialIndex = 0;

    for(int i=0;i<tmpFullText.size();i++)
    {
        if(tmpFullText[i].toStdString().c_str()[0]=='#')
            continue;
        else if(tmpFullText[i].toStdString().c_str()[0]=='v' && tmpFullText[i].toStdString().c_str()[1]==' ')
        {
            sscanf(tmpFullText[i].toStdString().c_str(),"v %f %f %f",&tmpx,&tmpy,&tmpz);
            SceneObjectPoints.append(QVector3D(tmpx,tmpy,tmpz));
        }
        else if(tmpFullText[i].toStdString().c_str()[0]=='v' && tmpFullText[i].toStdString().c_str()[1]=='n')
        {
            sscanf(tmpFullText[i].toStdString().c_str(),"vn %f %f %f",&tmpx,&tmpy,&tmpz);
            SceneObjectNormals.append(QVector3D(tmpx,tmpy,tmpz));
        }

        else if(tmpFullText[i].toStdString().c_str()[0]=='f' && tmpFullText[i].toStdString().c_str()[1]==' ')
        {
            sscanf(tmpFullText[i].toStdString().c_str(),"f %d//%d %d//%d %d//%d",&a,&b,&c,&b,&d,&b);
            ObjectFaceVertices.append(QVector4D(a,c,d,b));
            faceMaterialIndex += 1;

        }
        else if(tmpFullText[i].toStdString().c_str()[0]=='u' && tmpFullText[i].toStdString().c_str()[1]=='s')
        {
            if(tmpFullText[i].toStdString().c_str()[15]==' ')
                MaterialAssigner.append(QVector2D(0,faceMaterialIndex));
            else
                MaterialAssigner.append(QVector2D(tmpFullText[i].toStdString().c_str()[18],faceMaterialIndex));
        }
    }

    QFile file("../../../../RubicCubeSolver/objects/box3.mtl");
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "error opening Material file: " << file.error();
        return 0;
    }
    in = new QTextStream(&file);
    tmpFullText.clear();

    while(!in->atEnd())
    {
        tmpFullText.append(in->readLine());
    }
    file.close();

    for(int i=0;i<tmpFullText.size();i++)
    {
        if(tmpFullText[i].toStdString().c_str()[0]=='K' && tmpFullText[i].toStdString().c_str()[1]=='d')
        {
            sscanf(tmpFullText[i].toStdString().c_str(),"Kd %f %f %f",&tmpx,&tmpy,&tmpz);
            colors.append(QVector3D(tmpx,tmpy,tmpz));
        }
    }

    int counter = 0;

    for(int i=0;i<ObjectFaceVertices.size();i++)
    {

       SceneObjectVertices << SceneObjectPoints[(ObjectFaceVertices[i].x())-1]
                           << SceneObjectPoints[(ObjectFaceVertices[i].y())-1]
                           << SceneObjectPoints[(ObjectFaceVertices[i].z())-1];
       SceneObjectFaceNormals << SceneObjectNormals[(ObjectFaceVertices[i].w())-1]
                              << SceneObjectNormals[(ObjectFaceVertices[i].w())-1]
                              << SceneObjectNormals[(ObjectFaceVertices[i].w())-1];
       if(MaterialAssigner[counter+1].y()==i)
           counter++;
       SceneObjectColors << colors[counter] << colors[counter] << colors[counter];
    }

    QGLBuffer *tmpBuffer = WriteBufferData(SceneObjectVertices, SceneObjectFaceNormals, SceneObjectColors);
    m_pBufferList.append(new m_pBufferShaderList(1, SceneObjectVertices.size(), tmpBuffer));

    delete in;
}
Esempio n. 29
0
void ImportEnex::import(QString file) {
    fileName = file;
    errorMessage = "";

    lastError = 0;
    QFile xmlFile(fileName);
    QFile scanFile(fileName);
    if (!xmlFile.open(QIODevice::ReadOnly) || !scanFile.open(QIODevice::ReadOnly)) {
        lastError = 16;
        errorMessage = "Cannot open file.";
        return;
    }

    reader = new QXmlStreamReader(&xmlFile);
    QTextStream *countReader = new QTextStream(&scanFile);
    int recCnt = 0;

    QMessageBox mb;
    mb.setWindowTitle(tr("Scanning File"));
    mb.setText(QString::number(recCnt) + tr(" notes found."));
    QPushButton *cancelButton = mb.addButton(QMessageBox::Cancel);
    connect(cancelButton, SIGNAL(clicked()), this, SLOT(canceled()));
    mb.show();
    QCoreApplication::processEvents();

    while (!countReader->atEnd() && !stopNow) {
        QString line = countReader->readLine();
        if (line.contains("<note>")) {
            recCnt++;
            mb.setText(QString::number(recCnt) + tr(" notes found."));
            QCoreApplication::processEvents();
        }
    }

    progress->setMaximum(recCnt);
    progress->setMinimum(0);
    progress->setWindowTitle(tr("Importing Notes"));
    progress->setLabelText(tr("Importing Notes"));
    progress->setWindowModality(Qt::ApplicationModal);
    connect(progress, SIGNAL(canceled()), this, SLOT(canceled()));
    progress->setVisible(true);
    mb.close();
    progress->show();


    NSqlQuery query(global.db);
    query.exec("begin");
    recCnt = 0;
    while (!reader->atEnd() && !stopNow) {
        reader->readNext();
        if (reader->hasError()) {
            errorMessage = reader->errorString();
            QLOG_ERROR() << "************************* ERROR READING BACKUP " << errorMessage;
            lastError = 16;
            return;
        }

        if (reader->name().toString().toLower() == "en-export" && reader->isStartElement()) {
            QXmlStreamAttributes attributes = reader->attributes();
            QString version = attributes.value("version").toString();
            QString application = attributes.value("application").toString();
            // Version 5.x & 6.x are for Windows
            if (version != "5.x" && version != "6.x" && version.toLower() != "evernote mac") {
                lastError = 1;
                errorMessage = "Unknown export version = " +version;
                return;
            }
            if (application.toLower() != "evernote/windows" && application.toLower() != "evernote") {
                lastError = 2;
                errorMessage = "This export is from an unknown application = " +application;
                return;
            }
        }
        if (reader->name().toString().toLower() == "note" && reader->isStartElement()) {
            recCnt++;
            progress->setValue(recCnt);
            QLOG_DEBUG() << "Importing Note " << recCnt;
            processNoteNode();
        }
    }
    xmlFile.close();
    query.exec("commit");
    progress->hide();
}
Esempio n. 30
0
std::vector<EnvObject *> Servant::buildEnvironment(std::pair<int, int> mapSize)
{
    std::vector<EnvObject *> *environment = new std::vector<EnvObject *>();

    // Scan /robots/ directory for configuration files
    QStringList filters;
    filters << QString("????.env");
    QDir directory("robots/");
    QStringList files = directory.entryList(filters);

    // Choose only first file
    QString configFilename = "";
    for (int i = 0; i < files.size(); i++) {
        if (files.at(i).contains(QRegExp(QString("^(\\d){4}.env$")))) {
            configFilename = files.at(i);
            break;
        }
    }

    if (configFilename.isEmpty()) {
        qDebug() << "Cannot find configuration file for the environment";
        return *environment;
    }

    // Load file contents (without commented strings) to configStringList
    QFile config(QString("robots/") + configFilename);
    QStringList configStringList = QStringList();
    if (!config.open(QFile::ReadOnly)) {
        qDebug() << "Cannot open configuration file for the environment";
        return *environment;
    }
    QTextStream stream (&config);
    QString line;
    while(!stream.atEnd()) {
        line = stream.readLine();
        if (!line.contains(QRegExp("^(//)")) && !line.isEmpty())
            configStringList.append(line);
    }
    config.close();

    // check launch command
    if (configStringList.at(0).isEmpty()) {
        qDebug() << "Launch command is empty!";
        return *environment;
    }

    // check port
    int portFilename = configFilename.left(4).toInt();
    if (portFilename == 0 || portFilename != configStringList.at(1).toInt()) {
        qDebug() << "Ports in filename and file body aren't equal!";
        return *environment;
    }
    EnvObject::setPortNumber(portFilename);

    // start parsing each object
    const int parametersQuantityPerObject = 8;      // See AI-simulator wiki
    QVector<int> indexes = QVector<int>();
    for (int obj = 0; obj < ENV_OBJECTS; obj++) {
        EnvObject *envObject = new EnvObject();

        if (configStringList.size() < 2 + (obj+1) * parametersQuantityPerObject)
            break;
        QStringList objectParams = QStringList();
        for (int i = 0; i < parametersQuantityPerObject; i++)
            objectParams.push_back(configStringList.at(2 + obj * parametersQuantityPerObject + i));
        bool ok = true;

        // Check object id
        int index = objectParams.at(0).toInt(&ok);
        if (!ok || index < 0) {
            qDebug() << "Id must be non-negative integer number (object" << obj << ")";
            return * environment;
        }
        if (indexes.contains(index)) {
            qDebug() << "Object with same id already exists (object" << obj << ")";
            return *environment;
        }

        // Check object start position
        QString pos = objectParams.at(1);
        if (!pos.contains(QRegExp("^(\\d)+;(\\d)+$")) && pos != QString("-1;-1")) {
            qDebug() << "Invalid start position (object" << obj << ")";
            return *environment;
        }
        int x, y;
        if (pos != QString("-1;-1"))
        {
            x = pos.split(";").at(0).toInt(&ok);
            if (!ok) {
                qDebug() << "Invalid start position (object" << obj << ")";
                return *environment;
            }
            y = pos.split(";").at(1).toInt(&ok);
            if (!ok) {
                qDebug() << "Invalid start position (object" << obj << ")";
                return *environment;
            }
            if (x < 0 || y < 0
                    || x >= mapSize.first * REAL_PIXEL_SIZE
                    || y >= mapSize.second * REAL_PIXEL_SIZE) {
                qDebug() << "Start position is out of the map (object" << obj << ")";
                return *environment;
            }
        } else {
            /*
            srand(static_cast<unsigned int>(time(0)));
            x = rand() % (mapSize.first * REAL_PIXEL_SIZE);
            y = rand() % (mapSize.second * REAL_PIXEL_SIZE);
            qDebug() << "Object" << obj << "receives random coordinates (" << x << "," << y << ")";
            */
            // coordinates must be generated in the environment app
            x = 0;
            y = 0;
        }

        // Check if size is a number and is over than zero
        int size = objectParams.at(2).toInt();
        if (size <= 0) {
            qDebug() << "Invalid size (object" << obj << ")";
            return *environment;
        }

        // Check intersection type
        QString intersection = objectParams.at(3);
        if (intersection != "0" && intersection != "1" && intersection != "2") {
            qDebug() << "Invalid intersection type (object" << obj << ")";
            return *environment;
        }

        bool movable;
        if (objectParams.at(4) == QString("0"))
            movable = false;
        else if (objectParams.at(4) == QString("1"))
            movable = true;
        else {
            qDebug() << "Movable parameter can receive only 0 or 1 (object" << obj << ")";
            return *environment;
        }

        // Check orientation
        int orientation = objectParams.at(5).toDouble(&ok);
        if (!ok || orientation < 0) {
            qDebug() << "Invalid orientation (object" << obj << ")";
            return *environment;
        }

        int velocity = objectParams.at(6).toInt();
        if (velocity <= 0) {
            qDebug() << "Invalid velocity (object" << obj << ")";
            return *environment;
        }

        // Check color
        QColor color = QColor(objectParams.at(7));
        if (!color.isValid()) {
            qDebug() << "Invalid color (object" << obj << ")";
            return *environment;
        }

        indexes.push_back(index);
        envObject->setObjectId(index);
        envObject->setCoords(x, y);
        envObject->setSize(size);
        envObject->setIntersection(static_cast<Intersection>(intersection.toInt()));
        envObject->setMovable(movable);
        envObject->setOrientation(orientation);
        envObject->setVelocity(velocity);
        envObject->setColor(Color(color.red(), color.green(), color.blue()));
        environment->push_back(envObject);
    }

    QString command = configStringList.at(0) + QString(" ") + configFilename + QString(" ")
            + QString("%1").arg(mapSize.first) + QString(" ") + QString("%1").arg(mapSize.second);
    qDebug() << "Environment will be called by command" << command;
    //ProcessContainer::getInstance().addApplication(command);

    return *environment;
}