File: qgsatlascomposition.cpp

package info (click to toggle)
qgis 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 374,696 kB
  • ctags: 66,263
  • sloc: cpp: 396,139; ansic: 241,070; python: 130,609; xml: 14,884; perl: 1,290; sh: 1,287; sql: 500; yacc: 268; lex: 242; makefile: 168
file content (805 lines) | stat: -rw-r--r-- 23,967 bytes parent folder | download
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
/***************************************************************************
                             qgsatlascomposition.cpp
                             -----------------------
    begin                : October 2012
    copyright            : (C) 2005 by Hugo Mercier
    email                : hugo dot mercier at oslandia dot 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.                                   *
 *                                                                         *
 ***************************************************************************/
#include <stdexcept>
#include <QtAlgorithms>

#include "qgsatlascomposition.h"
#include "qgsvectorlayer.h"
#include "qgscomposermap.h"
#include "qgscomposition.h"
#include "qgsvectordataprovider.h"
#include "qgsexpression.h"
#include "qgsgeometry.h"
#include "qgsmaplayerregistry.h"
#include "qgsproject.h"
#include "qgsmessagelog.h"

QgsAtlasComposition::QgsAtlasComposition( QgsComposition* composition ) :
    mComposition( composition ),
    mEnabled( false ),
    mHideCoverage( false ), mFilenamePattern( "'output_'||$feature" ),
    mCoverageLayer( 0 ), mSingleFile( false ),
    mSortFeatures( false ), mSortAscending( true ), mCurrentFeatureNo( 0 ),
    mFilterFeatures( false ), mFeatureFilter( "" ),
    mFilenameParserError( QString() ),
    mFilterParserError( QString() )
{

  // declare special columns with a default value
  QgsExpression::setSpecialColumn( "$page", QVariant(( int )1 ) );
  QgsExpression::setSpecialColumn( "$feature", QVariant(( int )0 ) );
  QgsExpression::setSpecialColumn( "$numpages", QVariant(( int )1 ) );
  QgsExpression::setSpecialColumn( "$numfeatures", QVariant(( int )0 ) );
  QgsExpression::setSpecialColumn( "$atlasfeatureid", QVariant(( int )0 ) );
  QgsExpression::setSpecialColumn( "$atlasgeometry", QVariant::fromValue( QgsGeometry() ) );
}

QgsAtlasComposition::~QgsAtlasComposition()
{
}

void QgsAtlasComposition::setEnabled( bool enabled )
{
  mEnabled = enabled;
  mComposition->setAtlasMode( QgsComposition::AtlasOff );
  emit toggled( enabled );
}

void QgsAtlasComposition::setCoverageLayer( QgsVectorLayer* layer )
{
  mCoverageLayer = layer;

  // update the number of features
  QgsExpression::setSpecialColumn( "$numfeatures", QVariant(( int )mFeatureIds.size() ) );

  // Grab the first feature so that user can use it to test the style in rules.
  if ( layer )
  {
    QgsFeature fet;
    layer->getFeatures().nextFeature( fet );
    QgsExpression::setSpecialColumn( "$atlasfeatureid", fet.id() );
    QgsExpression::setSpecialColumn( "$atlasgeometry", QVariant::fromValue( *fet.geometry() ) );
  }

  emit coverageLayerChanged( layer );
}

QgsComposerMap* QgsAtlasComposition::composerMap() const
{
  //deprecated method. Until removed just return the first atlas-enabled composer map

  //build a list of composer maps
  QList<QgsComposerMap*> maps;
  mComposition->composerItems( maps );
  for ( QList<QgsComposerMap*>::iterator mit = maps.begin(); mit != maps.end(); ++mit )
  {
    QgsComposerMap* currentMap = ( *mit );
    if ( currentMap->atlasDriven() )
    {
      return currentMap;
    }
  }

  return 0;
}

void QgsAtlasComposition::setComposerMap( QgsComposerMap* map )
{
  //deprecated

  if ( !map )
  {
    return;
  }

  map->setAtlasDriven( true );
}


int QgsAtlasComposition::sortKeyAttributeIndex() const
{
  if ( !mCoverageLayer )
  {
    return -1;
  }
  return mCoverageLayer->fieldNameIndex( mSortKeyAttributeName );
}

void QgsAtlasComposition::setSortKeyAttributeIndex( int idx )
{
  if ( mCoverageLayer )
  {
    const QgsFields fields = mCoverageLayer->pendingFields();
    if ( idx >= 0 && idx < fields.count() )
    {
      mSortKeyAttributeName = fields[idx].name();
      return;
    }
  }
  mSortKeyAttributeName = "";
}

