Example #1
0
void CDPWizard::promptForFileName(QLineEdit * theLineEdit, QString theShortName, QString theLongName)
{
    QSettings myQSettings;
    QString myFilterList;
    FileReader::getGdalDriverMap(myFilterList);
    QString myWorkDirString = myQSettings.readEntry("/qgis/cdpwizard/DefaultDirectories/" + theShortName + "Dir",QDir::homeDirPath());

    std::cout << "Filter List: " << myFilterList << std::endl;
    QString myFileNameQString;
    QFileDialog myFileDialog (myWorkDirString,myFilterList,0,"Select " + theLongName ,"Select " + theLongName);
    QString myLastFilter = myQSettings.readEntry("/qgis/cdpwizard/DefaultDirectories/" + theShortName + "Filter","");
    if (!myLastFilter.isEmpty())
    {
      myFileDialog.setSelectedFilter(myLastFilter);
    }
    if ( myFileDialog.exec() == QDialog::Accepted )
    {
      myFileNameQString = myFileDialog.selectedFile();
      theLineEdit->setText(myFileNameQString);
      QFileInfo myFileInfo(myFileNameQString);
      myQSettings.writeEntry("/qgis/cdpwizard/DefaultDirectories/" + theShortName + "Dir",myFileInfo.dirPath());
      myQSettings.writeEntry("/qgis/cdpwizard/DefaultDirectories/" + theShortName + "Filter",myFileDialog.selectedFilter());
      checkInputFilenames();
    }
}
Example #2
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWebView* view;
    view = new QWebView();
    ViewLoader loader;

    //connect view signals with splashscreen
    QObject::connect(view, SIGNAL(loadStarted()),
                      &loader, SLOT(on_loadStarted()));
    QObject::connect(view, SIGNAL(loadProgress(int)),
                      &loader, SLOT(on_loadProgress(int)));
    QObject::connect(view, SIGNAL(loadFinished(bool)),
                      &loader, SLOT(on_loadFinished(bool)));

    Sensor *sensor = new Sensor(view);
    qDebug() << QDir::currentPath();
    QFileInfo myFileInfo("html/index.html");
    QUrl url = QUrl( "file://" + myFileInfo.absoluteFilePath());
    qDebug() << url;
    view->load(url);
    view->showFullScreen();
    return app.exec();
}
Example #3
0
QString HeatmapGui::outputFilename() const
{
  QString outputFileName;
  QString outputFormat;

  outputFileName = mOutputRasterLineEdit->text();
  QFileInfo myFileInfo( outputFileName );
  if ( outputFileName.isEmpty() || !myFileInfo.dir().exists() )
  {
    QMessageBox::information( nullptr, tr( "Invalid output filename" ), tr( "Please enter a valid output file path and name." ) );
    return QString::null;
  }

  // The output format
  outputFormat = mFormatCombo->itemData( mFormatCombo->currentIndex() ).toString();
  // append the file format if the suffix is empty
  QString suffix = myFileInfo.suffix();
  if ( suffix.isEmpty() )
  {
    QMap<QString, QString>::const_iterator it = mExtensionMap.find( outputFormat );
    if ( it != mExtensionMap.end() && it.key() == outputFormat )
    {
      // making sure that there is really a extension value available
      // Some drivers don't seem to have any extension at all
      if ( !it.value().isEmpty() )
      {
        outputFileName.append( '.' );
        outputFileName.append( it.value() );
      }
    }
  }

  return outputFileName;
}
Example #4
0
QString myStatusDir(const QString &fn){
 QString dp = qApp->applicationDirPath();
 QString fp = dp; fp.append("/").append(fn);
 
 QFileInfo fi = myFileInfo(fp);
 if (fi.exists() && !fi.isWritable()) 
  showMessage(QString("File is not writable %1").arg(fp));
 return fp;
};
Example #5
0
QString QgsMapLayer::saveSldStyle( const QString &theURI, bool &theResultFlag )
{
  QString errorMsg;
  QDomDocument myDocument;
  exportSldStyle( myDocument, errorMsg );
  if ( !errorMsg.isNull() )
  {
    theResultFlag = false;
    return errorMsg;
  }
  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );

  // check if the uri is a file or ends with .sld,
  // which indicates that it should become one
  QString filename;
  if ( vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = theURI.split( "|" );
    filename = theURIParts[0];
  }
  else if ( vlayer->providerType() == "delimitedtext" )
  {
    filename = QUrl::fromEncoded( theURI.toAscii() ).toLocalFile();
  }
  else
  {
    filename = theURI;
  }

  QFileInfo myFileInfo( filename );
  if ( myFileInfo.exists() || filename.endsWith( ".sld", Qt::CaseInsensitive ) )
  {
    QFileInfo myDirInfo( myFileInfo.path() );  //excludes file name
    if ( !myDirInfo.isWritable() )
    {
      return tr( "The directory containing your dataset needs to be writable!" );
    }

    // now construct the file name for our .sld style file
    QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".sld";

    QFile myFile( myFileName );
    if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
    {
      QTextStream myFileStream( &myFile );
      // save as utf-8 with 2 spaces for indents
      myDocument.save( myFileStream, 2 );
      myFile.close();
      theResultFlag = true;
      return tr( "Created default style file as %1" ).arg( myFileName );
    }
  }

  theResultFlag = false;
  return tr( "ERROR: Failed to created SLD style file as %1. Check file permissions and retry." ).arg( filename );
}
Example #6
0
QString QgsMapLayer::styleURI( )
{
  QString myURI = publicSource();

  // if file is using the VSIFILE mechanism, remove the prefix
  if ( myURI.startsWith( "/vsigzip/", Qt::CaseInsensitive ) )
  {
    myURI.remove( 0, 9 );
  }
  else if ( myURI.startsWith( "/vsizip/", Qt::CaseInsensitive ) &&
            myURI.endsWith( ".zip", Qt::CaseInsensitive ) )
  {
    // ideally we should look for .qml file inside zip file
    myURI.remove( 0, 8 );
  }
  else if ( myURI.startsWith( "/vsitar/", Qt::CaseInsensitive ) &&
            ( myURI.endsWith( ".tar", Qt::CaseInsensitive ) ||
              myURI.endsWith( ".tar.gz", Qt::CaseInsensitive ) ||
              myURI.endsWith( ".tgz", Qt::CaseInsensitive ) ) )
  {
    // ideally we should look for .qml file inside tar file
    myURI.remove( 0, 8 );
  }

  QFileInfo myFileInfo( myURI );
  QString key;

  if ( myFileInfo.exists() )
  {
    // if file is using the /vsizip/ or /vsigzip/ mechanism, cleanup the name
    if ( myURI.endsWith( ".gz", Qt::CaseInsensitive ) )
      myURI.chop( 3 );
    else if ( myURI.endsWith( ".zip", Qt::CaseInsensitive ) )
      myURI.chop( 4 );
    else if ( myURI.endsWith( ".tar", Qt::CaseInsensitive ) )
      myURI.chop( 4 );
    else if ( myURI.endsWith( ".tar.gz", Qt::CaseInsensitive ) )
      myURI.chop( 7 );
    else if ( myURI.endsWith( ".tgz", Qt::CaseInsensitive ) )
      myURI.chop( 4 );
    else if ( myURI.endsWith( ".gz", Qt::CaseInsensitive ) )
      myURI.chop( 3 );
    myFileInfo.setFile( myURI );
    // get the file name for our .qml style file
    key = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".qml";
  }
  else
  {
    key = publicSource();
  }

  return key;
}
void SaveLevelInfo::FileDialogButton_clicked()
{
    // use QFileInfo to brush up the file name
    QFileInfo myFileInfo(ui.theFileNameField->text());

    isUserOKOverwritingFile = false;

    QString myFileName = QFileDialog::getSaveFileName(this,
                                                      tr("Save Level"), myFileInfo.absoluteFilePath(), tr("TBE levels (*.tbe *.xml)"));

    if (performFileExists(myFileName) == false)
        return;

    ui.theFileNameField->setText(myFileName);
}
Example #8
0
QString QgsMapLayer::loadDefaultStyle( bool & theResultFlag )
{
  QString myURI = publicSource();
  QFileInfo myFileInfo( myURI );
  QString key;
  if ( myFileInfo.exists() )
  {
    // get the file name for our .qml style file
    key = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".qml";
  }
  else
  {
    key = myURI;
  }
  return loadNamedStyle( key, theResultFlag );
}
bool QgsProject::write()
{
  clearError();

  // if we have problems creating or otherwise writing to the project file,
  // let's find out up front before we go through all the hand-waving
  // necessary to create all the Dom objects
  if ( !imp_->file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
  {
    imp_->file.close();         // even though we got an error, let's make
    // sure it's closed anyway

    setError( tr( "Unable to save to file %1" ).arg( imp_->file.fileName() ) );
    return false;
  }
  QFileInfo myFileInfo( imp_->file );
  if ( !myFileInfo.isWritable() )
  {
    // even though we got an error, let's make
    // sure it's closed anyway
    imp_->file.close();
    setError( tr( "%1 is not writable. Please adjust permissions (if possible) and try again." )
              .arg( imp_->file.fileName() ) );
    return false;
  }

  QDomImplementation DomImplementation;

  QDomDocumentType documentType =
    DomImplementation.createDocumentType( "qgis", "http://mrcc.com/qgis.dtd",
                                          "SYSTEM" );
  std::auto_ptr < QDomDocument > doc =
    std::auto_ptr < QDomDocument > ( new QDomDocument( documentType ) );


  QDomElement qgisNode = doc->createElement( "qgis" );
  qgisNode.setAttribute( "projectname", title() );
  qgisNode.setAttribute( "version", QString( "%1" ).arg( QGis::QGIS_VERSION ) );

  doc->appendChild( qgisNode );

  // title
  QDomElement titleNode = doc->createElement( "title" );
  qgisNode.appendChild( titleNode );

  QDomText titleText = doc->createTextNode( title() );  // XXX why have title TWICE?
  titleNode.appendChild( titleText );

  // let map canvas and legend write their information
  emit writeProject( *doc );

  // within top level node save list of layers
  QMap<QString, QgsMapLayer*> & layers = QgsMapLayerRegistry::instance()->mapLayers();

  // Iterate over layers in zOrder
  // Call writeXML() on each
  QDomElement projectLayersNode = doc->createElement( "projectlayers" );
  projectLayersNode.setAttribute( "layercount", qulonglong( layers.size() ) );

  QMap<QString, QgsMapLayer*>::iterator li = layers.begin();
  while ( li != layers.end() )
  {
    //QgsMapLayer *ml = QgsMapLayerRegistry::instance()->mapLayer(*li);
    QgsMapLayer* ml = li.value();

    if ( ml )
    {
      QString externalProjectFile = layerIsEmbedded( ml->id() );
      QHash< QString, QPair< QString, bool> >::const_iterator emIt = mEmbeddedLayers.find( ml->id() );
      if ( emIt == mEmbeddedLayers.constEnd() )
      {
        ml->writeXML( projectLayersNode, *doc );
      }
      else //layer defined in an external project file
      {
        //only save embedded layer if not managed by a legend group
        if ( emIt.value().second )
        {
          QDomElement mapLayerElem = doc->createElement( "maplayer" );
          mapLayerElem.setAttribute( "embedded", 1 );
          mapLayerElem.setAttribute( "project", writePath( emIt.value().first ) );
          mapLayerElem.setAttribute( "id", ml->id() );
          projectLayersNode.appendChild( mapLayerElem );
        }
      }
    }
    li++;
  }

  qgisNode.appendChild( projectLayersNode );

  // now add the optional extra properties

  dump_( imp_->properties_ );

  QgsDebugMsg( QString( "there are %1 property scopes" ).arg( static_cast<int>( imp_->properties_.count() ) ) );

  if ( !imp_->properties_.isEmpty() ) // only worry about properties if we
    // actually have any properties
  {
    imp_->properties_.writeXML( "properties", qgisNode, *doc );
  }

  // now wrap it up and ship it to the project file
  doc->normalize();             // XXX I'm not entirely sure what this does

  //QString xml = doc->toString(4); // write to string with indentation of four characters
  // (yes, four is arbitrary)

  // const char * xmlString = xml; // debugger probe point
  // qDebug( "project file output:\n\n" + xml );

  QTextStream projectFileStream( &imp_->file );

  //projectFileStream << xml << endl;
  doc->save( projectFileStream, 4 );  // save as utf-8
  imp_->file.close();

  // check if the text stream had no error - if it does
  // the user will get a message so they can try to resolve the
  // situation e.g. by saving project to a volume with more space
  //
  if ( projectFileStream.pos() == -1  || imp_->file.error() != QFile::NoError )
  {
    setError( tr( "Unable to save to file %1. Your project "
                  "may be corrupted on disk. Try clearing some space on the volume and "
                  "check file permissions before pressing save again." )
              .arg( imp_->file.fileName() ) );
    return false;
  }

  dirty( false );               // reset to pristine state

  emit projectSaved();

  return true;
} // QgsProject::write
Example #10
0
QString QgsMapLayer::saveNamedStyle( const QString &theURI, bool &theResultFlag )
{
  QString myErrorMessage;
  QDomDocument myDocument;
  exportNamedStyle( myDocument, myErrorMessage );

  // check if the uri is a file or ends with .qml,
  // which indicates that it should become one
  // everything else goes to the database
  QString filename;

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = theURI.split( "|" );
    filename = theURIParts[0];
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    filename = QUrl::fromEncoded( theURI.toAscii() ).toLocalFile();
  }
  else
  {
    filename = theURI;
  }

  QFileInfo myFileInfo( filename );
  if ( myFileInfo.exists() || filename.endsWith( ".qml", Qt::CaseInsensitive ) )
  {
    QFileInfo myDirInfo( myFileInfo.path() );  //excludes file name
    if ( !myDirInfo.isWritable() )
    {
      return tr( "The directory containing your dataset needs to be writable!" );
    }

    // now construct the file name for our .qml style file
    QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".qml";

    QFile myFile( myFileName );
    if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
    {
      QTextStream myFileStream( &myFile );
      // save as utf-8 with 2 spaces for indents
      myDocument.save( myFileStream, 2 );
      myFile.close();
      theResultFlag = true;
      return tr( "Created default style file as %1" ).arg( myFileName );
    }
    else
    {
      theResultFlag = false;
      return tr( "ERROR: Failed to created default style file as %1. Check file permissions and retry." ).arg( myFileName );
    }
  }
  else
  {
    QString qml = myDocument.toString();

    // read from database
    sqlite3 *myDatabase;
    sqlite3_stmt *myPreparedStatement;
    const char *myTail;
    int myResult;

    myResult = sqlite3_open( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( "qgis.qmldb" ).toUtf8().data(), &myDatabase );
    if ( myResult != SQLITE_OK )
    {
      return tr( "User database could not be opened." );
    }

    QByteArray param0 = theURI.toUtf8();
    QByteArray param1 = qml.toUtf8();

    QString mySql = "create table if not exists tbl_styles(style varchar primary key,qml varchar)";
    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
    if ( myResult == SQLITE_OK )
    {
      if ( sqlite3_step( myPreparedStatement ) != SQLITE_DONE )
      {
        sqlite3_finalize( myPreparedStatement );
        sqlite3_close( myDatabase );
        theResultFlag = false;
        return tr( "The style table could not be created." );
      }
    }

    sqlite3_finalize( myPreparedStatement );

    mySql = "insert into tbl_styles(style,qml) values (?,?)";
    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
    if ( myResult == SQLITE_OK )
    {
      if ( sqlite3_bind_text( myPreparedStatement, 1, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK &&
           sqlite3_bind_text( myPreparedStatement, 2, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK &&
           sqlite3_step( myPreparedStatement ) == SQLITE_DONE )
      {
        theResultFlag = true;
        myErrorMessage = tr( "The style %1 was saved to database" ).arg( theURI );
      }
    }

    sqlite3_finalize( myPreparedStatement );

    if ( !theResultFlag )
    {
      QString mySql = "update tbl_styles set qml=? where style=?";
      myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
      if ( myResult == SQLITE_OK )
      {
        if ( sqlite3_bind_text( myPreparedStatement, 2, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK &&
             sqlite3_bind_text( myPreparedStatement, 1, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK &&
             sqlite3_step( myPreparedStatement ) == SQLITE_DONE )
        {
          theResultFlag = true;
          myErrorMessage = tr( "The style %1 was updated in the database." ).arg( theURI );
        }
        else
        {
          theResultFlag = false;
          myErrorMessage = tr( "The style %1 could not be updated in the database." ).arg( theURI );
        }
      }
      else
      {
        theResultFlag = false;
        myErrorMessage = tr( "The style %1 could not be inserted into database." ).arg( theURI );
      }

      sqlite3_finalize( myPreparedStatement );
    }

    sqlite3_close( myDatabase );
  }

  return myErrorMessage;
}
Example #11
0
QStringList ClimateImporter::import(QString theInputFile, QString theOutputDir, QString theFileType)
{

  // I should take a moment to explain before we start reading the data that
  // hadley cells are rectangular (3.75deg x 2.5deg). In order to make them square
  // we need to multiply the number of cells in each direction to get them to the
  // lowest common denominator. That means x cells are multiplied by 15
  // and y cells are multiplied by 10. We then end up with a block of 15x10 cells representing
  // the original rectangular cell. The hadley matrix originally was 96x73, but now
  // it will be 1440 x 730. Then lastly we discard the5 top rows and 5 bottom rows
  // to end up with a final resolution of 1440x720 (0.25 x 0.25 cells)
  float myInputCellSizeX = 0;
  int myXMultiplier = 0;
  int myYMultiplier = 0;
  int myEndRowMultiplier = 0;
  bool myDoMeridianShiftFlag = false;

  ClimateFileReader myReader;
  if (theFileType=="CRU")
  {
    myReader.initialise(theInputFile,ClimateFileReader::CRU_CL1_MONTHLY);

    myInputCellSizeX = 0.5;
    myXMultiplier = 2;
    myYMultiplier = 2;
    myEndRowMultiplier = 2;
    myDoMeridianShiftFlag = true;
  }
  else if (theFileType=="Hadley")
  {
    myReader.initialise(theInputFile,ClimateFileReader::HADLEY_SRES_MEAN);
    myInputCellSizeX = 3.75;
    myXMultiplier = 15;
    myYMultiplier = 10;
    myEndRowMultiplier = 5;
    myDoMeridianShiftFlag = true;
  }
  else // Invalid filetype
  {
    emit error("Invalid file type");
    return QStringList ();
  }
  connect(&myReader, SIGNAL(error(QString)), this, SLOT(propogateError(QString)));
  connect(&myReader, SIGNAL(message(QString)), this, SLOT(propogateMessage(QString)));

  //calculate the base name of the file without its extension of path
  QFileInfo myFileInfo(theInputFile);
  QString myBaseName = myFileInfo.baseName();

  int myXDim = myReader.xDim();
  int myYDim = myReader.yDim();
  int myBlockCount = myReader.blockCount();

  QStringList myOutputFileList;

  // shameless hardcoding taking place here....
  QString myHeader;
  myHeader += "ncols         " + QString::number(myXDim*myXMultiplier ) + "\r\n";
  myHeader += "nrows         " + QString::number(((myYDim-2)*(myYMultiplier))+(myEndRowMultiplier*2) ) + "\r\n";
  myHeader += "xllcorner     -180\r\n";
  myHeader += "yllcorner     -90\r\n";
  myHeader += "cellsize       " + QString::number(1.0/(static_cast<float>(myXDim*myXMultiplier)/360) ) + "\r\n";
  //note hdaley seen to use +9999 for no data....
  myHeader += "NODATA_value  -9999\r\n";

  //make a meridian shift object
  MeridianSwitcher mySwitcher;
  connect(&mySwitcher, SIGNAL(error(QString)), this, SLOT(propogateError(QString)));
  connect(&mySwitcher, SIGNAL(message(QString)), this, SLOT(propogateMessage(QString)));

  //for debugging....to be removed...
  //myReader.printBlockMarkers();
  //myReader.printFirstCellInEachBlock();
  //myReader.printLastCellInEachBlock();

  for (int i=0; i<myBlockCount;i++)
  {
    if (!myReader.setActiveBlock(i))
    {
      break;
    }
    //note filereader use base 1 not base 0!
    emit message("Processing block " + QString::number(i+1));
    QString myOutputFileName;
    //months are base1 !
    int myMonthNo = i+1;
    if (myMonthNo<10)
    {
      myOutputFileName = theOutputDir + "/" + myBaseName + "_0" + QString::number(myMonthNo).toLocal8Bit() + ".asc";
    }
    else
    {
      myOutputFileName = theOutputDir + "/" + myBaseName + "_" + QString::number(myMonthNo).toLocal8Bit() + ".asc";
    }
    QFile myOutputFile (myOutputFileName);
    //note file is not appended to but overwritten!
    if ( myOutputFile.open( QIODevice::WriteOnly ) )
    {
      myOutputFileList.append(myOutputFileName);
      QTextStream myOutputTextStream( &myOutputFile );
      myOutputTextStream << myHeader.toLocal8Bit();
      int myCurrentCount=0;
      QString myCurrentLine;
      while (!myReader.isAtMatrixEnd())
      {
        float myFloat = myReader.getElement();
        //repeat in the x direction the prescribed amount of times
        for (int x=1 ; x <= myXMultiplier; x++)
        {
          myCurrentLine +=  QString::number(myFloat);
          if (x < myXMultiplier)
          {
            myCurrentLine += " ";
          }
        }
        //if we are at rows' end we must repeat in the y direction too....
        //(simply by writing the same line several times)
        if (myReader.currentCol()==myXDim)
        {
          myCurrentLine += "\r\n";
          int myCurrentRowNo = myReader.currentRow();
          if (myCurrentRowNo==1 || myCurrentRowNo == myYDim)
          {
            //qDebug(myCurrentLine.toLocal8Bit());
            for (int y=0; y < myEndRowMultiplier; y++)
            {
              myOutputTextStream << myCurrentLine.toLocal8Bit();
            }
          }
          else
          {
            for (int y=0; y < myYMultiplier; y++)
            {
              myOutputTextStream << myCurrentLine.toLocal8Bit();
            }
          }
          myCurrentLine="";
        }
        else
        {
          myCurrentLine += " ";
        }
        myCurrentCount++;
      }
      myOutputFile.close();
    }
    else
    {
      emit error ("Could not open output file " + myOutputFileName.toLocal8Bit() + " for writing.");
      break;
    }

    if (myDoMeridianShiftFlag)
    {
      QString myMeridianShiftOutputFileName;
      if (myMonthNo<10)
      {
        myMeridianShiftOutputFileName = theOutputDir + "/" + myBaseName + "_shift_0" + QString::number(myMonthNo).toLocal8Bit() + ".asc";
      }
      else
      {
        myMeridianShiftOutputFileName = theOutputDir + "/" + myBaseName + "_shift_" + QString::number(myMonthNo).toLocal8Bit() + ".asc";
      }
      emit message("Shifting meridian");
      mySwitcher.doSwitch(myOutputFileName, myMeridianShiftOutputFileName);
    }
    emit updateProgress (i,myBlockCount);


  }
  emit message("Conversion Complete, " + QString::number(myBlockCount) + " blocks processed succssfully.");
  return myOutputFileList;
}
Example #12
0
QString QgsMapLayer::saveSldStyle( const QString theURI, bool & theResultFlag )
{
  QDomDocument myDocument = QDomDocument();

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

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

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

  QString errorMsg;
  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  if ( !vlayer )
  {
    theResultFlag = false;
    return tr( "Could not save symbology because:\n%1" ).arg( "Non-vector layers not supported yet" );
  }

  if ( !vlayer->writeSld( namedLayerNode, myDocument, errorMsg ) )
  {
    theResultFlag = false;
    return tr( "Could not save symbology because:\n%1" ).arg( errorMsg );
  }

  // check if the uri is a file or ends with .sld,
  // which indicates that it should become one
  QString filename;
  if ( vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = theURI.split( "|" );
    filename = theURIParts[0];
  }
  else if ( vlayer->providerType() == "delimitedtext" )
  {
    filename = QUrl::fromEncoded( theURI.toAscii() ).toLocalFile();
  }
  else
  {
    filename = theURI;
  }

  QFileInfo myFileInfo( filename );
  if ( myFileInfo.exists() || filename.endsWith( ".sld", Qt::CaseInsensitive ) )
  {
    QFileInfo myDirInfo( myFileInfo.path() );  //excludes file name
    if ( !myDirInfo.isWritable() )
    {
      return tr( "The directory containing your dataset needs to be writable!" );
    }

    // now construct the file name for our .sld style file
    QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".sld";

    QFile myFile( myFileName );
    if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
    {
      QTextStream myFileStream( &myFile );
      // save as utf-8 with 2 spaces for indents
      myDocument.save( myFileStream, 2 );
      myFile.close();
      theResultFlag = true;
      return tr( "Created default style file as %1" ).arg( myFileName );
    }
  }

  theResultFlag = false;
  return tr( "ERROR: Failed to created SLD style file as %1. Check file permissions and retry." ).arg( filename );
}
Example #13
0
QString QgsMapLayer::saveNamedStyle( const QString theURI, bool & theResultFlag )
{
  QString myErrorMessage;

  QDomImplementation DomImplementation;
  QDomDocumentType documentType =
    DomImplementation.createDocumentType(
      "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" );
  QDomDocument myDocument( documentType );
  QDomElement myRootNode = myDocument.createElement( "qgis" );
  myRootNode.setAttribute( "version", QString( "%1" ).arg( QGis::QGIS_VERSION ) );
  myDocument.appendChild( myRootNode );

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

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

  QString errorMsg;
  if ( !writeSymbology( myRootNode, myDocument, errorMsg ) )
  {
    return tr( "Could not save symbology because:\n%1" ).arg( errorMsg );
  }

  // check if the uri is a file or ends with .qml,
  // which indicates that it should become one
  // everything else goes to the database
  QString filename;

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = theURI.split( "|" );
    filename = theURIParts[0];
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    filename = QUrl::fromEncoded( theURI.toAscii() ).toLocalFile();
  }
  else
  {
    filename = theURI;
  }

  QFileInfo myFileInfo( filename );
  if ( myFileInfo.exists() || filename.endsWith( ".qml", Qt::CaseInsensitive ) )
  {
    QFileInfo myDirInfo( myFileInfo.path() );  //excludes file name
    if ( !myDirInfo.isWritable() )
    {
      return tr( "The directory containing your dataset needs to be writable!" );
    }

    // now construct the file name for our .qml style file
    QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".qml";

    QFile myFile( myFileName );
    if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
    {
      QTextStream myFileStream( &myFile );
      // save as utf-8 with 2 spaces for indents
      myDocument.save( myFileStream, 2 );
      myFile.close();
      theResultFlag = true;
      return tr( "Created default style file as %1" ).arg( myFileName );
    }
    else
    {
      theResultFlag = false;
      return tr( "ERROR: Failed to created default style file as %1. Check file permissions and retry." ).arg( myFileName );
    }
  }
  else
  {
    QString qml = myDocument.toString();

    // read from database
    sqlite3 *myDatabase;
    sqlite3_stmt *myPreparedStatement;
    const char *myTail;
    int myResult;

    myResult = sqlite3_open( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( "qgis.qmldb" ).toUtf8().data(), &myDatabase );
    if ( myResult != SQLITE_OK )
    {
      return tr( "User database could not be opened." );
    }

    QByteArray param0 = theURI.toUtf8();
    QByteArray param1 = qml.toUtf8();

    QString mySql = "create table if not exists tbl_styles(style varchar primary key,qml varchar)";
    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
    if ( myResult == SQLITE_OK )
    {
      if ( sqlite3_step( myPreparedStatement ) != SQLITE_DONE )
      {
        sqlite3_finalize( myPreparedStatement );
        sqlite3_close( myDatabase );
        theResultFlag = false;
        return tr( "The style table could not be created." );
      }
    }

    sqlite3_finalize( myPreparedStatement );

    mySql = "insert into tbl_styles(style,qml) values (?,?)";
    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
    if ( myResult == SQLITE_OK )
    {
      if ( sqlite3_bind_text( myPreparedStatement, 1, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK &&
           sqlite3_bind_text( myPreparedStatement, 2, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK &&
           sqlite3_step( myPreparedStatement ) == SQLITE_DONE )
      {
        theResultFlag = true;
        myErrorMessage = tr( "The style %1 was saved to database" ).arg( theURI );
      }
    }

    sqlite3_finalize( myPreparedStatement );

    if ( !theResultFlag )
    {
      QString mySql = "update tbl_styles set qml=? where style=?";
      myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
      if ( myResult == SQLITE_OK )
      {
        if ( sqlite3_bind_text( myPreparedStatement, 2, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK &&
             sqlite3_bind_text( myPreparedStatement, 1, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK &&
             sqlite3_step( myPreparedStatement ) == SQLITE_DONE )
        {
          theResultFlag = true;
          myErrorMessage = tr( "The style %1 was updated in the database." ).arg( theURI );
        }
        else
        {
          theResultFlag = false;
          myErrorMessage = tr( "The style %1 could not be updated in the database." ).arg( theURI );
        }
      }
      else
      {
        theResultFlag = false;
        myErrorMessage = tr( "The style %1 could not be inserted into database." ).arg( theURI );
      }

      sqlite3_finalize( myPreparedStatement );
    }

    sqlite3_close( myDatabase );
  }

  return myErrorMessage;
}
Example #14
0
const QString OmgGdal::Gdal2Ascii(const QString theFileName)
{
  std::cout << "Running gdal to ascii conversion..." << std::endl;
  QFileInfo myFileInfo(theFileName);
  QString myExt("asc");
  QString myOutFileName(QDir::convertSeparators(myFileInfo.dirPath(true)+"/"+myFileInfo.baseName() + "." + myExt));
  QFile myFile( myOutFileName );
  if ( !myFile.open( IO_WriteOnly ) )
  {
    printf("Opening output file for write failed");
    return QString("");
  }
  QTextStream myStream( &myFile );
  GDALAllRegister();
  GDALDataset  *gdalDataset = (GDALDataset *) GDALOpen( theFileName.local8Bit(), GA_ReadOnly );
  if ( gdalDataset == NULL )
  {
    std::cout <<  "Error couldn't open file: " << theFileName << std::endl;
    return QString("");
  }

  //Write the ascii headers
  myStream << getAsciiHeader(theFileName);

  //assume to be working with first band in dataset only
  GDALRasterBand  *myGdalBand = gdalDataset->GetRasterBand( 1 );
  //find out the name of the band if any
  QString myColorInterpretation = GDALGetColorInterpretationName(myGdalBand->GetColorInterpretation());
  // get the dimensions of the raster
  int myColsInt = myGdalBand->GetXSize();
  int myRowsInt = myGdalBand->GetYSize();
  double myNullValue=myGdalBand->GetNoDataValue();
  //allocate a buffer to hold one row of ints
  int myAllocationSizeInt = sizeof(uint)*myColsInt;
  uint * myScanlineAllocInt = (uint*) CPLMalloc(myAllocationSizeInt);
  for (int myCurrentRowInt=0; myCurrentRowInt < myRowsInt;myCurrentRowInt++)
  {
    //get a scanline
    CPLErr myResult = myGdalBand->RasterIO(
                        GF_Read, 0,
                        myCurrentRowInt,
                        myColsInt,
                        1,
                        myScanlineAllocInt,
                        myColsInt,
                        1,
                        GDT_UInt32,
                        0,
                        0 );
    for (int myCurrentColInt=0; myCurrentColInt < myColsInt; myCurrentColInt++)
    {
      //get the nth element from the current row
      double myDouble=myScanlineAllocInt[myCurrentColInt];
      myStream << myDouble << " "; //pixel value
    } //end of column wise loop
    myStream << "\r\n"; //dos style new line
  } //end of row wise loop
  CPLFree(myScanlineAllocInt);
  myFile.close();
  std::cout << "The output ascii file is: " << myOutFileName << std::endl;
  return myOutFileName;
}