-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgslayoutitemlegend.cpp
1139 lines (948 loc) · 36.9 KB
/
qgslayoutitemlegend.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
/***************************************************************************
qgslayoutitemlegend.cpp
-----------------------
begin : October 2017
copyright : (C) 2017 by Nyall Dawson
email : nyall dot dawson at gmail 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 <limits>
#include "qgslayoutitemlegend.h"
#include "qgslayoutitemregistry.h"
#include "qgslayoutitemmap.h"
#include "qgslayout.h"
#include "qgslayoutmodel.h"
#include "qgslayertree.h"
#include "qgslayertreemodel.h"
#include "qgslegendrenderer.h"
#include "qgslegendstyle.h"
#include "qgslogger.h"
#include "qgsmapsettings.h"
#include "qgsproject.h"
#include "qgssymbollayerutils.h"
#include "qgslayertreeutils.h"
#include "qgslayoututils.h"
#include "qgsmapthemecollection.h"
#include "qgsstyleentityvisitor.h"
#include <QDomDocument>
#include <QDomElement>
#include <QPainter>
#include "qgsexpressioncontext.h"
QgsLayoutItemLegend::QgsLayoutItemLegend( QgsLayout *layout )
: QgsLayoutItem( layout )
, mLegendModel( new QgsLegendModel( layout->project()->layerTreeRoot(), this ) )
{
#if 0 //no longer required?
connect( &layout->atlasComposition(), &QgsAtlasComposition::renderEnded, this, &QgsLayoutItemLegend::onAtlasEnded );
#endif
mTitle = mSettings.title();
// Connect to the main layertreeroot.
// It serves in "auto update mode" as a medium between the main app legend and this one
connect( mLayout->project()->layerTreeRoot(), &QgsLayerTreeNode::customPropertyChanged, this, &QgsLayoutItemLegend::nodeCustomPropertyChanged );
// If project colors change, we need to redraw legend, as legend symbols may rely on project colors
connect( mLayout->project(), &QgsProject::projectColorsChanged, this, [ = ]
{
invalidateCache();
update();
} );
connect( mLegendModel.get(), &QgsLegendModel::refreshLegend, this, &QgsLayoutItemLegend::refresh );
}
QgsLayoutItemLegend *QgsLayoutItemLegend::create( QgsLayout *layout )
{
return new QgsLayoutItemLegend( layout );
}
int QgsLayoutItemLegend::type() const
{
return QgsLayoutItemRegistry::LayoutLegend;
}
QIcon QgsLayoutItemLegend::icon() const
{
return QgsApplication::getThemeIcon( QStringLiteral( "/mLayoutItemLegend.svg" ) );
}
QgsLayoutItem::Flags QgsLayoutItemLegend::itemFlags() const
{
return QgsLayoutItem::FlagOverridesPaint;
}
void QgsLayoutItemLegend::paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget )
{
if ( !painter )
return;
if ( mFilterAskedForUpdate )
{
mFilterAskedForUpdate = false;
doUpdateFilterByMap();
}
int dpi = painter->device()->logicalDpiX();
double dotsPerMM = dpi / 25.4;
if ( mLayout )
{
Q_NOWARN_DEPRECATED_PUSH
// no longer required, but left set for api stability
mSettings.setUseAdvancedEffects( mLayout->renderContext().flags() & QgsLayoutRenderContext::FlagUseAdvancedEffects );
mSettings.setDpi( dpi );
Q_NOWARN_DEPRECATED_POP
}
if ( mMap && mLayout )
{
Q_NOWARN_DEPRECATED_PUSH
// no longer required, but left set for api stability
mSettings.setMmPerMapUnit( mLayout->convertFromLayoutUnits( mMap->mapUnitsToLayoutUnits(), QgsUnitTypes::LayoutMillimeters ).length() );
Q_NOWARN_DEPRECATED_POP
// use a temporary QgsMapSettings to find out real map scale
QSizeF mapSizePixels = QSizeF( mMap->rect().width() * dotsPerMM, mMap->rect().height() * dotsPerMM );
QgsRectangle mapExtent = mMap->extent();
QgsMapSettings ms = mMap->mapSettings( mapExtent, mapSizePixels, dpi, false );
// no longer required, but left set for api stability
Q_NOWARN_DEPRECATED_PUSH
mSettings.setMapScale( ms.scale() );
Q_NOWARN_DEPRECATED_POP
}
mInitialMapScaleCalculated = true;
QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
legendRenderer.setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() );
//adjust box if width or height is too small
if ( mSizeToContents )
{
QgsRenderContext context = QgsLayoutUtils::createRenderContextForLayout( mLayout, painter );
QSizeF size = legendRenderer.minimumSize( &context );
if ( mForceResize )
{
mForceResize = false;
//set new rect, respecting position mode and data defined size/position
QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
attemptResize( newSize );
}
else if ( size.height() > rect().height() || size.width() > rect().width() )
{
//need to resize box
QSizeF targetSize = rect().size();
if ( size.height() > targetSize.height() )
targetSize.setHeight( size.height() );
if ( size.width() > targetSize.width() )
targetSize.setWidth( size.width() );
QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( targetSize, sizeWithUnits().units() );
//set new rect, respecting position mode and data defined size/position
attemptResize( newSize );
}
}
QgsLayoutItem::paint( painter, itemStyle, pWidget );
}
void QgsLayoutItemLegend::finalizeRestoreFromXml()
{
if ( !mMapUuid.isEmpty() )
{
setLinkedMap( qobject_cast< QgsLayoutItemMap * >( mLayout->itemByUuid( mMapUuid, true ) ) );
}
}
void QgsLayoutItemLegend::refresh()
{
QgsLayoutItem::refresh();
clearLegendCachedData();
onAtlasFeature();
}
void QgsLayoutItemLegend::draw( QgsLayoutItemRenderContext &context )
{
QPainter *painter = context.renderContext().painter();
painter->save();
// painter is scaled to dots, so scale back to layout units
painter->scale( context.renderContext().scaleFactor(), context.renderContext().scaleFactor() );
painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
if ( !mSizeToContents )
{
// set a clip region to crop out parts of legend which don't fit
QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() );
painter->setClipRect( thisPaintRect );
}
if ( mLayout )
{
// no longer required, but left for API compatibility
Q_NOWARN_DEPRECATED_PUSH
mSettings.setDpi( mLayout->renderContext().dpi() );
Q_NOWARN_DEPRECATED_POP
}
QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
legendRenderer.setLegendSize( rect().size() );
legendRenderer.drawLegend( context.renderContext() );
painter->restore();
}
void QgsLayoutItemLegend::adjustBoxSize()
{
if ( !mSizeToContents )
return;
if ( !mInitialMapScaleCalculated )
{
// this is messy - but until we have painted the item we have no knowledge of the current DPI
// and so cannot correctly calculate the map scale. This results in incorrect size calculations
// for marker symbols with size in map units, causing the legends to initially expand to huge
// sizes if we attempt to calculate the box size first.
return;
}
QgsRenderContext context = QgsLayoutUtils::createRenderContextForLayout( mLayout, nullptr );
QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
QSizeF size = legendRenderer.minimumSize( &context );
QgsDebugMsg( QStringLiteral( "width = %1 height = %2" ).arg( size.width() ).arg( size.height() ) );
if ( size.isValid() )
{
QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
//set new rect, respecting position mode and data defined size/position
attemptResize( newSize );
}
}
void QgsLayoutItemLegend::setResizeToContents( bool enabled )
{
mSizeToContents = enabled;
}
bool QgsLayoutItemLegend::resizeToContents() const
{
return mSizeToContents;
}
void QgsLayoutItemLegend::setCustomLayerTree( QgsLayerTree *rootGroup )
{
mLegendModel->setRootGroup( rootGroup ? rootGroup : ( mLayout ? mLayout->project()->layerTreeRoot() : nullptr ) );
mCustomLayerTree.reset( rootGroup );
}
void QgsLayoutItemLegend::setAutoUpdateModel( bool autoUpdate )
{
if ( autoUpdate == autoUpdateModel() )
return;
setCustomLayerTree( autoUpdate ? nullptr : mLayout->project()->layerTreeRoot()->clone() );
adjustBoxSize();
updateFilterByMap( false );
}
void QgsLayoutItemLegend::nodeCustomPropertyChanged( QgsLayerTreeNode *, const QString &key )
{
if ( key == QLatin1String( "cached_name" ) )
return;
if ( autoUpdateModel() )
{
// in "auto update" mode, some parameters on the main app legend may have been changed (expression filtering)
// we must then call updateItem to reflect the changes
updateFilterByMap( false );
}
}
bool QgsLayoutItemLegend::autoUpdateModel() const
{
return !mCustomLayerTree;
}
void QgsLayoutItemLegend::setLegendFilterByMapEnabled( bool enabled )
{
mLegendFilterByMap = enabled;
updateFilterByMap( false );
}
void QgsLayoutItemLegend::setTitle( const QString &t )
{
mTitle = t;
mSettings.setTitle( t );
if ( mLayout && id().isEmpty() )
{
//notify the model that the display name has changed
mLayout->itemsModel()->updateItemDisplayName( this );
}
}
QString QgsLayoutItemLegend::title() const
{
return mTitle;
}
Qt::AlignmentFlag QgsLayoutItemLegend::titleAlignment() const
{
return mSettings.titleAlignment();
}
void QgsLayoutItemLegend::setTitleAlignment( Qt::AlignmentFlag alignment )
{
mSettings.setTitleAlignment( alignment );
}
QgsLegendStyle &QgsLayoutItemLegend::rstyle( QgsLegendStyle::Style s )
{
return mSettings.rstyle( s );
}
QgsLegendStyle QgsLayoutItemLegend::style( QgsLegendStyle::Style s ) const
{
return mSettings.style( s );
}
void QgsLayoutItemLegend::setStyle( QgsLegendStyle::Style s, const QgsLegendStyle &style )
{
mSettings.setStyle( s, style );
}
QFont QgsLayoutItemLegend::styleFont( QgsLegendStyle::Style s ) const
{
return mSettings.style( s ).font();
}
void QgsLayoutItemLegend::setStyleFont( QgsLegendStyle::Style s, const QFont &f )
{
rstyle( s ).setFont( f );
}
void QgsLayoutItemLegend::setStyleMargin( QgsLegendStyle::Style s, double margin )
{
rstyle( s ).setMargin( margin );
}
void QgsLayoutItemLegend::setStyleMargin( QgsLegendStyle::Style s, QgsLegendStyle::Side side, double margin )
{
rstyle( s ).setMargin( side, margin );
}
double QgsLayoutItemLegend::lineSpacing() const
{
return mSettings.lineSpacing();
}
void QgsLayoutItemLegend::setLineSpacing( double spacing )
{
mSettings.setLineSpacing( spacing );
}
double QgsLayoutItemLegend::boxSpace() const
{
return mSettings.boxSpace();
}
void QgsLayoutItemLegend::setBoxSpace( double s )
{
mSettings.setBoxSpace( s );
}
double QgsLayoutItemLegend::columnSpace() const
{
return mSettings.columnSpace();
}
void QgsLayoutItemLegend::setColumnSpace( double s )
{
mSettings.setColumnSpace( s );
}
QColor QgsLayoutItemLegend::fontColor() const
{
return mSettings.fontColor();
}
void QgsLayoutItemLegend::setFontColor( const QColor &c )
{
mSettings.setFontColor( c );
}
double QgsLayoutItemLegend::symbolWidth() const
{
return mSettings.symbolSize().width();
}
void QgsLayoutItemLegend::setSymbolWidth( double w )
{
mSettings.setSymbolSize( QSizeF( w, mSettings.symbolSize().height() ) );
}
void QgsLayoutItemLegend::setSymbolAlignment( Qt::AlignmentFlag alignment )
{
mSettings.setSymbolAlignment( alignment );
}
Qt::AlignmentFlag QgsLayoutItemLegend::symbolAlignment() const
{
return mSettings.symbolAlignment();
}
double QgsLayoutItemLegend::symbolHeight() const
{
return mSettings.symbolSize().height();
}
void QgsLayoutItemLegend::setSymbolHeight( double h )
{
mSettings.setSymbolSize( QSizeF( mSettings.symbolSize().width(), h ) );
}
double QgsLayoutItemLegend::wmsLegendWidth() const
{
return mSettings.wmsLegendSize().width();
}
void QgsLayoutItemLegend::setWmsLegendWidth( double w )
{
mSettings.setWmsLegendSize( QSizeF( w, mSettings.wmsLegendSize().height() ) );
}
double QgsLayoutItemLegend::wmsLegendHeight() const
{
return mSettings.wmsLegendSize().height();
}
void QgsLayoutItemLegend::setWmsLegendHeight( double h )
{
mSettings.setWmsLegendSize( QSizeF( mSettings.wmsLegendSize().width(), h ) );
}
void QgsLayoutItemLegend::setWrapString( const QString &t )
{
mSettings.setWrapChar( t );
}
QString QgsLayoutItemLegend::wrapString() const
{
return mSettings.wrapChar();
}
int QgsLayoutItemLegend::columnCount() const
{
return mColumnCount;
}
void QgsLayoutItemLegend::setColumnCount( int c )
{
mColumnCount = c;
mSettings.setColumnCount( c );
}
bool QgsLayoutItemLegend::splitLayer() const
{
return mSettings.splitLayer();
}
void QgsLayoutItemLegend::setSplitLayer( bool s )
{
mSettings.setSplitLayer( s );
}
bool QgsLayoutItemLegend::equalColumnWidth() const
{
return mSettings.equalColumnWidth();
}
void QgsLayoutItemLegend::setEqualColumnWidth( bool s )
{
mSettings.setEqualColumnWidth( s );
}
bool QgsLayoutItemLegend::drawRasterStroke() const
{
return mSettings.drawRasterStroke();
}
void QgsLayoutItemLegend::setDrawRasterStroke( bool enabled )
{
mSettings.setDrawRasterStroke( enabled );
}
QColor QgsLayoutItemLegend::rasterStrokeColor() const
{
return mSettings.rasterStrokeColor();
}
void QgsLayoutItemLegend::setRasterStrokeColor( const QColor &color )
{
mSettings.setRasterStrokeColor( color );
}
double QgsLayoutItemLegend::rasterStrokeWidth() const
{
return mSettings.rasterStrokeWidth();
}
void QgsLayoutItemLegend::setRasterStrokeWidth( double width )
{
mSettings.setRasterStrokeWidth( width );
}
void QgsLayoutItemLegend::updateLegend()
{
adjustBoxSize();
updateFilterByMap( false );
}
bool QgsLayoutItemLegend::writePropertiesToElement( QDomElement &legendElem, QDomDocument &doc, const QgsReadWriteContext &context ) const
{
//write general properties
legendElem.setAttribute( QStringLiteral( "title" ), mTitle );
legendElem.setAttribute( QStringLiteral( "titleAlignment" ), QString::number( static_cast< int >( mSettings.titleAlignment() ) ) );
legendElem.setAttribute( QStringLiteral( "columnCount" ), QString::number( mColumnCount ) );
legendElem.setAttribute( QStringLiteral( "splitLayer" ), QString::number( mSettings.splitLayer() ) );
legendElem.setAttribute( QStringLiteral( "equalColumnWidth" ), QString::number( mSettings.equalColumnWidth() ) );
legendElem.setAttribute( QStringLiteral( "boxSpace" ), QString::number( mSettings.boxSpace() ) );
legendElem.setAttribute( QStringLiteral( "columnSpace" ), QString::number( mSettings.columnSpace() ) );
legendElem.setAttribute( QStringLiteral( "symbolWidth" ), QString::number( mSettings.symbolSize().width() ) );
legendElem.setAttribute( QStringLiteral( "symbolHeight" ), QString::number( mSettings.symbolSize().height() ) );
legendElem.setAttribute( QStringLiteral( "symbolAlignment" ), mSettings.symbolAlignment() );
legendElem.setAttribute( QStringLiteral( "symbolAlignment" ), mSettings.symbolAlignment() );
legendElem.setAttribute( QStringLiteral( "lineSpacing" ), QString::number( mSettings.lineSpacing() ) );
legendElem.setAttribute( QStringLiteral( "rasterBorder" ), mSettings.drawRasterStroke() );
legendElem.setAttribute( QStringLiteral( "rasterBorderColor" ), QgsSymbolLayerUtils::encodeColor( mSettings.rasterStrokeColor() ) );
legendElem.setAttribute( QStringLiteral( "rasterBorderWidth" ), QString::number( mSettings.rasterStrokeWidth() ) );
legendElem.setAttribute( QStringLiteral( "wmsLegendWidth" ), QString::number( mSettings.wmsLegendSize().width() ) );
legendElem.setAttribute( QStringLiteral( "wmsLegendHeight" ), QString::number( mSettings.wmsLegendSize().height() ) );
legendElem.setAttribute( QStringLiteral( "wrapChar" ), mSettings.wrapChar() );
legendElem.setAttribute( QStringLiteral( "fontColor" ), mSettings.fontColor().name() );
legendElem.setAttribute( QStringLiteral( "resizeToContents" ), mSizeToContents );
if ( mMap )
{
legendElem.setAttribute( QStringLiteral( "map_uuid" ), mMap->uuid() );
}
QDomElement legendStyles = doc.createElement( QStringLiteral( "styles" ) );
legendElem.appendChild( legendStyles );
style( QgsLegendStyle::Title ).writeXml( QStringLiteral( "title" ), legendStyles, doc );
style( QgsLegendStyle::Group ).writeXml( QStringLiteral( "group" ), legendStyles, doc );
style( QgsLegendStyle::Subgroup ).writeXml( QStringLiteral( "subgroup" ), legendStyles, doc );
style( QgsLegendStyle::Symbol ).writeXml( QStringLiteral( "symbol" ), legendStyles, doc );
style( QgsLegendStyle::SymbolLabel ).writeXml( QStringLiteral( "symbolLabel" ), legendStyles, doc );
if ( mCustomLayerTree )
{
// if not using auto-update - store the custom layer tree
mCustomLayerTree->writeXml( legendElem, context );
}
if ( mLegendFilterByMap )
{
legendElem.setAttribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "1" ) );
}
legendElem.setAttribute( QStringLiteral( "legendFilterByAtlas" ), mFilterOutAtlas ? QStringLiteral( "1" ) : QStringLiteral( "0" ) );
return true;
}
bool QgsLayoutItemLegend::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &doc, const QgsReadWriteContext &context )
{
//read general properties
mTitle = itemElem.attribute( QStringLiteral( "title" ) );
mSettings.setTitle( mTitle );
if ( !itemElem.attribute( QStringLiteral( "titleAlignment" ) ).isEmpty() )
{
mSettings.setTitleAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "titleAlignment" ) ).toInt() ) );
}
int colCount = itemElem.attribute( QStringLiteral( "columnCount" ), QStringLiteral( "1" ) ).toInt();
if ( colCount < 1 ) colCount = 1;
mColumnCount = colCount;
mSettings.setColumnCount( mColumnCount );
mSettings.setSplitLayer( itemElem.attribute( QStringLiteral( "splitLayer" ), QStringLiteral( "0" ) ).toInt() == 1 );
mSettings.setEqualColumnWidth( itemElem.attribute( QStringLiteral( "equalColumnWidth" ), QStringLiteral( "0" ) ).toInt() == 1 );
QDomNodeList stylesNodeList = itemElem.elementsByTagName( QStringLiteral( "styles" ) );
if ( !stylesNodeList.isEmpty() )
{
QDomNode stylesNode = stylesNodeList.at( 0 );
for ( int i = 0; i < stylesNode.childNodes().size(); i++ )
{
QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
QgsLegendStyle style;
style.readXml( styleElem, doc, context );
QString name = styleElem.attribute( QStringLiteral( "name" ) );
QgsLegendStyle::Style s;
if ( name == QLatin1String( "title" ) ) s = QgsLegendStyle::Title;
else if ( name == QLatin1String( "group" ) ) s = QgsLegendStyle::Group;
else if ( name == QLatin1String( "subgroup" ) ) s = QgsLegendStyle::Subgroup;
else if ( name == QLatin1String( "symbol" ) ) s = QgsLegendStyle::Symbol;
else if ( name == QLatin1String( "symbolLabel" ) ) s = QgsLegendStyle::SymbolLabel;
else continue;
setStyle( s, style );
}
}
//font color
QColor fontClr;
fontClr.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) );
mSettings.setFontColor( fontClr );
//spaces
mSettings.setBoxSpace( itemElem.attribute( QStringLiteral( "boxSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
mSettings.setColumnSpace( itemElem.attribute( QStringLiteral( "columnSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
mSettings.setSymbolSize( QSizeF( itemElem.attribute( QStringLiteral( "symbolWidth" ), QStringLiteral( "7.0" ) ).toDouble(), itemElem.attribute( QStringLiteral( "symbolHeight" ), QStringLiteral( "14.0" ) ).toDouble() ) );
mSettings.setSymbolAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "symbolAlignment" ), QString::number( Qt::AlignLeft ) ).toInt() ) );
mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( QStringLiteral( "wmsLegendWidth" ), QStringLiteral( "50" ) ).toDouble(), itemElem.attribute( QStringLiteral( "wmsLegendHeight" ), QStringLiteral( "25" ) ).toDouble() ) );
mSettings.setLineSpacing( itemElem.attribute( QStringLiteral( "lineSpacing" ), QStringLiteral( "1.0" ) ).toDouble() );
mSettings.setDrawRasterStroke( itemElem.attribute( QStringLiteral( "rasterBorder" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) );
mSettings.setRasterStrokeColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "rasterBorderColor" ), QStringLiteral( "0,0,0" ) ) ) );
mSettings.setRasterStrokeWidth( itemElem.attribute( QStringLiteral( "rasterBorderWidth" ), QStringLiteral( "0" ) ).toDouble() );
mSettings.setWrapChar( itemElem.attribute( QStringLiteral( "wrapChar" ) ) );
mSizeToContents = itemElem.attribute( QStringLiteral( "resizeToContents" ), QStringLiteral( "1" ) ) != QLatin1String( "0" );
// map
mLegendFilterByMap = itemElem.attribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "0" ) ).toInt();
mMapUuid.clear();
if ( !itemElem.attribute( QStringLiteral( "map_uuid" ) ).isEmpty() )
{
mMapUuid = itemElem.attribute( QStringLiteral( "map_uuid" ) );
}
// disconnect current map
setupMapConnections( mMap, false );
mMap = nullptr;
mFilterOutAtlas = itemElem.attribute( QStringLiteral( "legendFilterByAtlas" ), QStringLiteral( "0" ) ).toInt();
// QGIS >= 2.6
QDomElement layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree" ) );
if ( layerTreeElem.isNull() )
layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree-group" ) );
if ( !layerTreeElem.isNull() )
{
std::unique_ptr< QgsLayerTree > tree( QgsLayerTree::readXml( layerTreeElem, context ) );
if ( mLayout )
tree->resolveReferences( mLayout->project(), true );
setCustomLayerTree( tree.release() );
}
else
setCustomLayerTree( nullptr );
return true;
}
QString QgsLayoutItemLegend::displayName() const
{
if ( !id().isEmpty() )
{
return id();
}
//if no id, default to portion of title text
QString text = mSettings.title();
if ( text.isEmpty() )
{
return tr( "<Legend>" );
}
if ( text.length() > 25 )
{
return tr( "%1…" ).arg( text.left( 25 ) );
}
else
{
return text;
}
}
void QgsLayoutItemLegend::setupMapConnections( QgsLayoutItemMap *map, bool connectSlots )
{
if ( !map )
return;
if ( !connectSlots )
{
disconnect( map, &QObject::destroyed, this, &QgsLayoutItemLegend::invalidateCurrentMap );
disconnect( map, &QgsLayoutObject::changed, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
disconnect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
disconnect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
disconnect( map, &QgsLayoutItemMap::layerStyleOverridesChanged, this, &QgsLayoutItemLegend::mapLayerStyleOverridesChanged );
disconnect( map, &QgsLayoutItemMap::themeChanged, this, &QgsLayoutItemLegend::mapThemeChanged );
}
else
{
connect( map, &QObject::destroyed, this, &QgsLayoutItemLegend::invalidateCurrentMap );
connect( map, &QgsLayoutObject::changed, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
connect( map, &QgsLayoutItemMap::extentChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
connect( map, &QgsLayoutItemMap::mapRotationChanged, this, &QgsLayoutItemLegend::updateFilterByMapAndRedraw );
connect( map, &QgsLayoutItemMap::layerStyleOverridesChanged, this, &QgsLayoutItemLegend::mapLayerStyleOverridesChanged );
connect( map, &QgsLayoutItemMap::themeChanged, this, &QgsLayoutItemLegend::mapThemeChanged );
}
}
void QgsLayoutItemLegend::setLinkedMap( QgsLayoutItemMap *map )
{
if ( mMap )
{
setupMapConnections( mMap, false );
}
mMap = map;
if ( mMap )
{
setupMapConnections( mMap, true );
mapThemeChanged( mMap->themeToRender( mMap->createExpressionContext() ) );
}
updateFilterByMap();
}
void QgsLayoutItemLegend::invalidateCurrentMap()
{
setLinkedMap( nullptr );
}
void QgsLayoutItemLegend::refreshDataDefinedProperty( const QgsLayoutObject::DataDefinedProperty property )
{
QgsExpressionContext context = createExpressionContext();
bool forceUpdate = false;
//updates data defined properties and redraws item to match
if ( property == QgsLayoutObject::LegendTitle || property == QgsLayoutObject::AllProperties )
{
bool ok = false;
QString t = mDataDefinedProperties.valueAsString( QgsLayoutObject::LegendTitle, context, mTitle, &ok );
if ( ok )
{
mSettings.setTitle( t );
forceUpdate = true;
}
}
if ( property == QgsLayoutObject::LegendColumnCount || property == QgsLayoutObject::AllProperties )
{
bool ok = false;
int cols = mDataDefinedProperties.valueAsInt( QgsLayoutObject::LegendColumnCount, context, mColumnCount, &ok );
if ( ok && cols >= 0 )
{
mSettings.setColumnCount( cols );
forceUpdate = true;
}
}
if ( forceUpdate )
{
adjustBoxSize();
update();
}
QgsLayoutItem::refreshDataDefinedProperty( property );
}
void QgsLayoutItemLegend::updateFilterByMapAndRedraw()
{
updateFilterByMap( true );
}
void QgsLayoutItemLegend::setModelStyleOverrides( const QMap<QString, QString> &overrides )
{
mLegendModel->setLayerStyleOverrides( overrides );
const QList< QgsLayerTreeLayer * > layers = mLegendModel->rootGroup()->findLayers();
for ( QgsLayerTreeLayer *nodeLayer : layers )
mLegendModel->refreshLayerLegend( nodeLayer );
}
void QgsLayoutItemLegend::clearLegendCachedData()
{
std::function< void( QgsLayerTreeNode * ) > clearNodeCache;
clearNodeCache = [&]( QgsLayerTreeNode * node )
{
mLegendModel->clearCachedData( node );
if ( QgsLayerTree::isGroup( node ) )
{
QgsLayerTreeGroup *group = QgsLayerTree::toGroup( node );
const QList< QgsLayerTreeNode * > children = group->children();
for ( QgsLayerTreeNode *child : children )
{
clearNodeCache( child );
}
}
};
clearNodeCache( mLegendModel->rootGroup() );
}
void QgsLayoutItemLegend::mapLayerStyleOverridesChanged()
{
if ( !mMap )
return;
// map's style has been changed, so make sure to update the legend here
if ( mLegendFilterByMap )
{
// legend is being filtered by map, so we need to re run the hit test too
// as the style overrides may also have affected the visible symbols
updateFilterByMap( false );
}
else
{
setModelStyleOverrides( mMap->layerStyleOverrides() );
}
adjustBoxSize();
updateFilterByMap( false );
}
void QgsLayoutItemLegend::mapThemeChanged( const QString &theme )
{
if ( mThemeName == theme )
return;
mThemeName = theme;
// map's theme has been changed, so make sure to update the legend here
if ( mLegendFilterByMap )
{
// legend is being filtered by map, so we need to re run the hit test too
// as the style overrides may also have affected the visible symbols
updateFilterByMap( false );
}
else
{
if ( mThemeName.isEmpty() )
{
setModelStyleOverrides( QMap<QString, QString>() );
}
else
{
// get style overrides for theme
const QMap<QString, QString> overrides = mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
setModelStyleOverrides( overrides );
}
}
adjustBoxSize();
updateFilterByMap();
}
void QgsLayoutItemLegend::updateFilterByMap( bool redraw )
{
// ask for update
// the actual update will take place before the redraw.
// This is to avoid multiple calls to the filter
mFilterAskedForUpdate = true;
clearLegendCachedData();
if ( redraw )
update();
}
void QgsLayoutItemLegend::doUpdateFilterByMap()
{
if ( mMap )
{
if ( !mThemeName.isEmpty() )
{
// get style overrides for theme
const QMap<QString, QString> overrides = mLayout->project()->mapThemeCollection()->mapThemeStyleOverrides( mThemeName );
mLegendModel->setLayerStyleOverrides( overrides );
}
else
{
mLegendModel->setLayerStyleOverrides( mMap->layerStyleOverrides() );
}
}
else
mLegendModel->setLayerStyleOverrides( QMap<QString, QString>() );
bool filterByExpression = QgsLayerTreeUtils::hasLegendFilterExpression( *( mCustomLayerTree ? mCustomLayerTree.get() : mLayout->project()->layerTreeRoot() ) );
if ( mMap && ( mLegendFilterByMap || filterByExpression || mInAtlas ) )
{
double dpi = mLayout->renderContext().dpi();
QgsRectangle requestRectangle = mMap->requestedExtent();
QSizeF size( requestRectangle.width(), requestRectangle.height() );
size *= mLayout->convertFromLayoutUnits( mMap->mapUnitsToLayoutUnits(), QgsUnitTypes::LayoutMillimeters ).length() * dpi / 25.4;
QgsMapSettings ms = mMap->mapSettings( requestRectangle, size, dpi, true );
QgsGeometry filterPolygon;
if ( mInAtlas )
{
filterPolygon = mLayout->reportContext().currentGeometry( mMap->crs() );
}
mLegendModel->setLegendFilter( &ms, /* useExtent */ mInAtlas || mLegendFilterByMap, filterPolygon, /* useExpressions */ true );
}
else
mLegendModel->setLegendFilterByMap( nullptr );
mForceResize = true;
}
QString QgsLayoutItemLegend::themeName() const
{
return mThemeName;
}
void QgsLayoutItemLegend::setLegendFilterOutAtlas( bool doFilter )
{
mFilterOutAtlas = doFilter;
}
bool QgsLayoutItemLegend::legendFilterOutAtlas() const
{
return mFilterOutAtlas;
}
void QgsLayoutItemLegend::onAtlasFeature()
{
if ( !mLayout->reportContext().feature().isValid() )
return;
mInAtlas = mFilterOutAtlas;
updateFilterByMap();
}
void QgsLayoutItemLegend::onAtlasEnded()
{
mInAtlas = false;
updateFilterByMap();
}
QgsExpressionContext QgsLayoutItemLegend::createExpressionContext() const
{
QgsExpressionContext context = QgsLayoutItem::createExpressionContext();
// We only want the last scope from the map's expression context, as this contains
// the map specific variables. We don't want the rest of the map's context, because that
// will contain duplicate global, project, layout, etc scopes.
if ( mMap )
context.appendScope( mMap->createExpressionContext().popScope() );
QgsExpressionContextScope *scope = new QgsExpressionContextScope( tr( "Legend Settings" ) );
scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_title" ), title(), true ) );
scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_column_count" ), columnCount(), true ) );
scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_split_layers" ), splitLayer(), true ) );
scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_wrap_string" ), wrapString(), true ) );
scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_filter_by_map" ), legendFilterByMapEnabled(), true ) );
scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "legend_filter_out_atlas" ), legendFilterOutAtlas(), true ) );
context.appendScope( scope );
return context;
}
QgsLayoutItem::ExportLayerBehavior QgsLayoutItemLegend::exportLayerBehavior() const
{
return MustPlaceInOwnLayer;
}
bool QgsLayoutItemLegend::accept( QgsStyleEntityVisitorInterface *visitor ) const
{
std::function<bool( QgsLayerTreeGroup *group ) >visit;
visit = [ =, &visit]( QgsLayerTreeGroup * group ) -> bool
{
const QList<QgsLayerTreeNode *> childNodes = group->children();
for ( QgsLayerTreeNode *node : childNodes )
{
if ( QgsLayerTree::isGroup( node ) )
{
QgsLayerTreeGroup *nodeGroup = QgsLayerTree::toGroup( node );
if ( !visit( nodeGroup ) )
return false;
}
else if ( QgsLayerTree::isLayer( node ) )
{
QgsLayerTreeLayer *nodeLayer = QgsLayerTree::toLayer( node );
if ( !nodeLayer->patchShape().isNull() )
{
QgsStyleLegendPatchShapeEntity entity( nodeLayer->patchShape() );
if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity, uuid(), displayName() ) ) )
return false;