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
use std::ptr::null_mut;
use std::ffi::CString;
use libc::c_int;
use vector::{Feature, Geometry, FieldValue};
use vector::defn::Defn;
use gdal_major_object::MajorObject;
use metadata::Metadata;
use gdal_sys::{self, OGRErr, OGREnvelope, OGRFieldDefnH, OGRFieldType, OGRLayerH, GDALMajorObjectH};
use utils::{_last_null_pointer_err, _string};
use spatial_ref::SpatialRef;

use errors::*;

/// Layer in a vector dataset
///
/// ```
/// use std::path::Path;
/// use gdal::vector::Dataset;
///
/// let mut dataset = Dataset::open(Path::new("fixtures/roads.geojson")).unwrap();
/// let layer = dataset.layer(0).unwrap();
/// for feature in layer.features() {
///     // do something with each feature
/// }
/// ```
pub struct Layer {
    c_layer: OGRLayerH,
    defn: Defn,
}

impl MajorObject for Layer {
    unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH {
        self.c_layer
    }
}

impl Metadata for Layer {}


impl Layer {
    pub unsafe fn _with_c_layer(c_layer: OGRLayerH) -> Layer {
        let c_defn = gdal_sys::OGR_L_GetLayerDefn(c_layer);
        let defn = Defn::_with_c_defn(c_defn);
        Layer{c_layer, defn}
    }

    pub unsafe fn c_layer(&self) -> OGRLayerH {
        self.c_layer
    }

    /// Iterate over all features in this layer.
    pub fn features(&self) -> FeatureIterator {
        FeatureIterator::_with_layer(self)
    }

    pub fn set_spatial_filter(&self, geometry: &Geometry) {
        unsafe { gdal_sys::OGR_L_SetSpatialFilter(self.c_layer, geometry.c_geometry()) };
    }

    pub fn clear_spatial_filter(&self) {
        unsafe { gdal_sys::OGR_L_SetSpatialFilter(self.c_layer, null_mut()) };
    }

    /// Get the name of this layer.
    pub fn name(&self) -> String {
        let rv = unsafe { gdal_sys::OGR_L_GetName(self.c_layer) };
        _string(rv)
    }

    pub fn defn(&self) -> &Defn {
        &self.defn
    }

    pub fn create_defn_fields(&self, fields_def: &[(&str, OGRFieldType::Type)]) -> Result<()> {
        for fd in fields_def {
            let fdefn = FieldDefn::new(fd.0, fd.1)?;
            fdefn.add_to_layer(self)?;
        }
        Ok(())
    }
    pub fn create_feature(&mut self, geometry: Geometry) -> Result<()> {
        let c_feature = unsafe { gdal_sys::OGR_F_Create(self.defn.c_defn()) };
        let c_geometry = unsafe { geometry.into_c_geometry() };
        let rv = unsafe { gdal_sys::OGR_F_SetGeometryDirectly(c_feature, c_geometry) };
        if rv != OGRErr::OGRERR_NONE {
            Err(ErrorKind::OgrError{err: rv, method_name: "OGR_F_SetGeometryDirectly"})?;
        }
        let rv = unsafe { gdal_sys::OGR_L_CreateFeature(self.c_layer, c_feature) };
        if rv != OGRErr::OGRERR_NONE {
            Err(ErrorKind::OgrError{err: rv, method_name: "OGR_L_CreateFeature"})?;
        }
        Ok(())
    }

    pub fn create_feature_fields(&mut self, geometry: Geometry,
                                 field_names: &[&str], values: &[FieldValue]) -> Result<()> {
        let mut ft = Feature::new(&self.defn)?;
        ft.set_geometry(geometry)?;
        for (fd, val) in field_names.iter().zip(values.iter()) {
            ft.set_field(fd, val)?;
        }
        ft.create(self)?;
        Ok(())
    }

    pub fn get_extent(&self, force: bool) -> Result<gdal_sys::OGREnvelope> {
        let mut envelope = OGREnvelope { MinX: 0.0, MaxX: 0.0, MinY: 0.0, MaxY: 0.0 };
        let force = if force { 1 } else { 0 };
        let rv = unsafe { gdal_sys::OGR_L_GetExtent(self.c_layer, &mut envelope, force) };
        if rv != OGRErr::OGRERR_NONE {
            Err(ErrorKind::OgrError{err: rv, method_name: "OGR_L_GetExtent"})?;
        }
        Ok(envelope)
    }

    pub fn spatial_reference(&self) -> Result<SpatialRef> {
        let c_obj = unsafe { gdal_sys::OGR_L_GetSpatialRef(self.c_layer) };
        if c_obj.is_null() {
            Err(_last_null_pointer_err("OGR_L_GetSpatialRef"))?;
        }
        SpatialRef::from_c_obj(c_obj)
    }
}

pub struct FeatureIterator<'a> {
    layer: &'a Layer,
}

impl<'a> Iterator for FeatureIterator<'a> {
    type Item = Feature<'a>;

    #[inline]
    fn next(&mut self) -> Option<Feature<'a>> {
        let c_feature = unsafe { gdal_sys::OGR_L_GetNextFeature(self.layer.c_layer) };
        if c_feature.is_null() {
            None
        } else {
            Some(unsafe { Feature::_with_c_feature(self.layer.defn(), c_feature) })
        }
    }
}

impl<'a> FeatureIterator<'a> {
    pub fn _with_layer(layer: &'a Layer) -> FeatureIterator<'a> {
        FeatureIterator { layer }
    }
}

pub struct FieldDefn {
    c_obj: OGRFieldDefnH,
}

impl Drop for FieldDefn {
    fn drop(&mut self) {
        unsafe { gdal_sys::OGR_Fld_Destroy(self.c_obj) };
    }
}

impl MajorObject for FieldDefn {
    unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH {
        self.c_obj
    }
}

impl FieldDefn {
    pub fn new(name: &str, field_type: OGRFieldType::Type) -> Result<FieldDefn> {
        let c_str = CString::new(name)?;
        let c_obj = unsafe { gdal_sys::OGR_Fld_Create(c_str.as_ptr(), field_type) };
        if c_obj.is_null() {
            Err(_last_null_pointer_err("OGR_Fld_Create"))?;
        };
        Ok(FieldDefn { c_obj })
    }
    pub fn set_width(&self, width: i32) {
        unsafe {gdal_sys:: OGR_Fld_SetWidth(self.c_obj, width as c_int) };
    }
    pub fn set_precision(&self, precision: i32) {
        unsafe {gdal_sys:: OGR_Fld_SetPrecision(self.c_obj, precision as c_int) };
    }
    pub fn add_to_layer(&self, layer: &Layer) -> Result<()> {
        let rv = unsafe { gdal_sys::OGR_L_CreateField(layer.c_layer(), self.c_obj, 1) };
        if rv != OGRErr::OGRERR_NONE {
            Err(ErrorKind::OgrError{err: rv, method_name: "OGR_L_CreateFeature"})?;
        }
        Ok(())
    }
}