-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgswmsserver.cpp
executable file
·1709 lines (1516 loc) · 55.5 KB
/
qgswmsserver.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
/***************************************************************************
qgswmsserver.cpp
-------------------
begin : May 14, 2006
copyright : (C) 2006 by Marco Hugentobler & Ionut Iosifescu Enescu
email : marco dot hugentobler at karto dot baug dot ethz dot ch
***************************************************************************/
/***************************************************************************
* *
* 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 "qgswmsserver.h"
#include "qgsconfigparser.h"
#include "qgsepsgcache.h"
#include "qgsfield.h"
#include "qgsgeometry.h"
#include "qgsmaplayer.h"
#include "qgsmaplayerregistry.h"
#include "qgsmaprenderer.h"
#include "qgsmaptopixel.h"
#include "qgspallabeling.h"
#include "qgsproject.h"
#include "qgsrasterlayer.h"
#include "qgsscalecalculator.h"
#include "qgscoordinatereferencesystem.h"
#include "qgsvectordataprovider.h"
#include "qgsvectorlayer.h"
#include "qgslogger.h"
#include "qgsmapserviceexception.h"
#include "qgssldparser.h"
#include "qgssymbol.h"
#include "qgssymbolv2.h"
#include "qgsrenderer.h"
#include "qgslegendmodel.h"
#include "qgscomposerlegenditem.h"
#include "qgslogger.h"
#include <QImage>
#include <QPainter>
#include <QStringList>
#include <QTextStream>
#include <QDir>
//for printing
#include "qgscomposition.h"
#include <QBuffer>
#include <QPrinter>
#include <QSvgGenerator>
#include <QUrl>
#include <QPaintEngine>
QgsWMSServer::QgsWMSServer( std::map<QString, QString> parameters, QgsMapRenderer* renderer )
: mParameterMap( parameters )
, mConfigParser( 0 )
, mMapRenderer( renderer )
{
}
QgsWMSServer::~QgsWMSServer()
{
}
QgsWMSServer::QgsWMSServer()
{
}
QDomDocument QgsWMSServer::getCapabilities()
{
QgsDebugMsg( "Entering." );
QDomDocument doc;
//wms:WMS_Capabilities element
QDomElement wmsCapabilitiesElement = doc.createElement( "WMS_Capabilities"/*wms:WMS_Capabilities*/ );
wmsCapabilitiesElement.setAttribute( "xmlns", "http://www.opengis.net/wms" );
wmsCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" );
wmsCapabilitiesElement.setAttribute( "xsi:schemaLocation", "http://www.opengis.net/wms http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd" );
wmsCapabilitiesElement.setAttribute( "version", "1.3.0" );
doc.appendChild( wmsCapabilitiesElement );
if ( mConfigParser )
{
mConfigParser->serviceCapabilities( wmsCapabilitiesElement, doc );
}
//wms:Capability element
QDomElement capabilityElement = doc.createElement( "Capability"/*wms:Capability*/ );
wmsCapabilitiesElement.appendChild( capabilityElement );
//wms:Request element
QDomElement requestElement = doc.createElement( "Request"/*wms:Request*/ );
capabilityElement.appendChild( requestElement );
//wms:GetCapabilities
QDomElement getCapabilitiesElement = doc.createElement( "GetCapabilities"/*wms:GetCapabilities*/ );
requestElement.appendChild( getCapabilitiesElement );
QDomElement capabilitiesFormatElement = doc.createElement( "Format" );/*wms:Format*/
getCapabilitiesElement.appendChild( capabilitiesFormatElement );
QDomText capabilitiesFormatText = doc.createTextNode( "text/xml" );
capabilitiesFormatElement.appendChild( capabilitiesFormatText );
QDomElement dcpTypeElement = doc.createElement( "DCPType"/*wms:DCPType*/ );
getCapabilitiesElement.appendChild( dcpTypeElement );
QDomElement httpElement = doc.createElement( "HTTP"/*wms:HTTP*/ );
dcpTypeElement.appendChild( httpElement );
//Prepare url
//Some client requests already have http://<SERVER_NAME> in the REQUEST_URI variable
QString hrefString;
QString requestUrl = getenv( "REQUEST_URI" );
QUrl mapUrl( requestUrl );
mapUrl.setHost( QString( getenv( "SERVER_NAME" ) ) );
mapUrl.removeQueryItem( "REQUEST" );
mapUrl.removeQueryItem( "VERSION" );
mapUrl.removeQueryItem( "SERVICE" );
hrefString = mapUrl.toString();
// SOAP platform
//only give this information if it is not a WMS request to be in sync with the WMS capabilities schema
std::map<QString, QString>::const_iterator service_it = mParameterMap.find( "SERVICE" );
if ( service_it != mParameterMap.end() && service_it->second.compare( "WMS", Qt::CaseInsensitive ) != 0 )
{
QDomElement soapElement = doc.createElement( "SOAP"/*wms:SOAP*/ );
httpElement.appendChild( soapElement );
QDomElement soapResourceElement = doc.createElement( "OnlineResource"/*wms:OnlineResource*/ );
soapResourceElement.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" );
soapResourceElement.setAttribute( "xlink:type", "simple" );
soapResourceElement.setAttribute( "xlink:href", hrefString );
soapElement.appendChild( soapResourceElement );
}
//only Get supported for the moment
QDomElement getElement = doc.createElement( "Get"/*wms:Get*/ );
httpElement.appendChild( getElement );
QDomElement olResourceElement = doc.createElement( "OnlineResource"/*wms:OnlineResource*/ );
olResourceElement.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" );
olResourceElement.setAttribute( "xlink:type", "simple" );
requestUrl.truncate( requestUrl.indexOf( "?" ) + 1 );
olResourceElement.setAttribute( "xlink:href", hrefString );
getElement.appendChild( olResourceElement );
// POST already used by SOAP
// QDomElement postElement = doc.createElement("post"/*wms:SOAP*/);
// httpElement.appendChild(postElement);
// QDomElement postResourceElement = doc.createElement("OnlineResource"/*wms:OnlineResource*/);
// postResourceElement.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");
// postResourceElement.setAttribute("xlink:type","simple");
// postResourceElement.setAttribute("xlink:href", "http://" + QString(getenv("SERVER_NAME")) + QString(getenv("REQUEST_URI")));
// postElement.appendChild(postResourceElement);
// dcpTypeElement.appendChild(postElement);
//wms:GetMap
QDomElement getMapElement = doc.createElement( "GetMap"/*wms:GetMap*/ );
requestElement.appendChild( getMapElement );
QDomElement jpgFormatElement = doc.createElement( "Format"/*wms:Format*/ );
QDomText jpgFormatText = doc.createTextNode( "image/jpeg" );
jpgFormatElement.appendChild( jpgFormatText );
getMapElement.appendChild( jpgFormatElement );
QDomElement pngFormatElement = doc.createElement( "Format"/*wms:Format*/ );
QDomText pngFormatText = doc.createTextNode( "image/png" );
pngFormatElement.appendChild( pngFormatText );
getMapElement.appendChild( pngFormatElement );
QDomElement getMapDhcTypeElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities'
getMapElement.appendChild( getMapDhcTypeElement );
//wms:GetFeatureInfo
QDomElement getFeatureInfoElem = doc.createElement( "GetFeatureInfo" );
//text/plain
QDomElement textFormatElem = doc.createElement( "Format" );
QDomText textFormatText = doc.createTextNode( "text/plain" );
textFormatElem.appendChild( textFormatText );
getFeatureInfoElem.appendChild( textFormatElem );
//text/html
QDomElement htmlFormatElem = doc.createElement( "Format" );
QDomText htmlFormatText = doc.createTextNode( "text/html" );
htmlFormatElem.appendChild( htmlFormatText );
getFeatureInfoElem.appendChild( htmlFormatElem );
//text/xml
QDomElement xmlFormatElem = doc.createElement( "Format" );
QDomText xmlFormatText = doc.createTextNode( "text/xml" );
xmlFormatElem.appendChild( xmlFormatText );
getFeatureInfoElem.appendChild( xmlFormatElem );
//dcpType
QDomElement getFeatureInfoDhcTypeElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities'
getFeatureInfoElem.appendChild( getFeatureInfoDhcTypeElement );
requestElement.appendChild( getFeatureInfoElem );
//Exception element is mandatory
QDomElement exceptionElement = doc.createElement( "Exception" );
QDomElement exFormatElement = doc.createElement( "Format" );
QDomText formatText = doc.createTextNode( "text/xml" );
exFormatElement.appendChild( formatText );
exceptionElement.appendChild( exFormatElement );
capabilityElement.appendChild( exceptionElement );
//Insert <ComposerTemplate> elements derived from wms:_ExtendedCapabilities
if ( mConfigParser )
{
mConfigParser->printCapabilities( capabilityElement, doc );
}
//add the xml content for the individual layers/styles
QgsDebugMsg( "calling layersAndStylesCapabilities" );
if ( mConfigParser )
{
mConfigParser->layersAndStylesCapabilities( capabilityElement, doc );
}
QgsDebugMsg( "layersAndStylesCapabilities returned" );
#if 0
//for debugging: save the document to disk
QFile capabilitiesFile( QDir::tempPath() + "/capabilities.txt" );
if ( capabilitiesFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
{
QTextStream capabilitiesStream( &capabilitiesFile );
doc.save( capabilitiesStream, 4 );
}
#endif
return doc;
}
QImage* QgsWMSServer::getLegendGraphics()
{
if ( !mConfigParser || !mMapRenderer )
{
return false;
}
QStringList layersList, stylesList;
if ( readLayersAndStyles( layersList, stylesList ) != 0 )
{
QgsDebugMsg( "error reading layers and styles" );
return 0;
}
if ( layersList.size() < 1 )
{
return 0;
}
QgsCoordinateReferenceSystem dummyCRS;
QStringList layerIds = layerSet( layersList, stylesList, dummyCRS );
QgsLegendModel legendModel;
legendModel.setLayerSet( layerIds );
//create first image (to find out dpi)
QImage* theImage = createImage( 10, 10 );
if ( !theImage )
{
return 0;
}
double mmToPixelFactor = theImage->dotsPerMeterX() / 1000;
//get icon size, spaces between legend items and font from config parser
double boxSpace, layerSpace, symbolSpace, iconLabelSpace, symbolWidth, symbolHeight;
boxSpace = mConfigParser->legendBoxSpace() * mmToPixelFactor;
layerSpace = mConfigParser->legendLayerSpace() * mmToPixelFactor;
symbolSpace = mConfigParser->legendSymbolSpace() * mmToPixelFactor;
iconLabelSpace = mConfigParser->legendIconLabelSpace() * mmToPixelFactor;
symbolWidth = mConfigParser->legendSymbolWidth() * mmToPixelFactor;
symbolHeight = mConfigParser->legendSymbolHeight() * mmToPixelFactor;
double maxTextWidth = 0;
double maxSymbolWidth = 0;
double currentY = 0;
double fontOversamplingFactor = 10.0;
QFont layerFont = mConfigParser->legendLayerFont();
layerFont.setPixelSize( layerFont.pointSizeF() * 0.3528 * mmToPixelFactor * fontOversamplingFactor );
QFont itemFont = mConfigParser->legendItemFont();
itemFont.setPixelSize( itemFont.pointSizeF() * 0.3528 * mmToPixelFactor * fontOversamplingFactor );
//first find out image dimensions without painting
QStandardItem* rootItem = legendModel.invisibleRootItem();
if ( !rootItem )
{
return 0;
}
int numLayerItems = rootItem->rowCount();
if ( numLayerItems < 1 )
{
return 0;
}
currentY = boxSpace;
for ( int i = 0; i < numLayerItems; ++i )
{
QgsComposerLayerItem* layerItem = dynamic_cast<QgsComposerLayerItem*>( rootItem->child( i ) );
if ( layerItem )
{
drawLegendLayerItem( layerItem, 0, maxTextWidth, maxSymbolWidth, currentY, layerFont, itemFont, boxSpace, layerSpace, symbolSpace,
iconLabelSpace, symbolWidth, symbolHeight, fontOversamplingFactor, theImage->dotsPerMeterX() * 0.0254 );
}
}
currentY += boxSpace;
//create second image with the right dimensions
QImage* paintImage = createImage( maxTextWidth + maxSymbolWidth, currentY );
//go through the items a second time for painting
QPainter p( paintImage );
p.setRenderHint( QPainter::Antialiasing, true );
currentY = boxSpace;
for ( int i = 0; i < numLayerItems; ++i )
{
QgsComposerLayerItem* layerItem = dynamic_cast<QgsComposerLayerItem*>( rootItem->child( i ) );
if ( layerItem )
{
drawLegendLayerItem( layerItem, &p, maxTextWidth, maxSymbolWidth, currentY, layerFont, itemFont, boxSpace, layerSpace, symbolSpace,
iconLabelSpace, symbolWidth, symbolHeight, fontOversamplingFactor, theImage->dotsPerMeterX() * 0.0254 );
}
}
QgsMapLayerRegistry::instance()->mapLayers().clear();
delete theImage;
return paintImage;
}
QDomDocument QgsWMSServer::getStyle()
{
QDomDocument doc;
std::map<QString, QString>::const_iterator style_it = mParameterMap.find( "STYLE" );
if ( style_it == mParameterMap.end() )
{
throw QgsMapServiceException( "StyleNotSpecified", "Style is mandatory for GetStyle operation" );
}
std::map<QString, QString>::const_iterator layer_it = mParameterMap.find( "LAYER" );
if ( layer_it == mParameterMap.end() )
{
throw QgsMapServiceException( "LayerNotSpecified", "Layer is mandatory for GetStyle operation" );
}
QString styleName = style_it->second;
QString layerName = layer_it->second;
return mConfigParser->getStyle( styleName, layerName );
}
// Hack to workaround Qt #5114 by disabling PatternTransform
class QgsPaintEngineHack : public QPaintEngine
{
public:
void fixFlags()
{
gccaps = 0;
gccaps |= ( QPaintEngine::PrimitiveTransform
// | QPaintEngine::PatternTransform
| QPaintEngine::PixmapTransform
| QPaintEngine::PatternBrush
// | QPaintEngine::LinearGradientFill
// | QPaintEngine::RadialGradientFill
// | QPaintEngine::ConicalGradientFill
| QPaintEngine::AlphaBlend
// | QPaintEngine::PorterDuff
| QPaintEngine::PainterPaths
| QPaintEngine::Antialiasing
| QPaintEngine::BrushStroke
| QPaintEngine::ConstantOpacity
| QPaintEngine::MaskedBrush
// | QPaintEngine::PerspectiveTransform
| QPaintEngine::BlendModes
// | QPaintEngine::ObjectBoundingModeGradients
#if QT_VERSION >= 0x040500
| QPaintEngine::RasterOpModes
#endif
| QPaintEngine::PaintOutsidePaintEvent
);
}
};
QByteArray* QgsWMSServer::getPrint( const QString& formatString )
{
QStringList layersList, stylesList, layerIdList;
QString dummyFormat;
QImage* theImage = initializeRendering( layersList, stylesList, layerIdList );
if ( !theImage )
{
return 0;
}
delete theImage;
QMap<QString, QString> originalLayerFilters = applyRequestedLayerFilters( layersList, layerIdList );
//GetPrint request needs a template parameter
std::map<QString, QString>::const_iterator templateIt = mParameterMap.find( "TEMPLATE" );
if ( templateIt == mParameterMap.end() )
{
throw QgsMapServiceException( "ParameterMissing", "The TEMPLATE parameter is required for the GetPrint request" );
}
QgsComposition* c = mConfigParser->createPrintComposition( templateIt->second, mMapRenderer, QMap<QString, QString>( mParameterMap ) );
if ( !c )
{
restoreLayerFilters( originalLayerFilters );
return 0;
}
QByteArray* ba = 0;
c->setPlotStyle( QgsComposition::Print );
//SVG export without a running X-Server is a problem. See e.g. http://developer.qt.nokia.com/forums/viewthread/2038
if ( formatString.compare( "svg", Qt::CaseInsensitive ) == 0 )
{
c->setPlotStyle( QgsComposition::Print );
QSvgGenerator generator;
ba = new QByteArray();
QBuffer svgBuffer( ba );
generator.setOutputDevice( &svgBuffer );
int width = ( int )( c->paperWidth() * c->printResolution() / 25.4 ); //width in pixel
int height = ( int )( c->paperHeight() * c->printResolution() / 25.4 ); //height in pixel
generator.setSize( QSize( width, height ) );
generator.setResolution( c->printResolution() ); //because the rendering is done in mm, convert the dpi
QPainter p( &generator );
QRectF sourceArea( 0, 0, c->paperWidth(), c->paperHeight() );
QRectF targetArea( 0, 0, width, height );
if ( c->printAsRaster() ) //embed one raster into the svg
{
QImage* img = printCompositionToImage( c );
if ( img )
{
p.drawImage( targetArea, *img, QRectF( 0, 0, img->width(), img->height() ) );
}
delete img;
}
else
{
c->render( &p, targetArea, sourceArea );
}
p.end();
}
else if ( formatString.compare( "png", Qt::CaseInsensitive ) == 0 || formatString.compare( "jpg", Qt::CaseInsensitive ) == 0 )
{
QImage* image = printCompositionToImage( c );
if ( image )
{
ba = new QByteArray();
QBuffer buffer( ba );
buffer.open( QIODevice::WriteOnly );
image->save( &buffer, formatString.toLocal8Bit().data(), -1 );
}
delete image;
}
else if ( formatString.compare( "pdf", Qt::CaseInsensitive ) == 0 )
{
QTemporaryFile tempFile;
if ( !tempFile.open() )
{
delete c;
restoreLayerFilters( originalLayerFilters );
return 0;
}
QPrinter printer;
printer.setResolution( c->printResolution() );
printer.setFullPage( true );
printer.setOutputFormat( QPrinter::PdfFormat );
printer.setOutputFileName( tempFile.fileName() );
printer.setPaperSize( QSizeF( c->paperWidth(), c->paperHeight() ), QPrinter::Millimeter );
QRectF paperRectMM = printer.pageRect( QPrinter::Millimeter );
QRectF paperRectPixel = printer.pageRect( QPrinter::DevicePixel );
QPaintEngine *engine = printer.paintEngine();
if ( engine )
{
QgsPaintEngineHack *hack = static_cast<QgsPaintEngineHack*>( engine );
hack->fixFlags();
}
QPainter p( &printer );
if ( c->printAsRaster() ) //embed one raster into the pdf
{
QImage* img = printCompositionToImage( c );
if ( img )
{
p.drawImage( paperRectPixel, *img, QRectF( 0, 0, img->width(), img->height() ) );
}
delete img;
}
else //vector pdf
{
c->render( &p, paperRectPixel, paperRectMM );
}
p.end();
ba = new QByteArray();
*ba = tempFile.readAll();
}
else //unknown format
{
throw QgsMapServiceException( "InvalidFormat", "Output format '" + formatString + "' is not supported in the GetPrint request" );
}
restoreLayerFilters( originalLayerFilters );
delete c;
return ba;
}
QImage* QgsWMSServer::printCompositionToImage( QgsComposition* c ) const
{
int width = ( int )( c->paperWidth() * c->printResolution() / 25.4 ); //width in pixel
int height = ( int )( c->paperHeight() * c->printResolution() / 25.4 ); //height in pixel
QImage* image = new QImage( QSize( width, height ), QImage::Format_ARGB32 );
image->setDotsPerMeterX( c->printResolution() / 25.4 * 1000 );
image->setDotsPerMeterY( c->printResolution() / 25.4 * 1000 );
image->fill( 0 );
QPainter p( image );
QRectF sourceArea( 0, 0, c->paperWidth(), c->paperHeight() );
QRectF targetArea( 0, 0, width, height );
c->render( &p, targetArea, sourceArea );
p.end();
return image;
}
QImage* QgsWMSServer::getMap()
{
QStringList layersList, stylesList, layerIdList;
QImage* theImage = initializeRendering( layersList, stylesList, layerIdList );
QPainter thePainter( theImage );
thePainter.setRenderHint( QPainter::Antialiasing ); //make it look nicer
QMap<QString, QString> originalLayerFilters = applyRequestedLayerFilters( layersList, layerIdList );
mMapRenderer->render( &thePainter );
restoreLayerFilters( originalLayerFilters );
QgsMapLayerRegistry::instance()->mapLayers().clear();
return theImage;
}
int QgsWMSServer::getFeatureInfo( QDomDocument& result )
{
if ( !mMapRenderer || !mConfigParser )
{
return 1;
}
result.clear();
QStringList layersList, stylesList;
bool conversionSuccess;
for ( std::map<QString, QString>::iterator it = mParameterMap.begin(); it != mParameterMap.end(); ++it )
{
QgsDebugMsg( QString( "%1 // %2" ).arg( it->first ).arg( it->second ) );
}
if ( readLayersAndStyles( layersList, stylesList ) != 0 )
{
return 0;
}
if ( initializeSLDParser( layersList, stylesList ) != 0 )
{
return 0;
}
QImage* outputImage = createImage();
if ( !outputImage )
{
return 1;
}
if ( configureMapRender( outputImage ) != 0 )
{
delete outputImage;
return 2;
}
//find out the current scale denominater and set it to the SLD parser
QgsScaleCalculator scaleCalc(( outputImage->logicalDpiX() + outputImage->logicalDpiY() ) / 2 , mMapRenderer->destinationCrs().mapUnits() );
QgsRectangle mapExtent = mMapRenderer->extent();
mConfigParser->setScaleDenominator( scaleCalc.calculate( mapExtent, outputImage->width() ) );
delete outputImage; //no longer needed for feature info
//read FEATURE_COUNT
int featureCount = 1;
std::map<QString, QString>::const_iterator feature_count_it = mParameterMap.find( "FEATURE_COUNT" );
if ( feature_count_it != mParameterMap.end() )
{
featureCount = feature_count_it->second.toInt( &conversionSuccess );
if ( !conversionSuccess )
{
featureCount = 1;
}
}
//read QUERY_LAYERS
std::map<QString, QString>::const_iterator query_layers_it = mParameterMap.find( "QUERY_LAYERS" );
if ( query_layers_it == mParameterMap.end() )
{
return 3;
}
QStringList queryLayerList = query_layers_it->second.split( ",", QString::SkipEmptyParts );
if ( queryLayerList.size() < 1 )
{
return 4;
}
//read I,J resp. X,Y
QString iString, jString;
int i = -1;
int j = -1;
std::map<QString, QString>::const_iterator i_it = mParameterMap.find( "I" );
if ( i_it == mParameterMap.end() )
{
std::map<QString, QString>::const_iterator x_it = mParameterMap.find( "X" );
if ( x_it == mParameterMap.end() )
{
return 5;
}
iString = x_it->second;
}
else
{
iString = i_it->second;
}
i = iString.toInt( &conversionSuccess );
if ( !conversionSuccess )
{
return 6;
}
std::map<QString, QString>::const_iterator j_it = mParameterMap.find( "J" );
if ( j_it == mParameterMap.end() )
{
std::map<QString, QString>::const_iterator y_it = mParameterMap.find( "Y" );
if ( y_it == mParameterMap.end() )
{
return 7;
}
jString = y_it->second;
}
else
{
jString = j_it->second;
}
j = jString.toInt( &conversionSuccess );
if ( !conversionSuccess )
{
return 8;
}
QDomElement getFeatureInfoElement = result.createElement( "GetFeatureInfoResponse" );
result.appendChild( getFeatureInfoElement );
QStringList nonIdentifiableLayers = mConfigParser->identifyDisabledLayers();
QMap< QString, QMap< int, QString > > aliasInfo = mConfigParser->layerAliasInfo();
QMap< QString, QSet<QString> > hiddenAttributes = mConfigParser->hiddenAttributes();
QList<QgsMapLayer*> layerList;
QgsMapLayer* currentLayer = 0;
QgsPoint infoPoint; //info point in coordinates of the layer
QStringList::const_iterator layerIt;
for ( layerIt = queryLayerList.constBegin(); layerIt != queryLayerList.constEnd(); ++layerIt )
{
//create maplayer from sld parser
layerList = mConfigParser->mapLayerFromStyle( *layerIt, "" );
currentLayer = layerList.at( 0 );
if ( !currentLayer || nonIdentifiableLayers.contains( currentLayer->id() ) )
{
continue;
}
if ( infoPointToLayerCoordinates( i, j, infoPoint, mMapRenderer, currentLayer ) != 0 )
{
continue;
}
QgsDebugMsg( "Info point in layer crs: " + QString::number( infoPoint.x() ) + "//" + QString::number( infoPoint.y() ) );
QDomElement layerElement = result.createElement( "Layer" );
layerElement.setAttribute( "name", currentLayer->name() );
getFeatureInfoElement.appendChild( layerElement );
//switch depending on vector or raster
QgsVectorLayer* vectorLayer = dynamic_cast<QgsVectorLayer*>( currentLayer );
if ( vectorLayer )
{
//is there alias info for this vector layer?
QMap< int, QString > layerAliasInfo;
QMap< QString, QMap< int, QString > >::const_iterator aliasIt = aliasInfo.find( currentLayer->id() );
if ( aliasIt != aliasInfo.constEnd() )
{
layerAliasInfo = aliasIt.value();
}
//hidden attributes for this layer
QSet<QString> layerHiddenAttributes;
QMap< QString, QSet<QString> >::const_iterator hiddenIt = hiddenAttributes.find( currentLayer->id() );
if ( hiddenIt != hiddenAttributes.constEnd() )
{
layerHiddenAttributes = hiddenIt.value();
}
if ( featureInfoFromVectorLayer( vectorLayer, infoPoint, featureCount, result, layerElement, mMapRenderer, layerAliasInfo, layerHiddenAttributes ) != 0 )
{
return 9;
}
}
else //raster layer
{
QgsRasterLayer* rasterLayer = dynamic_cast<QgsRasterLayer*>( currentLayer );
if ( rasterLayer )
{
if ( featureInfoFromRasterLayer( rasterLayer, infoPoint, result, layerElement ) != 0 )
{
return 10;
}
}
else
{
return 11;
}
}
}
return 0;
}
QImage* QgsWMSServer::initializeRendering( QStringList& layersList, QStringList& stylesList, QStringList& layerIdList )
{
if ( !mConfigParser )
{
QgsDebugMsg( "Error: mSLDParser is 0" );
return 0;
}
if ( !mMapRenderer )
{
QgsDebugMsg( "Error: mMapRenderer is 0" );
return 0;
}
if ( readLayersAndStyles( layersList, stylesList ) != 0 )
{
QgsDebugMsg( "error reading layers and styles" );
return 0;
}
if ( initializeSLDParser( layersList, stylesList ) != 0 )
{
return 0;
}
//pass external GML to the SLD parser.
std::map<QString, QString>::const_iterator gmlIt = mParameterMap.find( "GML" );
if ( gmlIt != mParameterMap.end() )
{
QDomDocument* gmlDoc = new QDomDocument();
if ( gmlDoc->setContent( gmlIt->second, true ) )
{
QString layerName = gmlDoc->documentElement().attribute( "layerName" );
QgsDebugMsg( "Adding entry with key: " + layerName + " to external GML data" );
mConfigParser->addExternalGMLData( layerName, gmlDoc );
}
else
{
QgsDebugMsg( "Error, could not add external GML to QgsSLDParser" );
delete gmlDoc;
}
}
QImage* theImage = createImage();
if ( !theImage )
{
return 0;
}
if ( configureMapRender( theImage ) != 0 )
{
delete theImage;
return 0;
}
mMapRenderer->setLabelingEngine( new QgsPalLabeling() );
//find out the current scale denominater and set it to the SLD parser
QgsScaleCalculator scaleCalc(( theImage->logicalDpiX() + theImage->logicalDpiY() ) / 2 , mMapRenderer->destinationCrs().mapUnits() );
QgsRectangle mapExtent = mMapRenderer->extent();
mConfigParser->setScaleDenominator( scaleCalc.calculate( mapExtent, theImage->width() ) );
layerIdList = layerSet( layersList, stylesList, mMapRenderer->destinationCrs() );
#ifdef QGISDEBUG
QgsDebugMsg( QString( "Number of layers to be rendered. %1" ).arg( layerIdList.count() ) );
#endif
mMapRenderer->setLayerSet( layerIdList );
return theImage;
}
QImage* QgsWMSServer::createImage( int width, int height ) const
{
bool conversionSuccess;
if ( width < 0 )
{
std::map<QString, QString>::const_iterator wit = mParameterMap.find( "WIDTH" );
if ( wit == mParameterMap.end() )
{
width = 0; //width parameter is mandatory
}
else
{
width = wit->second.toInt( &conversionSuccess );
if ( !conversionSuccess )
{
width = 0;
}
}
}
if ( height < 0 )
{
std::map<QString, QString>::const_iterator hit = mParameterMap.find( "HEIGHT" );
if ( hit == mParameterMap.end() )
{
height = 0; //height parameter is mandatory
}
else
{
height = hit->second.toInt( &conversionSuccess );
if ( !conversionSuccess )
{
height = 0;
}
}
}
if ( width < 0 || height < 0 )
{
return 0;
}
QImage* theImage = 0;
//is format jpeg?
bool jpeg = false;
std::map<QString, QString>::const_iterator formatIt = mParameterMap.find( "FORMAT" );
if ( formatIt != mParameterMap.end() )
{
if ( formatIt->second.compare( "jpg", Qt::CaseInsensitive ) == 0
|| formatIt->second.compare( "jpeg", Qt::CaseInsensitive ) == 0
|| formatIt->second.compare( "image/jpeg", Qt::CaseInsensitive ) == 0 )
{
jpeg = true;
}
}
//transparent parameter
bool transparent = false;
std::map<QString, QString>::const_iterator transparentIt = mParameterMap.find( "TRANSPARENT" );
if ( transparentIt != mParameterMap.end() && transparentIt->second.compare( "true", Qt::CaseInsensitive ) == 0 )
{
transparent = true;
}
//use alpha channel only if necessary because it slows down performance
if ( transparent && !jpeg )
{
theImage = new QImage( width, height, QImage::Format_ARGB32_Premultiplied );
theImage->fill( 0 );
}
else
{
theImage = new QImage( width, height, QImage::Format_RGB32 );
theImage->fill( qRgb( 255, 255, 255 ) );
}
if ( !theImage )
{
return 0;
}
//apply DPI parameter if present. This is an extension of QGIS mapserver compared to WMS 1.3.
//Because of backwards compatibility, this parameter is optional
std::map<QString, QString>::const_iterator dit = mParameterMap.find( "DPI" );
if ( dit != mParameterMap.end() )
{
int dpi = dit->second.toInt( &conversionSuccess );
if ( conversionSuccess )
{
int dpm = dpi / 0.0254;
theImage->setDotsPerMeterX( dpm );
theImage->setDotsPerMeterY( dpm );
}
}
return theImage;
}
int QgsWMSServer::configureMapRender( const QPaintDevice* paintDevice ) const
{
if ( !mMapRenderer || !paintDevice )
{
return 1; //paint device is needed for height, width, dpi
}
mMapRenderer->setOutputSize( QSize( paintDevice->width(), paintDevice->height() ), paintDevice->logicalDpiX() );
//map extent
bool conversionSuccess;
double minx, miny, maxx, maxy;
std::map<QString, QString>::const_iterator bbIt = mParameterMap.find( "BBOX" );
if ( bbIt == mParameterMap.end() )
{
//GetPrint request is allowed to have missing BBOX parameter
minx = 0; miny = 0; maxx = 0; maxy = 0;
}
else
{
bool bboxOk = true;
QString bbString = bbIt->second;
minx = bbString.section( ",", 0, 0 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
bboxOk = false;
miny = bbString.section( ",", 1, 1 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
bboxOk = false;
maxx = bbString.section( ",", 2, 2 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
bboxOk = false;
maxy = bbString.section( ",", 3, 3 ).toDouble( &conversionSuccess );
if ( !conversionSuccess )
bboxOk = false;
if ( !bboxOk )
{
//throw a service exception
throw QgsMapServiceException( "InvalidParameterValue", "Invalid BBOX parameter" );
}
}
QGis::UnitType mapUnits = QGis::Degrees;
std::map<QString, QString>::const_iterator crsIt = mParameterMap.find( "CRS" );
if ( crsIt == mParameterMap.end() )
{
crsIt = mParameterMap.find( "SRS" ); //some clients (e.g. QGIS) call it SRS
}
QgsCoordinateReferenceSystem outputCRS;
//wms spec says that CRS parameter is mandatory.
//we don't rejeict the request if it is not there but disable reprojection on the fly
if ( crsIt == mParameterMap.end() )
{
//disable on the fly projection
QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectionsEnabled", 0 );
}
else
{
//enable on the fly projection
QgsDebugMsg( "enable on the fly projection" );
QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectionsEnabled", 1 );
QString crsString = crsIt->second;
if ( !( crsString.left( 4 ) == "EPSG" ) )
{
return 3; // only EPSG ids supported
}
long epsgId = crsString.section( ":", 1, 1 ).toLong( &conversionSuccess );
if ( !conversionSuccess )
{
return 4;
}
//destination SRS
outputCRS = QgsEPSGCache::instance()->searchCRS( epsgId );
if ( !outputCRS.isValid() )
{
QgsDebugMsg( "Error, could not create output CRS from EPSG" );
throw QgsMapServiceException( "InvalidCRS", "Could not create output CRS" );
return 5;
}
mMapRenderer->setDestinationCrs( outputCRS );
mMapRenderer->setProjectionsEnabled( true );
mapUnits = outputCRS.mapUnits();
}
mMapRenderer->setMapUnits( mapUnits );
//Change x- and y- of BBOX for WMS 1.3.0 and geographic coordinate systems
std::map<QString, QString>::const_iterator versionIt = mParameterMap.find( "VERSION" );
if ( versionIt != mParameterMap.end() )
{
QString version = versionIt->second;
if ( version == "1.3.0" && outputCRS.geographicFlag() )
{
//switch coordinates of extent
double tmp;
tmp = minx;
minx = miny; miny = tmp;
tmp = maxx;
maxx = maxy; maxy = tmp;
}
}
QgsRectangle mapExtent( minx, miny, maxx, maxy );
mMapRenderer->setExtent( mapExtent );
if ( mConfigParser )
{
mMapRenderer->setOutputUnits( mConfigParser->outputUnits() );