/
qgsogrprovider.cpp
1374 lines (1142 loc) · 37.4 KB
/
qgsogrprovider.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
qgsogrprovider.cpp Data provider for OGR supported formats
Formerly known as qgsshapefileprovider.cpp
begin : Oct 29, 2003
copyright : (C) 2003 by Gary E.Sherman
email : sherman at mrcc.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/* $Id$ */
#include "qgsogrprovider.h"
#include "qgslogger.h"
#include <iostream>
#include <cassert>
#define CPL_SUPRESS_CPLUSPLUS
#include <gdal.h> // to collect version information
#include <ogr_api.h>
#include <ogr_srs_api.h>
#include <cpl_error.h>
#include <QtDebug>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QMap>
#include <QString>
//TODO Following ifndef can be removed once WIN32 GEOS support
// is fixed
#ifndef NOWIN32GEOSXXX
//XXX GEOS support on windows is broken until we can get VC++ to
// tolerate geos.h without throwing a bunch of type errors. It
// appears that the windows version of GEOS may be compiled with
// MINGW rather than VC++.
#endif
#include "qgsapplication.h"
#include "qgsdataprovider.h"
#include "qgsfeature.h"
#include "qgsfield.h"
#include "qgsgeometry.h"
#include "qgslogger.h"
#include "qgsspatialrefsys.h"
static const QString TEXT_PROVIDER_KEY = "ogr";
static const QString TEXT_PROVIDER_DESCRIPTION =
QString("OGR data provider")
+ " (compiled against GDAL/OGR library version "
+ GDAL_RELEASE_NAME
+ ", running against GDAL/OGR library version "
+ GDALVersionInfo("RELEASE_NAME")
+ ")";
QgsOgrProvider::QgsOgrProvider(QString const & uri)
: QgsVectorDataProvider(uri),
ogrDataSource(0),
extent_(0),
ogrLayer(0),
ogrDriver(0)
{
OGRRegisterAll();
// set the selection rectangle pointer to 0
mSelectionRectangle = 0;
// make connection to the data source
QgsDebugMsg("Data source uri is " + uri);
// try to open for update, but disable error messages to avoid a
// message if the file is read only, because we cope with that
// ourselves.
CPLPushErrorHandler(CPLQuietErrorHandler);
ogrDataSource = OGROpen(QFile::encodeName(uri).constData(), TRUE, &ogrDriver);
CPLPopErrorHandler();
if(ogrDataSource == NULL)
{
// try to open read-only
ogrDataSource = OGROpen(QFile::encodeName(uri).constData(), FALSE, &ogrDriver);
//TODO Need to set a flag or something to indicate that the layer
//TODO is in read-only mode, otherwise edit ops will fail
//TODO: capabilities() should now reflect this; need to test.
}
if (ogrDataSource != NULL) {
QgsDebugMsg("Data source is valid");
QgsDebugMsg("OGR Driver was " + QString(OGR_Dr_GetName(ogrDriver)));
valid = true;
ogrDriverName = OGR_Dr_GetName(ogrDriver);
ogrLayer = OGR_DS_GetLayer(ogrDataSource,0);
// get the extent_ (envelope) of the layer
QgsDebugMsg("Starting get extent\n");
// TODO: This can be expensive, do we really need it!
extent_ = calloc(sizeof(OGREnvelope),1);
OGR_L_GetExtent(ogrLayer,(OGREnvelope *) extent_, TRUE );
QgsDebugMsg("Finished get extent\n");
// getting the total number of features in the layer
// TODO: This can be expensive, do we really need it!
numberFeatures = OGR_L_GetFeatureCount(ogrLayer, TRUE);
// check the validity of the layer
QgsDebugMsg("checking validity\n");
loadFields();
QgsDebugMsg("Done checking validity\n");
} else {
QgsLogger::critical("Data source is invalid");
const char *er = CPLGetLastErrorMsg();
QgsLogger::critical(er);
valid = false;
}
// create the geos objects
geometryFactory = new GEOS_GEOM::GeometryFactory();
assert(geometryFactory!=0);
mSupportedNativeTypes.insert("Integer");
mSupportedNativeTypes.insert("Real");
mSupportedNativeTypes.insert("String");
}
QgsOgrProvider::~QgsOgrProvider()
{
OGR_DS_Destroy(ogrDataSource);
ogrDataSource = 0;
free(extent_);
extent_ = 0;
delete geometryFactory;
if( mSelectionRectangle )
{
OGR_G_DestroyGeometry( mSelectionRectangle );
mSelectionRectangle = 0;
}
}
void QgsOgrProvider::setEncoding(const QString& e)
{
QgsVectorDataProvider::setEncoding(e);
loadFields();
}
void QgsOgrProvider::loadFields()
{
//the attribute fields need to be read again when the encoding changes
mAttributeFields.clear();
OGRFeatureDefnH fdef = OGR_L_GetLayerDefn(ogrLayer);
if(fdef)
{
geomType = OGR_FD_GetGeomType(fdef);
//Some ogr drivers (e.g. GML) are not able to determine the geometry type of a layer like this.
//In such cases, we examine the first feature
if(geomType == wkbUnknown)
{
OGR_L_ResetReading(ogrLayer);
OGRFeatureH firstFeature = OGR_L_GetNextFeature(ogrLayer);
if(firstFeature)
{
OGRGeometryH firstGeometry = OGR_F_GetGeometryRef(firstFeature);
if(firstGeometry)
{
geomType = OGR_G_GetGeometryType(firstGeometry);
}
OGR_F_Destroy( firstFeature );
}
OGR_L_ResetReading(ogrLayer);
}
for(int i=0;i<OGR_FD_GetFieldCount(fdef);++i)
{
OGRFieldDefnH fldDef = OGR_FD_GetFieldDefn(fdef,i);
OGRFieldType ogrType = OGR_Fld_GetType(fldDef);
QVariant::Type varType;
switch (ogrType)
{
case OFTInteger: varType = QVariant::Int; break;
case OFTReal: varType = QVariant::Double; break;
// unsupported in OGR 1.3
//case OFTDateTime: varType = QVariant::DateTime; break;
#if GDAL_VERSION_NUM >= 1400
case OFTString: varType = QVariant::String; break;
#endif
default: varType = QVariant::String; // other unsupported, leave it as a string
}
mAttributeFields.insert(
i, QgsField(
mEncoding->toUnicode(OGR_Fld_GetNameRef(fldDef)), varType,
mEncoding->toUnicode(OGR_GetFieldTypeName(ogrType)),
OGR_Fld_GetWidth(fldDef),
OGR_Fld_GetPrecision(fldDef) ));
}
}
}
QString QgsOgrProvider::storageType() const
{
// Delegate to the driver loaded in by OGR
return ogrDriverName;
}
bool QgsOgrProvider::getFeatureAtId(int featureId,
QgsFeature& feature,
bool fetchGeometry,
QgsAttributeList fetchAttributes)
{
OGRFeatureH fet = OGR_L_GetFeature(ogrLayer,featureId);
if (fet == NULL)
return false;
feature.setFeatureId(OGR_F_GetFID(fet));
/* fetch geometry */
if (fetchGeometry)
{
OGRGeometryH geom = OGR_F_GetGeometryRef(fet);
// get the wkb representation
unsigned char *wkb = new unsigned char[OGR_G_WkbSize(geom)];
OGR_G_ExportToWkb(geom,(OGRwkbByteOrder) QgsApplication::endian(), wkb);
feature.setGeometryAndOwnership(wkb, OGR_G_WkbSize(geom));
}
/* fetch attributes */
for(QgsAttributeList::iterator it = fetchAttributes.begin(); it != fetchAttributes.end(); ++it)
{
getFeatureAttribute(fet,feature,*it);
}
return true;
}
bool QgsOgrProvider::getNextFeature(QgsFeature& feature)
{
if (!valid)
{
QgsLogger::warning("Read attempt on an invalid shapefile data source");
return false;
}
OGRFeatureH fet;
QgsRect selectionRect;
while ((fet = OGR_L_GetNextFeature(ogrLayer)) != NULL)
{
// skip features without geometry
if (OGR_F_GetGeometryRef(fet) == NULL && !mFetchFeaturesWithoutGeom)
{
OGR_F_Destroy( fet );
continue;
}
OGRFeatureDefnH featureDefinition = OGR_F_GetDefnRef(fet);
QString featureTypeName = featureDefinition ? QString(OGR_FD_GetName(featureDefinition)) : QString("");
feature.setFeatureId(OGR_F_GetFID(fet));
feature.setTypeName(featureTypeName);
/* fetch geometry */
if (mFetchGeom)
{
OGRGeometryH geom = OGR_F_GetGeometryRef(fet);
// get the wkb representation
unsigned char *wkb = new unsigned char[OGR_G_WkbSize(geom)];
OGR_G_ExportToWkb(geom,(OGRwkbByteOrder) QgsApplication::endian(), wkb);
feature.setGeometryAndOwnership(wkb, OGR_G_WkbSize(geom));
if (mUseIntersect)
{
//precise test for intersection with search rectangle
//first make QgsRect from OGRPolygon
OGREnvelope env;
memset( &env, 0, sizeof(env) );
if(mSelectionRectangle)
OGR_G_GetEnvelope(mSelectionRectangle,&env);
if(env.MinX != 0 || env.MinY != 0 || env.MaxX != 0 || env.MaxY != 0 ) //if envelope is invalid, skip the precise intersection test
{
selectionRect.set(env.MinX, env.MinY, env.MaxX, env.MaxY);
if(!feature.geometry()->intersects(selectionRect))
{
OGR_F_Destroy( fet );
continue;
}
}
}
}
/* fetch attributes */
for(QgsAttributeList::iterator it = mAttributesToFetch.begin(); it != mAttributesToFetch.end(); ++it)
{
getFeatureAttribute(fet,feature,*it);
}
/* we have a feature, end this cycle */
break;
} /* while */
if (fet)
{
OGR_F_Destroy( fet );
return true;
}
else
{
QgsDebugMsg("Feature is null");
// probably should reset reading here
OGR_L_ResetReading(ogrLayer);
return false;
}
}
void QgsOgrProvider::select(QgsAttributeList fetchAttributes, QgsRect rect, bool fetchGeometry, \
bool useIntersect)
{
mUseIntersect = useIntersect;
mAttributesToFetch = fetchAttributes;
mFetchGeom = fetchGeometry;
// spatial query to select features
if(rect.isEmpty())
{
OGR_L_SetSpatialFilter(ogrLayer,0);
}
else
{
OGRGeometryH filter = 0;
QString wktExtent = QString("POLYGON ((%1))").arg(rect.asPolygon());
const char *wktText = wktExtent.toAscii();
if(useIntersect)
{
// store the selection rectangle for use in filtering features during
// an identify and display attributes
if( mSelectionRectangle )
OGR_G_DestroyGeometry( mSelectionRectangle );
OGR_G_CreateFromWkt( (char **)&wktText,
NULL, &mSelectionRectangle);
}
wktText = wktExtent.toAscii();
OGR_G_CreateFromWkt( (char **)&wktText, NULL, &filter );
QgsDebugMsg("Setting spatial filter using " + wktExtent);
OGR_L_SetSpatialFilter( ogrLayer, filter );
OGR_G_DestroyGeometry( filter );
}
}
unsigned char * QgsOgrProvider::getGeometryPointer(OGRFeatureH fet)
{
OGRGeometryH geom = OGR_F_GetGeometryRef(fet);
unsigned char *gPtr=0;
if( geom == NULL )
return NULL;
// get the wkb representation
gPtr = new unsigned char[OGR_G_WkbSize(geom)];
OGR_G_ExportToWkb(geom,(OGRwkbByteOrder) QgsApplication::endian(), gPtr);
return gPtr;
}
QgsRect QgsOgrProvider::extent()
{
OGREnvelope *ext = (OGREnvelope *) extent_;
mExtentRect.set(ext->MinX, ext->MinY, ext->MaxX, ext->MaxY);
return mExtentRect;
}
size_t QgsOgrProvider::layerCount() const
{
return OGR_DS_GetLayerCount(ogrDataSource);
} // QgsOgrProvider::layerCount()
/**
* Return the feature type
*/
QGis::WKBTYPE QgsOgrProvider::geometryType() const
{
return (QGis::WKBTYPE) geomType;
}
/**
* Return the feature type
*/
long QgsOgrProvider::featureCount() const
{
return numberFeatures;
}
/**
* Return the number of fields
*/
uint QgsOgrProvider::fieldCount() const
{
return mAttributeFields.size();
}
void QgsOgrProvider::getFeatureAttribute(OGRFeatureH ogrFet, QgsFeature & f, int attindex)
{
OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef(ogrFet, attindex);
if ( ! fldDef )
{
QgsDebugMsg("ogrFet->GetFieldDefnRef(attindex) returns NULL");
return;
}
QVariant value;
if( OGR_F_IsFieldSet(ogrFet, attindex) )
{
switch (mAttributeFields[attindex].type())
{
case QVariant::String: value = QVariant( mEncoding->toUnicode( OGR_F_GetFieldAsString(ogrFet,attindex) ) ); break;
case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attindex ) ); break;
case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attindex ) ); break;
//case QVariant::DateTime: value = QVariant(QDateTime::fromString(str)); break;
default: assert(NULL && "unsupported field type");
}
}
else
{
value = QVariant( QString::null );
}
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 features
bool 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;
} else {
f.setFeatureId( OGR_F_GetFID(feature) );
}
++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.toAscii(), 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)
{
return "[OGR] " +
longName + " (" + glob.lower() + " " + glob.upper() + ");;";
} // createFileFilter_
QGISEXTERN QString fileVectorFilters()
{
static QString myFileFilters;
// if we've already built the supported vector string, just return what
// we've already built
if ( ! ( myFileFilters.isEmpty() || myFileFilters.isNull() ) )
{
return myFileFilters;
}
// register ogr plugins
OGRRegisterAll();
// first get the GDAL driver manager
OGRSFDriverH driver; // current driver
QString driverName; // current driver name
// Grind through all the drivers and their respective metadata.
// We'll add a file filter for those drivers that have a file
// extension defined for them; the others, welll, even though
// theoreticaly we can open those files because there exists a
// driver for them, the user will have to use the "All Files" to
// open datasets with no explicitly defined file name extension.
QgsDebugMsg( QString("Driver count: %1").arg( OGRGetDriverCount() ) );
for (int i = 0; i < OGRGetDriverCount(); ++i)
{
driver = OGRGetDriver(i);
Q_CHECK_PTR(driver);
if (!driver)
{
QgsLogger::warning("unable to get driver " + QString::number(i));
continue;
}
driverName = OGR_Dr_GetName(driver);
if (driverName.startsWith("ESRI"))
{
myFileFilters += createFileFilter_("ESRI Shapefiles", "*.shp");
}
else if (driverName.startsWith("UK"))
{
// XXX needs file filter extension
}
else if (driverName.startsWith("SDTS"))
{
myFileFilters += createFileFilter_( "Spatial Data Transfer Standard",
"*catd.ddf" );
}
else if (driverName.startsWith("TIGER"))
{
// XXX needs file filter extension
}
else if (driverName.startsWith("S57"))
{
// XXX needs file filter extension
}
else if (driverName.startsWith("MapInfo"))
{
myFileFilters += createFileFilter_("MapInfo", "*.mif *.tab");
// XXX needs file filter extension
}
else if (driverName.startsWith("DGN"))
{
// XXX needs file filter extension
}
else if (driverName.startsWith("VRT"))
{