//
// Private class only used for the sorting of features
class FieldSorter
{
  public:
    FieldSorter( QgsAtlasComposition::SorterKeys& keys, bool ascending = true ) : mKeys( keys ), mAscending( ascending ) {}

    bool operator()( const QgsFeatureId& id1, const QgsFeatureId& id2 )
    {
      bool result = true;

      if ( mKeys[ id1 ].type() == QVariant::Int )
      {
        result = mKeys[ id1 ].toInt() < mKeys[ id2 ].toInt();
      }
      else if ( mKeys[ id1 ].type() == QVariant::Double )
      {
        result = mKeys[ id1 ].toDouble() < mKeys[ id2 ].toDouble();
      }
      else if ( mKeys[ id1 ].type() == QVariant::String )
      {
        result = ( QString::localeAwareCompare( mKeys[ id1 ].toString(), mKeys[ id2 ].toString() ) < 0 );
      }

      return mAscending ? result : !result;
    }
  private:
    QgsAtlasComposition::SorterKeys& mKeys;
    bool mAscending;
};

int QgsAtlasComposition::updateFeatures()
{
  //needs to be called when layer, filter, sort changes

  if ( !mCoverageLayer )
  {
    return 0;
  }

  updateFilenameExpression();

  // select all features with all attributes
  QgsFeatureIterator fit = mCoverageLayer->getFeatures();

  std::auto_ptr<QgsExpression> filterExpression;
  if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
  {
    filterExpression = std::auto_ptr<QgsExpression>( new QgsExpression( mFeatureFilter ) );
    if ( filterExpression->hasParserError() )
    {
      mFilterParserError = filterExpression->parserErrorString();
      return 0;
    }
  }
  mFilterParserError = QString();

  // We cannot use nextFeature() directly since the feature pointer is rewinded by the rendering process
  // We thus store the feature ids for future extraction
  QgsFeature feat;
  mFeatureIds.clear();
  mFeatureKeys.clear();
  int sortIdx = mCoverageLayer->fieldNameIndex( mSortKeyAttributeName );
  while ( fit.nextFeature( feat ) )
  {
    if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
    {
      QVariant result = filterExpression->evaluate( &feat, mCoverageLayer->pendingFields() );
      if ( filterExpression->hasEvalError() )
      {
        QgsMessageLog::logMessage( tr( "Atlas filter eval error: %1" ).arg( filterExpression->evalErrorString() ), tr( "Composer" ) );
      }

      // skip this feature if the filter evaluation if false
      if ( !result.toBool() )
      {
        continue;
      }
    }
    mFeatureIds.push_back( feat.id() );

    if ( mSortFeatures && sortIdx != -1 )
    {
      mFeatureKeys.insert( feat.id(), feat.attributes()[ sortIdx ] );
    }
  }

  // sort features, if asked for
  if ( mFeatureKeys.count() )
  {
    FieldSorter sorter( mFeatureKeys, mSortAscending );
    qSort( mFeatureIds.begin(), mFeatureIds.end(), sorter );
  }

  QgsExpression::setSpecialColumn( "$numfeatures", QVariant(( int )mFeatureIds.size() ) );

  //jump to first feature if currently using an atlas preview
  //need to do this in case filtering/layer change has altered matching features
  if ( mComposition->atlasMode() == QgsComposition::PreviewAtlas )
  {
    firstFeature();
  }

  return mFeatureIds.size();
}


bool QgsAtlasComposition::beginRender()
{
  if ( !mCoverageLayer )
  {
    return false;
  }

  emit renderBegun();

  bool featuresUpdated = updateFeatures();
  if ( !featuresUpdated )
  {
    //no matching features found
    return false;
  }

  // special columns for expressions
  QgsExpression::setSpecialColumn( "$numpages", QVariant( mComposition->numPages() ) );
  QgsExpression::setSpecialColumn( "$numfeatures", QVariant(( int )mFeatureIds.size() ) );

  return true;
}

void QgsAtlasComposition::endRender()
{
  if ( !mCoverageLayer )
  {
    return;
  }

  emit featureChanged( 0 );

  updateAtlasMaps();

  emit renderEnded();
}

