⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 qgsogrprovider.cpp

📁 一个非常好的GIS开源新版本
💻 CPP
📖 第 1 页 / 共 3 页
字号:
  }  f.addAttribute(attindex, value);}const QgsFieldMap & QgsOgrProvider::fields() const{  return mAttributeFields;}void QgsOgrProvider::reset(){  OGR_L_ResetReading(ogrLayer);}//TODO - add sanity check for shape file layers, to include cheking to//       see if the .shp, .dbf, .shx files are all present and the layer//       actually has featuresbool QgsOgrProvider::isValid(){  return valid;}bool QgsOgrProvider::addFeature(QgsFeature& f){   bool returnValue = true;  OGRFeatureDefnH fdef=OGR_L_GetLayerDefn(ogrLayer);  OGRFeatureH feature= OGR_F_Create(fdef);  QGis::WKBTYPE ftype = f.geometry()->wkbType();  unsigned char* wkb = f.geometry()->wkbBuffer();  if( f.geometry()->wkbSize() > 0 )  {    OGRGeometryH geom = NULL;    if( OGR_G_CreateFromWkb( wkb, NULL, &geom, f.geometry()->wkbSize() )      != OGRERR_NONE )    {      return false;    }    OGR_F_SetGeometryDirectly( feature, geom );  }  QgsAttributeMap attrs = f.attributeMap();  //add possible attribute information  for(QgsAttributeMap::iterator it = attrs.begin(); it != attrs.end(); ++it)  {    int targetAttributeId = it.key();    // don't try to set field from attribute map if it's not present in layer    if (targetAttributeId >= OGR_FD_GetFieldCount(fdef))      continue;    //if(!s.isEmpty())    // continue;    //    OGRFieldDefnH fldDef = OGR_FD_GetFieldDefn( fdef, targetAttributeId );    OGRFieldType type = OGR_Fld_GetType( fldDef );    if( it->isNull() || (type!=OFTString && it->toString().isEmpty()) )    {      OGR_F_UnsetField(feature, targetAttributeId);    }    else    {      switch( type )      {        case OFTInteger:          OGR_F_SetFieldInteger(feature,targetAttributeId,it->toInt());          break;        case OFTReal:          OGR_F_SetFieldDouble(feature,targetAttributeId,it->toDouble());          break;        case OFTString:          QgsDebugMsg( QString("Writing string attribute %1 with %2, encoding %3")              .arg( targetAttributeId )              .arg( it->toString() )              .arg( mEncoding->name().data() ) );          OGR_F_SetFieldString(feature,targetAttributeId,mEncoding->fromUnicode(it->toString()).constData());          break;        default:          QgsLogger::warning("QgsOgrProvider::addFeature, no type found");          break;      }    }  }  if( OGR_L_CreateFeature(ogrLayer,feature) != OGRERR_NONE)  {    QgsLogger::warning("Writing of the feature failed");    returnValue = false;  }  ++numberFeatures;  OGR_F_Destroy( feature );  return returnValue;}bool QgsOgrProvider::addFeatures(QgsFeatureList & flist){  bool returnvalue=true;  for(QgsFeatureList::iterator it = flist.begin(); it != flist.end(); ++it)  {    if(!addFeature(*it))    {      returnvalue=false;    }  }  // flush features  OGR_L_SyncToDisk(ogrLayer);  numberFeatures = OGR_L_GetFeatureCount(ogrLayer,TRUE); //new feature count  return returnvalue;}bool QgsOgrProvider::addAttributes(const QgsNewAttributesMap & attributes){  bool returnvalue=true;  for(QgsNewAttributesMap::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter)  {    OGRFieldDefnH fielddefn =       OGR_Fld_Create(mEncoding->fromUnicode(iter.key()).data(),OFTInteger);    if(*iter=="OFTInteger")    {      OGR_Fld_SetType( fielddefn, OFTInteger );    }    else if(*iter=="OFTReal")    {      OGR_Fld_SetType( fielddefn, OFTReal );    }    else if(*iter=="OFTString")    {      OGR_Fld_SetType( fielddefn, OFTString );    }    else    {      QgsLogger::warning("QgsOgrProvider::addAttributes, type not found");      returnvalue=false;      continue;    }    if( OGR_L_CreateField(ogrLayer,fielddefn,TRUE) != OGRERR_NONE)    {      QgsLogger::warning("QgsOgrProvider.cpp: writing of OFTInteger field failed");	      returnvalue=false;    }    OGR_Fld_Destroy( fielddefn );  }  return returnvalue;}bool QgsOgrProvider::changeAttributeValues(const QgsChangedAttributesMap & attr_map){     for(QgsChangedAttributesMap::const_iterator it = attr_map.begin(); it != attr_map.end(); ++it)  {    long fid = (long) it.key();    OGRFeatureH of = OGR_L_GetFeature( ogrLayer, fid );    if ( !of )    {      QgsLogger::warning("QgsOgrProvider::changeAttributeValues, Cannot read feature, cannot change attributes");      return false;    }    const QgsAttributeMap& attr = it.value();    for( QgsAttributeMap::const_iterator it2 = attr.begin(); it2 != attr.end(); ++it2 )    {      int f = it2.key();      OGRFieldDefnH fd = OGR_F_GetFieldDefnRef( of, f );      if (fd == NULL)      {        QgsLogger::warning("QgsOgrProvider::changeAttributeValues, Field " + QString::number(f) + " doesn't exist");        continue;      }      OGRFieldType type = OGR_Fld_GetType( fd );      if( it2->isNull() || (type!=OFTString && it2->toString().isEmpty()) )      {        OGR_F_UnsetField( of, f);      }      else      {                switch ( type )        {          case OFTInteger:            OGR_F_SetFieldInteger ( of, f, it2->toInt() );            break;          case OFTReal:            OGR_F_SetFieldDouble ( of, f, it2->toDouble() );            break;          case OFTString:            OGR_F_SetFieldString ( of, f, mEncoding->fromUnicode(it2->toString()).constData() );            break;          default:            QgsLogger::warning("QgsOgrProvider::changeAttributeValues, Unknown field type, cannot change attribute");            break;        }      }    }    OGR_L_SetFeature( ogrLayer, of );  }  OGR_L_SyncToDisk( ogrLayer );  return true;}bool QgsOgrProvider::changeGeometryValues(QgsGeometryMap & geometry_map){  OGRFeatureH theOGRFeature = 0;  OGRGeometryH theNewGeometry = 0;  for (QgsGeometryMap::iterator it = geometry_map.begin(); it != geometry_map.end(); ++it)  {    theOGRFeature = OGR_L_GetFeature(ogrLayer,it.key());    if(!theOGRFeature)    {      QgsLogger::warning("QgsOgrProvider::changeGeometryValues, cannot find feature");      continue;    }    //create an OGRGeometry    if (OGR_G_CreateFromWkb(it->wkbBuffer(),      OGR_L_GetSpatialRef(ogrLayer),      &theNewGeometry,      it->wkbSize()) != OGRERR_NONE)    {      QgsLogger::warning("QgsOgrProvider::changeGeometryValues, error while creating new OGRGeometry");      OGR_G_DestroyGeometry( theNewGeometry );      theNewGeometry = 0;      continue;    }    if(!theNewGeometry)    {      QgsLogger::warning("QgsOgrProvider::changeGeometryValues, new geometry is NULL");      continue;    }    //set the new geometry    if(OGR_F_SetGeometryDirectly(theOGRFeature, theNewGeometry) != OGRERR_NONE)    {      QgsLogger::warning("QgsOgrProvider::changeGeometryValues, error while replacing geometry");      OGR_G_DestroyGeometry( theNewGeometry );      theNewGeometry = 0;      continue;    }    OGR_L_SetFeature(ogrLayer,theOGRFeature);    OGR_F_Destroy( theOGRFeature);  }  OGR_L_SyncToDisk(ogrLayer);  return true;}bool QgsOgrProvider::createSpatialIndex(){  QString filename=dataSourceUri().section('/',-1,-1);//find out the filename from the uri  QString layername=filename.section('.',0,0);  QString sql="CREATE SPATIAL INDEX ON "+layername;  OGR_DS_ExecuteSQL (ogrDataSource,sql.ascii(), OGR_L_GetSpatialFilter(ogrLayer),"");  //find out, if the .qix file is there  QString indexname = dataSourceUri();  indexname.truncate(dataSourceUri().length()-filename.length());  indexname=indexname+layername+".qix";  QFile indexfile(indexname);  if(indexfile.exists())  {    return true;  }  else  {    return false;  }}bool QgsOgrProvider::deleteFeatures(const QgsFeatureIds & id){  bool returnvalue=true;  for (QgsFeatureIds::const_iterator it = id.begin(); it != id.end(); ++it)  {    if(!deleteFeature(*it))    {      returnvalue=false;    }  }  OGR_L_SyncToDisk(ogrLayer);  QString filename=dataSourceUri().section('/',-1,-1);//find out the filename from the uri  QString layername=filename.section('.',0,0);  QString sql="REPACK " + layername;  OGR_DS_ExecuteSQL(ogrDataSource,sql.toLocal8Bit().data(), NULL, NULL);  numberFeatures = OGR_L_GetFeatureCount(ogrLayer,TRUE); //new feature count  return returnvalue;}bool QgsOgrProvider::deleteFeature(int id){  OGRErr res = OGR_L_DeleteFeature(ogrLayer,id);  return (res == OGRERR_NONE);}int QgsOgrProvider::capabilities() const{  int ability = NoCapabilities;  // collect abilities reported by OGR  if (ogrLayer)  {    // Whilst the OGR documentation (e.g. at    // http://www.gdal.org/ogr/classOGRLayer.html#a17) states "The capability    // codes that can be tested are represented as strings, but #defined    // constants exists to ensure correct spelling", we always use strings    // here.  This is because older versions of OGR don't always have all    // the #defines we want to test for here.    if (OGR_L_TestCapability(ogrLayer,"RandomRead"))      // TRUE if the GetFeature() method works *efficiently* for this layer.      // TODO: Perhaps influence if QGIS caches into memory       //       (vs read from disk every time) based on this setting.    {      ability |= QgsVectorDataProvider::RandomSelectGeometryAtId;    }    else    {      ability |= QgsVectorDataProvider::SequentialSelectGeometryAtId;    }    ability |= QgsVectorDataProvider::SelectGeometryAtId;    if (OGR_L_TestCapability(ogrLayer,"SequentialWrite"))      // TRUE if the CreateFeature() method works for this layer.    {      ability |= QgsVectorDataProvider::AddFeatures;    }    if (OGR_L_TestCapability(ogrLayer,"DeleteFeature"))      // TRUE if this layer can delete its features    {      ability |= DeleteFeatures;    }    if (OGR_L_TestCapability(ogrLayer,"RandomWrite"))      // TRUE if the SetFeature() method is operational on this layer.    {      // TODO According to http://shapelib.maptools.org/ (Shapefile C Library V1.2)      // TODO "You can't modify the vertices of existing structures".      // TODO Need to work out versions of shapelib vs versions of GDAL/OGR      // TODO And test appropriately.      ability |= ChangeAttributeValues;      ability |= QgsVectorDataProvider::ChangeGeometries;    }    if (OGR_L_TestCapability(ogrLayer,"FastSpatialFilter"))      // TRUE if this layer implements spatial filtering efficiently.      // Layers that effectively read all features, and test them with the       // OGRFeature intersection methods should return FALSE.      // This can be used as a clue by the application whether it should build      // and maintain it's own spatial index for features in this layer.    {      // TODO: Perhaps use as a clue by QGIS whether it should build and maintain it's own spatial index for features in this layer.    }    if (OGR_L_TestCapability(ogrLayer,"FastFeatureCount"))      // TRUE if this layer can return a feature count      // (via OGRLayer::GetFeatureCount()) efficiently ... ie. without counting      // the features. In some cases this will return TRUE until a spatial      // filter is installed after which it will return FALSE.    {      // TODO: Perhaps use as a clue by QGIS whether it should spawn a thread to count features.    }    if (OGR_L_TestCapability(ogrLayer,"FastGetExtent"))      // TRUE if this layer can return its data extent       // (via OGRLayer::GetExtent()) efficiently ... ie. without scanning      // all the features. In some cases this will return TRUE until a      // spatial filter is installed after which it will return FALSE.    {      // TODO: Perhaps use as a clue by QGIS whether it should spawn a thread to calculate extent.    }    if (OGR_L_TestCapability(ogrLayer,"FastSetNextByIndex"))      // TRUE if this layer can perform the SetNextByIndex() call efficiently.    {      // No use required for this QGIS release.    }    if (1)    {      // Ideally this should test for Shapefile type and GDAL >= 1.2.6      // In reality, createSpatialIndex() looks after itself.      ability |= QgsVectorDataProvider::CreateSpatialIndex;    }    // OGR doesn't handle shapefiles without attributes, ie. missing DBFs well, fixes #803    if( ogrDriverName.startsWith("ESRI") && mAttributeFields.size()==0 )    {      QgsDebugMsg("OGR doesn't handle shapefile without attributes well, ie. missing DBFs");      ability &= ~(AddFeatures|DeleteFeatures|ChangeAttributeValues|AddAttributes|DeleteAttributes);    }  }  return ability;  /*  return (QgsVectorDataProvider::AddFeatures  | QgsVectorDataProvider::ChangeAttributeValues  | QgsVectorDataProvider::CreateSpatialIndex);  */}QString QgsOgrProvider::name() const{  return TEXT_PROVIDER_KEY;} // QgsOgrProvider::name()QString  QgsOgrProvider::description() const{  return TEXT_PROVIDER_DESCRIPTION;} //  QgsOgrProvider::description()/**  Convenience function for readily creating file filters.  Given a long name for a file filter and a regular expression, return  a file filter string suitable for use in a QFileDialog::OpenFiles()  call.  The regular express, glob, will have both all lower and upper  case versions added.  @note  Copied from qgisapp.cpp.    @todo XXX This should probably be generalized and moved to a standard            utility type thingy.*/static QString createFileFilter_(QString const &longName, QString const &glob)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -