-
Notifications
You must be signed in to change notification settings - Fork 14
/
mapfileexportdlg.py
379 lines (292 loc) · 14.8 KB
/
mapfileexportdlg.py
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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : RT MapServer Exporter
Description : A plugin to export qgs project to mapfile
Date : Oct 21, 2012
copyright : (C) 2012 by Giuseppe Sucameli (Faunalia)
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from .ui.mapfileexportdlg_ui import Ui_MapfileExportDlg
import MapfileExporter
import utils
from utils import toUTF8
class MapfileExportDlg(QDialog, Ui_MapfileExportDlg):
def __init__(self, iface, parent=None):
QDialog.__init__(self, parent)
self.setupUi(self)
self.iface = iface
self.canvas = self.iface.mapCanvas()
self.legend = self.iface.legendInterface()
# hide map unit combo and label
self.lblMapUnits.hide()
self.cmbMapUnits.hide()
# setup the template table
m = TemplateModel(self)
for layer in self.legend.layers():
m.append( layer )
self.templateTable.setModel(m)
d = TemplateDelegate(self)
self.templateTable.setItemDelegate(d)
# get the default title from the project
title = QgsProject.instance().title()
if title == "":
title = QFileInfo( QgsProject.instance().fileName() ).completeBaseName()
if title != "":
self.txtMapName.setText( title )
# Set the export method based on the user's last choice (default to SLD)
settings = QSettings()
useSLD = settings.value("/rt_mapserver_exporter/useSLD", True, type=bool)
self.checkExportSLD.setChecked(useSLD);
self.checkExportCustom.setChecked(not useSLD);
# fill the image format combo
self.cmbMapImageType.addItems( ["png", "gif", "jpeg", "svg", "GTiff"] )
QObject.connect( self.btnChooseFile, SIGNAL("clicked()"), self.selectMapFile )
QObject.connect( self.btnChooseTemplate, SIGNAL("clicked()"), self.selectTemplateBody )
QObject.connect( self.btnChooseTmplHeader, SIGNAL("clicked()"), self.selectTemplateHeader )
QObject.connect( self.btnChooseTmplFooter, SIGNAL("clicked()"), self.selectTemplateFooter )
QObject.connect( self.lblHelpMeDecide, SIGNAL("linkActivated(QString)"), self.showExportMethodHint )
def showExportMethodHint(self):
QMessageBox.information(
self,
"On Vector Style Export Methods",
""" <style>p { margin-bottom: 1em; }</style>
<p>MapServer Exporter offers two methods for exporting vector layer styles (export of non-vector layers
remains unchanged):</p>
<ul>
<li><p><b>SLD-based method:</b></p>
<p>This method uses the SLD (Styled Layer Descriptor) standard as the exchange format for vector
styles between QGIS and MapServer. However, the SLD standard is only partially implemented in
both QGIS and MapServer. This may result in incorrectly or incompletely exported vector
styles.</p>
<p>Support for SLD might improve in the future and when it does, you get to enjoy it
automatically, without updating this plugin.</p>
<p><i>(This is the method used by previous versions of MapServer Exporter.)</i></p>
</li>
<li><p><b>New Python-based exporter:</b></p>
<p>This method uses a custom-made exporter written in Python. It does not aim to be
a comprehensive solution to the problem of exporting vector styles but we believe it currently
offers a more faithful rendering of the most commonly used style elements than the SLD-based
method does.</p>
<p>This exporter is included with the plugin, therefore new features and bug fixes depend on
updating the plugin itself. If SLD support gains momentum in the future, certain parts of it may
become obsolete and will be superseded by the first method.</p>
<p><a href="https://github.com/faunalia/rt_mapserver_exporter/pull/5#issue-101595345">
Click here for a visual comparison and a list of features supported by the new method.
</a></p>
</li>
</ul>
"""
)
def selectMapFile(self):
# retrieve the last used map file path
settings = QSettings()
lastUsedFile = settings.value("/rt_mapserver_exporter/lastUsedFile", "", type=str)
# ask for choosing where to store the map file
filename = QFileDialog.getSaveFileName(self, "Select where to save the map file", lastUsedFile, "MapFile (*.map)")
if filename == "":
return
# store the last used map file path
settings.setValue("/rt_mapserver_exporter/lastUsedFile", filename)
# update the displayd path
self.txtMapFilePath.setText( filename )
def selectTemplateBody(self):
self.selectTemplateFile( self.txtTemplatePath )
def selectTemplateHeader(self):
self.selectTemplateFile( self.txtTmplHeaderPath )
def selectTemplateFooter(self):
self.selectTemplateFile( self.txtTmplFooterPath )
def selectTemplateFile(self, lineedit):
# retrieve the last used template file path
settings = QSettings()
lastUsedFile = settings.value("/rt_mapserver_exporter/lastUsedTmpl", "", type=str)
# ask for choosing where to store the map file
filename = QFileDialog.getOpenFileName(self, "Select the template file", lastUsedFile, "Template (*.html *.tmpl);;All files (*);;")
if filename == "":
return
# store the last used map file path
settings.setValue("/rt_mapserver_exporter/lastUsedTmpl", filename)
# update the path
lineedit.setText( filename )
def accept(self):
# check user inputs
if self.txtMapFilePath.text() == "":
QMessageBox.warning(self, "RT MapServer Exporter", "Mapfile output path is required")
else:
units = utils.unitMap[self.canvas.mapUnits()]
if self.cmbMapUnits.currentIndex() >= 0:
u, result = self.cmbMapUnits.itemData(self.cmbMapUnits.currentIndex())
if result:
units = u
MapfileExporter.export(
name = toUTF8(self.txtMapName.text()),
width = int(self.txtMapWidth.text()),
height = int(self.txtMapHeight.text()),
units = units,
extent = self.canvas.fullExtent(),
projection = toUTF8(self.canvas.mapRenderer().destinationCrs().toProj4()),
shapePath = toUTF8(self.txtMapShapePath.text()),
backgroundColor = self.canvas.canvasColor(),
imageType = toUTF8(self.cmbMapImageType.currentText()),
imagePath = toUTF8(self.getWebImagePath()),
imageURL = toUTF8(self.getWebImageUrl()),
tempPath = toUTF8(self.getWebTemporaryPath()),
validationRegexp = toUTF8(self.getExternalGraphicRegexp()),
templatePath = toUTF8(self.getTemplatePath()),
templateHeaderPath = toUTF8(self.getTemplateHeaderPath()),
templateFooterPath = toUTF8(self.getTemplateFooterPath()),
mapServerURL = toUTF8(self.txtMapServerUrl.text()),
mapfilePath = self.txtMapFilePath.text(),
createFontFile = self.checkCreateFontFile.isChecked(),
fontsetPath = toUTF8(self.txtMapFontsetPath.text()),
useSLD = self.checkExportSLD.isChecked(),
layers = self.legend.layers(),
legend = self.legend
)
settings = QSettings()
settings.setValue("/rt_mapserver_exporter/useSLD", self.checkExportSLD.isChecked())
QDialog.accept(self)
def generateTemplate(self):
tmpl = u""
if self.getTemplateHeaderPath() == "":
tmpl += u'''<!-- MapServer Template -->
<html>
<head>
<title>%s</title>
</head>
<body>
''' % self.txtMapName.text()
for lid, orientation in self.templateTable.model().getObjectIter():
layer = QgsMapLayerRegistry.instance().mapLayer(lid)
if not layer:
continue
# define the template file content
tmpl += '[resultset layer="%s"]\n' % layer.name()
layerTitle = layer.title() if layer.title() != "" else layer.name()
tmpl += u'<b>"%s"</b>\n' % layerTitle
tmpl += '<table class="idtmplt_tableclass">\n'
if orientation == Qt.Horizontal:
tmpl += ' <tr class="idtmplt_trclass_1h">\n'
for idx, fld in enumerate(layer.dataProvider().fields()):
fldDescr = fld.comment() if fld.comment() != "" else fld.name()
tmpl += u' <td class="idtmplt_tdclass_1h">"%s"</td>\n' % fldDescr
tmpl += '</tr>\n'
tmpl += '[feature limit=20]\n'
tmpl += ' <tr class="idtmplt_trclass_2h">\n'
for idx, fld in enumerate(layer.dataProvider().fields()):
fldDescr = fld.comment() if fld.comment() != "" else fld.name()
tmpl += u' <td class="idtmplt_tdclass_2h">[item name="%s"]</td>\n' % fld.name()
tmpl += ' </tr>\n'
tmpl += '[/feature]\n'
else:
for idx, fld in enumerate(layer.dataProvider().fields()):
tmpl += ' <tr class="idtmplt_trclass_v">\n'
fldDescr = fld.comment() if fld.comment() != "" else fld.name()
tmpl += u' <td class="idtmplt_tdclass_1v">"%s"</td>\n' % fldDescr
tmpl += '[feature limit=20]\n'
tmpl += u' <td class="idtmplt_tdclass_2v">[item name="%s"]</td>\n' % fld.name()
tmpl += '[/feature]\n'
tmpl += ' </tr>\n'
tmpl += '</table>\n'
tmpl += '[/resultset]\n'
tmpl += '<hr>\n'
if self.getTemplateFooterPath() == "":
tmpl += ''' </body>
</html>'''
return tmpl
def getTemplatePath(self):
if self.checkTmplFromFile.isChecked():
return self.txtTemplatePath.text() # "[templatepath]"
elif self.checkGenerateTmpl.isChecked():
# generate the template for layers
tmplContent = self.generateTemplate()
# store the template alongside the mapfile
tmplPath = self.txtMapFilePath.text() + ".html.tmpl"
with open(unicode(tmplPath), 'w') as fout:
fout.write(toUTF8(tmplContent))
return tmplPath
def getTemplateHeaderPath(self):
return self.txtTmplHeaderPath.text()
def getTemplateFooterPath(self):
return self.txtTmplFooterPath.text()
def getMapShapePath(self):
return self.txtMapShapePath.text()
def getWebImagePath(self):
return self.txtWebImagePath.text() #"/tmp/"
def getWebImageUrl(self):
return self.txtWebImageUrl.text() #"/tmp/"
def getWebTemporaryPath(self):
return self.txtWebTempPath.text() #"/tmp/"
def getExternalGraphicRegexp(self):
return self.txtExternalGraphicRegexp.text()
class TemplateDelegate(QItemDelegate):
""" delegate with some special item editors """
def createEditor(self, parent, option, index):
# special combobox for orientation
if index.column() == 1:
cbo = QComboBox(parent)
cbo.setEditable(False)
cbo.setFrame(False)
for val, txt in enumerate(TemplateModel.ORIENTATIONS):
cbo.addItem(txt, val)
return cbo
return QItemDelegate.createEditor(self, parent, option, index)
def setEditorData(self, editor, index):
""" load data from model to editor """
m = index.model()
if index.column() == 1:
val = m.data(index, Qt.UserRole)[0]
editor.setCurrentIndex( editor.findData(val) )
else:
# use default
QItemDelegate.setEditorData(self, editor, index)
def setModelData(self, editor, model, index):
""" save data from editor back to model """
if index.column() == 1:
val = editor.itemData(editor.currentIndex())[0]
model.setData(index, TemplateModel.ORIENTATIONS[val])
model.setData(index, val, Qt.UserRole)
else:
# use default
QItemDelegate.setModelData(self, editor, model, index)
class TemplateModel(QStandardItemModel):
ORIENTATIONS = { Qt.Horizontal : u"Horizontal", Qt.Vertical : u"Vertical" }
def __init__(self, parent=None):
self.header = ["Layer name", "Orientation"]
QStandardItemModel.__init__(self, 0, len(self.header), parent)
def append(self, layer):
rowdata = []
item = QStandardItem( unicode(layer.name()) )
item.setFlags( item.flags() & ~Qt.ItemIsEditable )
rowdata.append( item )
item = QStandardItem( TemplateModel.ORIENTATIONS[Qt.Horizontal] )
item.setFlags( item.flags() | Qt.ItemIsEditable )
rowdata.append( item )
self.appendRow( rowdata )
row = self.rowCount()-1
self.setData(self.index(row, 0), layer.id(), Qt.UserRole)
self.setData(self.index(row, 1), Qt.Horizontal, Qt.UserRole)
def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.header[section]
return None
def getObject(self, row):
lid = self.data(self.index(row, 0), Qt.UserRole)
orientation = self.data(self.index(row, 1), Qt.UserRole)
return (lid, orientation)
def getObjectIter(self):
for row in range(self.rowCount()):
yield self.getObject(row)