void QgsAtlasComposition::updateAtlasMaps()
{
  //update atlas-enabled composer maps
  QList<QgsComposerMap*> maps;
  mComposition->composerItems( maps );
  for ( QList<QgsComposerMap*>::iterator mit = maps.begin(); mit != maps.end(); ++mit )
  {
    QgsComposerMap* currentMap = ( *mit );
    if ( !currentMap->atlasDriven() )
    {
      continue;
    }

    currentMap->cache();
  }
}

int QgsAtlasComposition::numFeatures() const
{
  return mFeatureIds.size();
}

void QgsAtlasComposition::nextFeature()
{
  int newFeatureNo = mCurrentFeatureNo + 1;
  if ( newFeatureNo >= mFeatureIds.size() )
  {
    newFeatureNo = mFeatureIds.size() - 1;
  }

  prepareForFeature( newFeatureNo );
}

void QgsAtlasComposition::prevFeature()
{
  int newFeatureNo = mCurrentFeatureNo - 1;
  if ( newFeatureNo < 0 )
  {
    newFeatureNo = 0;
  }

  prepareForFeature( newFeatureNo );
}

void QgsAtlasComposition::firstFeature()
{
  prepareForFeature( 0 );
}

void QgsAtlasComposition::lastFeature()
{
  prepareForFeature( mFeatureIds.size() - 1 );
}

bool QgsAtlasComposition::prepareForFeature( QgsFeature * feat )
{
  int featureI = mFeatureIds.indexOf( feat->id() );
  return prepareForFeature( featureI );
}

bool QgsAtlasComposition::prepareForFeature( int featureI )
{
  if ( !mCoverageLayer )
  {
    return false;
  }

  if ( mFeatureIds.size() == 0 )
  {
    emit statusMsgChanged( tr( "No matching atlas features" ) );
    return false;
  }

  mCurrentFeatureNo = featureI;

  // retrieve the next feature, based on its id
  mCoverageLayer->getFeatures( QgsFeatureRequest().setFilterFid( mFeatureIds[ featureI ] ) ).nextFeature( mCurrentFeature );

  QgsExpression::setSpecialColumn( "$atlasfeatureid", mCurrentFeature.id() );
  QgsExpression::setSpecialColumn( "$atlasgeometry", QVariant::fromValue( *mCurrentFeature.geometry() ) );
  QgsExpression::setSpecialColumn( "$feature", QVariant(( int )featureI + 1 ) );

  // generate filename for current feature
  if ( !evalFeatureFilename() )
  {
    //error evaluating filename
    return false;
  }

  emit featureChanged( &mCurrentFeature );
  emit statusMsgChanged( QString( tr( "Atlas feature %1 of %2" ) ).arg( featureI + 1 ).arg( mFeatureIds.size() ) );

  //update composer maps

  //build a list of atlas-enabled composer maps
  QList<QgsComposerMap*> maps;
  QList<QgsComposerMap*> atlasMaps;
  mComposition->composerItems( maps );
  for ( QList<QgsComposerMap*>::iterator mit = maps.begin(); mit != maps.end(); ++mit )
  {
    QgsComposerMap* currentMap = ( *mit );
    if ( !currentMap->atlasDriven() )
    {
      continue;
    }
    atlasMaps << currentMap;
  }

  //clear the transformed bounds of the previous feature
  mTransformedFeatureBounds = QgsRectangle();

  if ( atlasMaps.isEmpty() )
  {
    //no atlas enabled maps
    return true;
  }

  // compute extent of current feature in the map CRS. This should be set on a per-atlas map basis,
  // but given that it's not currently possible to have maps with different CRSes we can just
  // calculate it once based on the first atlas maps' CRS.
  computeExtent( atlasMaps[0] );

  //update atlas bounds of every atlas enabled composer map
  for ( QList<QgsComposerMap*>::iterator mit = atlasMaps.begin(); mit != atlasMaps.end(); ++mit )
  {
    prepareMap( *mit );
  }

  return true;
}

void QgsAtlasComposition::computeExtent( QgsComposerMap* map )
{
  // compute the extent of the current feature, in the crs of the specified map

  const QgsCoordinateReferenceSystem& coverage_crs = mCoverageLayer->crs();
  // transformation needed for feature geometries
  const QgsCoordinateReferenceSystem& destination_crs = map->composition()->mapSettings().destinationCrs();
  mTransform.setSourceCrs( coverage_crs );
  mTransform.setDestCRS( destination_crs );

  // QgsGeometry::boundingBox is expressed in the geometry"s native CRS
  // We have to transform the grometry to the destination CRS and ask for the bounding box
  // Note: we cannot directly take the transformation of the bounding box, since transformations are not linear
  QgsGeometry tgeom( *mCurrentFeature.geometry() );
  tgeom.transform( mTransform );
  mTransformedFeatureBounds = tgeom.boundingBox();
}

void QgsAtlasComposition::prepareMap( QgsComposerMap* map )
{
  if ( !map->atlasDriven() )
  {
    return;
  }

  if ( mTransformedFeatureBounds.isEmpty() )
  {
    //transformed extent of current feature hasn't been calculated yet. This can happen if
    //a map has been set to be atlas controlled after prepare feature was called
    computeExtent( map );
  }

  double xa1 = mTransformedFeatureBounds.xMinimum();
  double xa2 = mTransformedFeatureBounds.xMaximum();
  double ya1 = mTransformedFeatureBounds.yMinimum();
  double ya2 = mTransformedFeatureBounds.yMaximum();
  QgsRectangle newExtent = mTransformedFeatureBounds;
  QgsRectangle mOrigExtent = map->extent();

  //sanity check - only allow fixed scale mode for point layers
  bool isPointLayer = false;
  switch ( mCoverageLayer->wkbType() )
  {
    case QGis::WKBPoint:
    case QGis::WKBPoint25D:
    case QGis::WKBMultiPoint:
    case QGis::WKBMultiPoint25D:
      isPointLayer = true;
      break;
    default:
      isPointLayer = false;
      break;
  }

  if ( map->atlasScalingMode() == QgsComposerMap::Fixed || map->atlasScalingMode() == QgsComposerMap::Predefined || isPointLayer )
  {
    QgsScaleCalculator calc;
    calc.setMapUnits( composition()->mapSettings().mapUnits() );
    calc.setDpi( 25.4 );
    double originalScale = calc.calculate( mOrigExtent, map->rect().width() );
    double geomCenterX = ( xa1 + xa2 ) / 2.0;
    double geomCenterY = ( ya1 + ya2 ) / 2.0;

    if ( map->atlasScalingMode() == QgsComposerMap::Fixed || isPointLayer )
    {
      // only translate, keep the original scale (i.e. width x height)
      double xMin = geomCenterX - mOrigExtent.width() / 2.0;
      double yMin = geomCenterY - mOrigExtent.height() / 2.0;
      newExtent = QgsRectangle( xMin,
                                yMin,
                                xMin + mOrigExtent.width(),
                                yMin + mOrigExtent.height() );

      //scale newExtent to match original scale of map
      //this is required for geographic coordinate systems, where the scale varies by extent
      double newScale = calc.calculate( newExtent, map->rect().width() );
      newExtent.scale( originalScale / newScale );
    }
    else if ( map->atlasScalingMode() == QgsComposerMap::Predefined )
    {
      // choose one of the predefined scales
      double newWidth = mOrigExtent.width();
      double newHeight = mOrigExtent.height();
      const QVector<qreal>& scales = mPredefinedScales;
      for ( int i = 0; i < scales.size(); i++ )
      {
        double ratio = scales[i] / originalScale;
        newWidth = mOrigExtent.width() * ratio;
        newHeight = mOrigExtent.height() * ratio;

        // compute new extent, centered on feature
        double xMin = geomCenterX - newWidth / 2.0;
        double yMin = geomCenterY - newHeight / 2.0;
        newExtent = QgsRectangle( xMin,
                                  yMin,
                                  xMin + newWidth,
                                  yMin + newHeight );

        //scale newExtent to match desired map scale
        //this is required for geographic coordinate systems, where the scale varies by extent
        double newScale = calc.calculate( newExtent, map->rect().width() );
        newExtent.scale( scales[i] / newScale );

        if (( newExtent.width() >= mTransformedFeatureBounds.width() ) && ( newExtent.height() >= mTransformedFeatureBounds.height() ) )
        {
          // this is the smallest extent that embeds the feature, stop here
          break;
        }
      }
    }
  }
  else if ( map->atlasScalingMode() == QgsComposerMap::Auto )
  {
    // auto scale

    double geomRatio = mTransformedFeatureBounds.width() / mTransformedFeatureBounds.height();
    double mapRatio = mOrigExtent.width() / mOrigExtent.height();

    // geometry height is too big
    if ( geomRatio < mapRatio )
    {
      // extent the bbox's width
      double adjWidth = ( mapRatio * mTransformedFeatureBounds.height() - mTransformedFeatureBounds.width() ) / 2.0;
      xa1 -= adjWidth;
      xa2 += adjWidth;
    }
    // geometry width is too big
    else if ( geomRatio > mapRatio )
    {
      // extent the bbox's height
      double adjHeight = ( mTransformedFeatureBounds.width() / mapRatio - mTransformedFeatureBounds.height() ) / 2.0;
      ya1 -= adjHeight;
      ya2 += adjHeight;
    }
    newExtent = QgsRectangle( xa1, ya1, xa2, ya2 );

    if ( map->atlasMargin() > 0.0 )
    {
      newExtent.scale( 1 + map->atlasMargin() );
    }
  }

  // set the new extent (and render)
  map->setNewAtlasFeatureExtent( newExtent );
}

const QString& QgsAtlasComposition::currentFilename() const
{
  return mCurrentFilename;
}

void QgsAtlasComposition::writeXML( QDomElement& elem, QDomDocument& doc ) const
{
  QDomElement atlasElem = doc.createElement( "Atlas" );
  atlasElem.setAttribute( "enabled", mEnabled ? "true" : "false" );
  if ( !mEnabled )
  {
    return;
  }

  if ( mCoverageLayer )
  {
    atlasElem.setAttribute( "coverageLayer", mCoverageLayer->id() );
  }
  else
  {
    atlasElem.setAttribute( "coverageLayer", "" );
  }

  atlasElem.setAttribute( "hideCoverage", mHideCoverage ? "true" : "false" );
  atlasElem.setAttribute( "singleFile", mSingleFile ? "true" : "false" );
  atlasElem.setAttribute( "filenamePattern", mFilenamePattern );

  atlasElem.setAttribute( "sortFeatures", mSortFeatures ? "true" : "false" );
  if ( mSortFeatures )
  {
    atlasElem.setAttribute( "sortKey", mSortKeyAttributeName );
    atlasElem.setAttribute( "sortAscending", mSortAscending ? "true" : "false" );
  }
  atlasElem.setAttribute( "filterFeatures", mFilterFeatures ? "true" : "false" );
  if ( mFilterFeatures )
  {
    atlasElem.setAttribute( "featureFilter", mFeatureFilter );
  }

  elem.appendChild( atlasElem );
}

void QgsAtlasComposition::readXML( const QDomElement& atlasElem, const QDomDocument& )
{
  mEnabled = atlasElem.attribute( "enabled", "false" ) == "true" ? true : false;
  emit toggled( mEnabled );
  if ( !mEnabled )
  {
    emit parameterChanged();
    return;
  }

  // look for stored layer name
  mCoverageLayer = 0;
  QMap<QString, QgsMapLayer*> layers = QgsMapLayerRegistry::instance()->mapLayers();
  for ( QMap<QString, QgsMapLayer*>::const_iterator it = layers.begin(); it != layers.end(); ++it )
  {
    if ( it.key() == atlasElem.attribute( "coverageLayer" ) )
    {
      mCoverageLayer = dynamic_cast<QgsVectorLayer*>( it.value() );
      break;
    }
  }
  //look for stored composer map, to upgrade pre 2.1 projects
  int composerMapNo = atlasElem.attribute( "composerMap", "-1" ).toInt();
  QgsComposerMap * composerMap = 0;
  if ( composerMapNo != -1 )
  {
    QList<QgsComposerMap*> maps;
    mComposition->composerItems( maps );
    for ( QList<QgsComposerMap*>::iterator it = maps.begin(); it != maps.end(); ++it )
    {
      if (( *it )->id() == composerMapNo )
      {
        composerMap = ( *it );
        composerMap->setAtlasDriven( true );
        break;
      }
    }
  }
  mHideCoverage = atlasElem.attribute( "hideCoverage", "false" ) == "true" ? true : false;

  //upgrade pre 2.1 projects
  double margin = atlasElem.attribute( "margin", "0.0" ).toDouble();
  if ( composerMap && margin != 0 )
  {
    composerMap->setAtlasMargin( margin );
  }
  bool fixedScale = atlasElem.attribute( "fixedScale", "false" ) == "true" ? true : false;
  if ( composerMap && fixedScale )
  {
    composerMap->setAtlasScalingMode( QgsComposerMap::Fixed );
  }

  mSingleFile = atlasElem.attribute( "singleFile", "false" ) == "true" ? true : false;
  mFilenamePattern = atlasElem.attribute( "filenamePattern", "" );

  mSortFeatures = atlasElem.attribute( "sortFeatures", "false" ) == "true" ? true : false;
  if ( mSortFeatures )
  {
    mSortKeyAttributeName = atlasElem.attribute( "sortKey", "" );
    // since 2.3, the field name is saved instead of the field index
    // following code keeps compatibility with version 2.2 projects
    // to be removed in QGIS 3.0
    bool isIndex;
    int idx = mSortKeyAttributeName.toInt( &isIndex );
    if ( isIndex && mCoverageLayer )
    {
      const QgsFields fields = mCoverageLayer->pendingFields();
      if ( idx >= 0 && idx < fields.count() )
      {
        mSortKeyAttributeName = fields[idx].name();
      }
    }
    mSortAscending = atlasElem.attribute( "sortAscending", "true" ) == "true" ? true : false;
  }
  mFilterFeatures = atlasElem.attribute( "filterFeatures", "false" ) == "true" ? true : false;
  if ( mFilterFeatures )
  {
    mFeatureFilter = atlasElem.attribute( "featureFilter", "" );
  }

  emit parameterChanged();
}

void QgsAtlasComposition::setHideCoverage( bool hide )
{
  mHideCoverage = hide;

  if ( mComposition->atlasMode() == QgsComposition::PreviewAtlas )
  {
    //an atlas preview is enabled, so reflect changes in coverage layer visibility immediately
    updateAtlasMaps();
    mComposition->update();
  }

}

bool QgsAtlasComposition::setFilenamePattern( const QString& pattern )
{
  mFilenamePattern = pattern;
  return updateFilenameExpression();
}

bool QgsAtlasComposition::updateFilenameExpression()
{
  if ( !mCoverageLayer )
  {
    return false;
  }

  const QgsFields& fields = mCoverageLayer->pendingFields();

  if ( mFilenamePattern.size() > 0 )
  {
    mFilenameExpr = std::auto_ptr<QgsExpression>( new QgsExpression( mFilenamePattern ) );
    // expression used to evaluate each filename
    // test for evaluation errors
    if ( mFilenameExpr->hasParserError() )
    {
      mFilenameParserError = mFilenameExpr->parserErrorString();
      return false;
    }

    // prepare the filename expression
    mFilenameExpr->prepare( fields );
  }

  //if atlas preview is currently enabled, regenerate filename for current feature
  if ( mComposition->atlasMode() == QgsComposition::PreviewAtlas )
  {
    evalFeatureFilename();
  }
  return true;
}

bool QgsAtlasComposition::evalFeatureFilename()
{
  //generate filename for current atlas feature
  if ( mFilenamePattern.size() > 0 )
  {
    QVariant filenameRes = mFilenameExpr->evaluate( &mCurrentFeature, mCoverageLayer->pendingFields() );
    if ( mFilenameExpr->hasEvalError() )
    {
      QgsMessageLog::logMessage( tr( "Atlas filename evaluation error: %1" ).arg( mFilenameExpr->evalErrorString() ), tr( "Composer" ) );
      return false;
    }

    mCurrentFilename = filenameRes.toString();
  }
  return true;
}

void QgsAtlasComposition::setPredefinedScales( const QVector<qreal>& scales )
{
  mPredefinedScales = scales;
  // make sure the list is sorted
  qSort( mPredefinedScales.begin(), mPredefinedScales.end() );
}

Q_NOWARN_DEPRECATED_PUSH
bool QgsAtlasComposition::fixedScale() const
{
  //deprecated method. Until removed just return the property for the first atlas-enabled composer map
  QgsComposerMap * map = composerMap();
  if ( !map )
  {
    return false;
  }

  return map->atlasFixedScale();
}

void QgsAtlasComposition::setFixedScale( bool fixed )
{
  //deprecated method. Until removed just set the property for the first atlas-enabled composer map
  QgsComposerMap * map = composerMap();
  if ( !map )
  {
    return;
  }

  map->setAtlasScalingMode( fixed ? QgsComposerMap::Fixed : QgsComposerMap::Auto );
}

float QgsAtlasComposition::margin() const
{
  //deprecated method. Until removed just return the property for the first atlas-enabled composer map
  QgsComposerMap * map = composerMap();
  if ( !map )
  {
    return 0;
  }

  return map->atlasMargin();
}

void QgsAtlasComposition::setMargin( float margin )
{
  //deprecated method. Until removed just set the property for the first atlas-enabled composer map
  QgsComposerMap * map = composerMap();
  if ( !map )
  {
    return;
  }

  map->setAtlasMargin(( double ) margin );
}
Q_NOWARN_DEPRECATED_POP