-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathficha_urbanistica.py
609 lines (478 loc) · 22.8 KB
/
ficha_urbanistica.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
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
# -*- coding: utf-8 -*-
"""Main file of the project ficha_urbanistica. This contains the main class as well as all the important work."""
import codecs
import configparser
import errno
import io
import os
import psycopg2
import subprocess
import sys
import sip
from PyQt5 import QtCore
from PyQt5.QtCore import QObject, QSettings, Qt, QUrl, pyqtSignal
from qgis.PyQt.QtWidgets import QAction, QApplication, QDialog, QFileDialog
from qgis.core import QgsExpressionContextUtils, QgsFeature, QgsGeometry, QgsMessageLog, QgsProject, QgsLayoutExporter
from qgis.core import QgsRectangle, QgsLayoutItemMap, QgsLayoutMultiFrame, QgsLayoutFrame, QgsLayoutItemLegend
from qgis.gui import QgsMapTool, QgsMessageBar
from PyQt5.QtGui import QCursor, QIcon, QPainter, QPixmap
from PyQt5.QtPrintSupport import QPrinter, QPrintDialog
from .const import Const
from .ui.form import Ui_Form
from .ui.docs_view import Ui_DocsView
class FichaUrbanistica:
"""Main class of the project ficha_urbanistica"""
def __init__(self, iface):
"""Contructor"""
# Saving iface to be reachable from the other functions
self.iface = iface
self.plugin_dir = os.path.dirname(__file__)
self.pluginName = os.path.basename(self.plugin_dir)
self.settings = QSettings("PSIG", "ficha_urbanistica")
# Find and safe the plugin's icon
filename = os.path.abspath(os.path.join(self.plugin_dir, 'icon.png'))
self.icon = QIcon(str(filename))
self.style_doc_path = os.path.join(self.plugin_dir, 'Styles', 'selected_parcel.qml')
self.action = None
self.dialog = None
self.projectChange()
def projectChange(self):
# Check if there is an actual project
if not QgsProject.instance().title():
return
self.project_folder = QgsProject.instance().homePath()
if not self.project_folder:
self.project_folder = self.plugin_dir
config_file = os.path.join(self.project_folder, 'ficha_urbanistica.conf')
try:
self.config = Config(config_file)
except IOError:
self.error(u"No s'ha trobat el fitxer de configuració del plugin.")
return
self.reports_folder = os.path.join(self.project_folder, 'informes')
try:
os.makedirs(self.reports_folder)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# Save and make, if they don't exist, the docs folders.
self.sector_folder = os.path.join(self.config.docs_folder, 'sectors')
self.classi_folder = os.path.join(self.config.docs_folder, 'classificacio')
self.ord_folder = os.path.join(self.config.docs_folder, 'ordenacions')
# Disconnect the server
self.cursor = None
self.conn = None
# Get the credentials
service_uri = getServiceUri(self.config.service)
if not service_uri:
self.error(u"Hi ha algun error a la configuració del servei de la base de dades.")
return
# Connecting to the database
try:
self.conn = psycopg2.connect(service_uri)
self.cursor = self.conn.cursor()
except psycopg2.DatabaseError:
self.error(u'Error al connectar amb la base de dades.')
def initGui(self):
"""Called when the gui must be generated."""
self.tool = FichaUrbanisticaTool(self.iface.mapCanvas(), self)
# Add menu and toolbar entries (basically allows to activate it)
self.action = QAction(self.icon, u"Fitxa urbanística", self.iface.mainWindow())
self.action.setCheckable(True)
self.action.triggered.connect(self.activateTool)
self.iface.addToolBarIcon(self.action)
self.iface.addPluginToMenu(qu("Ficha urbanística"), self.action)
self.iface.mapCanvas().mapToolSet.connect(self.deactivateTool)
def activateTool(self):
"""Called when the plugin icon is toggled on"""
self.iface.mapCanvas().setMapTool(self.tool)
self.action.setChecked(True)
def deactivateTool(self):
"""Called when the plugin icon is toggled off"""
self.action.setChecked(False)
def unload(self):
"""Called when the plugin is being unloaded."""
self.iface.removePluginMenu(qu("Ficha urbanística"), self.action)
self.iface.removeToolBarIcon(self.action)
def run(self):
"""Called when the plugin's icon is pressed."""
if not hasattr(self, 'config'):
self.projectChange()
# check if projectChange was successful
if not hasattr(self, 'config'):
return
# Get the active layer (where the selected form is).
layer = self.iface.activeLayer()
if layer is None:
return
# single feature
features = layer.selectedFeatures()
if len(features) < 1:
return
elif len(features) > 1:
layer.selectByIds([features[0].id()])
feature = features[0]
id_index = feature.fieldNameIndex(self.config.plot_id)
if id_index < 0:
return
# Query the necesary information
# self.cursor.fetchall(); # ignore any residual information (should never do anything)
self.cursor.execute(Const.MAIN_QUERY, [int(feature[id_index])])
info = self.cursor.fetchone()
# Make dialog and set its atributes
if self.dialog:
self.dialog.close()
self.dialog = self.initDialog(Ui_Form)
self.dialog.setFixedSize(self.dialog.size())
# Static links
self.dialog.ui.lblCondGenerals.setText(Const.LINK_COND.format(self.config.docs_folder))
self.dialog.ui.lblCondGenerals.linkActivated.connect(self.webDialog)
self.dialog.ui.lblDotacioAparc.setText(Const.LINK_DOT.format(self.config.docs_folder))
self.dialog.ui.lblDotacioAparc.linkActivated.connect(self.webDialog)
self.dialog.ui.lblRegulacioAparc.setText(Const.LINK_REG.format(self.config.docs_folder))
self.dialog.ui.lblRegulacioAparc.linkActivated.connect(self.webDialog)
self.dialog.ui.lblParamFinca.setText(Const.LINK_FINCA.format(self.config.docs_folder))
self.dialog.ui.lblParamFinca.linkActivated.connect(self.webDialog)
self.dialog.ui.lblParamEdificacio.setText(Const.LINK_EDIF.format(self.config.docs_folder))
self.dialog.ui.lblParamEdificacio.linkActivated.connect(self.webDialog)
# Show data
self.dialog.ui.refcat.setText(u'{}'.format(info[Const.REFCAT]))
self.dialog.ui.area.setText((u'{}'.format(round(info[Const.AREA], 1))).rstrip('0').rstrip('.'))
self.dialog.ui.txtAdreca.setText(u'{}'.format(info[Const.ADRECA]))
if info[Const.CODI_SECTOR] is not None: # It may not be part of any sector
self.dialog.ui.txtSector.setText(u'{} - {}'.format(info[Const.CODI_SECTOR], info[Const.DESCR_SECTOR]))
self.dialog.ui.lblSector.setText(self.sectorLink('{}'.format(info[Const.CODI_SECTOR])))
self.dialog.ui.lblSector.linkActivated.connect(self.webDialog)
else:
self.dialog.ui.lblSector.setHidden(True)
self.dialog.ui.txtClass.setText(u'{} - {}'.format(info[Const.CODI_CLASSI], info[Const.DESCR_CLASSI]))
self.dialog.ui.lblClass.setText(self.classiLink('{}'.format(info[Const.CODI_CLASSI])))
codes = info[Const.CODI_ZONES]
percents = info[Const.PERCENT_ZONES]
general_codes = info[Const.CODI_GENERAL_ZONES]
for i in range(0, 4):
txtClau = getattr(self.dialog.ui, 'txtClau_{}'.format(i + 1))
txtPer = getattr(self.dialog.ui, 'txtPer_{}'.format(i + 1))
lblOrd = getattr(self.dialog.ui, 'lblOrd_{}'.format(i + 1))
try:
txtClau.setText(u'{}'.format(codes[i]))
except IndexError:
txtClau.setHidden(True)
try:
txtPer.setText(u'{:02.2f}'.format(percents[i]))
except IndexError:
txtPer.setHidden(True)
try:
lblOrd.setText(u'{}'.format(self.ordLink(general_codes[i])))
lblOrd.linkActivated.connect(self.webDialog)
except IndexError:
lblOrd.setHidden(True)
# PDF generation functions
def makeShowUbicacioPdf():
# Make temporary layer
vl = self.iface.addVectorLayer("Polygon?crs=epsg:25831&field=id:integer&index=yes", "temp_print_polygon", "memory")
vl.loadNamedStyle(self.style_doc_path)
vl.setName(u"Parcel·la seleccionada")
pr = vl.dataProvider()
fet = QgsFeature()
fet.setGeometry(QgsGeometry(feature.geometry())) # copy the geometry
pr.addFeatures([fet])
vl.updateExtents()
moveLayer(vl, 0)
def refreshed():
# Disconnect signal
self.iface.mapCanvas().mapCanvasRefreshed.disconnect(refreshed)
composition = None
for item in QgsProject.instance().layoutManager().printLayouts():
if item.name() == Const.PDF_UBICACIO:
composition = item
break
if composition is None:
return
# Set values
QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),'refcat', info[Const.REFCAT])
QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),'area', '{:.0f}'.format(info[Const.AREA]))
QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),'adreca', info[Const.ADRECA])
# Set main map to the propper position
#main_map = composition.itemById('Mapa principal')
#main_map = composition.referenceMap()
main_map=layout_item(composition,'Mapa principal',QgsLayoutItemMap)
centerMap(main_map, feature)
# Add temporal layer to composition
legend = layout_item(composition,'Llegenda',QgsLayoutItemLegend)
legend_root = legend.model().rootGroup()
legend_root.insertLayer(0, vl)
# Make PDF
filename =os.path.join(self.reports_folder, '{}_ubicacio.pdf'.format(info[Const.REFCAT]))
exporter = QgsLayoutExporter(composition)
exporter.exportToPdf(filename,QgsLayoutExporter.PdfExportSettings())
openFile(filename)
# Delete temporary layer
legend_root.removeLayer(vl)
QgsProject.instance().removeMapLayers([vl.id()])
# Repaint again
self.iface.mapCanvas().refresh()
self.iface.mapCanvas().mapCanvasRefreshed.connect(refreshed)
self.iface.mapCanvas().refresh()
def makeShowZonesPdf():
self.cursor.execute(Const.ZONES_QUERY, [int(feature[id_index])])
rows = (row for row in self.cursor.fetchall() if row[Const.ZONES_COLUMNS.index('per_int')] >= 3)
composition = None
for item in QgsProject.instance().layoutManager().printLayouts():
if item.name() == Const.PDF_ZONES:
composition = item
break
if composition is None:
return
# Set values
for data in rows:
print (data)
for i, column in enumerate(Const.ZONES_COLUMNS):
QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),column, data[i])
if info[Const.CODI_SECTOR] is not None:
QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),'sec_descripcio', u'{} - {}'.format(info[Const.CODI_SECTOR], info[Const.DESCR_SECTOR]))
else:
QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),'sec_descripcio', None)
QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),'cla_descripcio', u'{} - {}'.format(info[Const.CODI_CLASSI], info[Const.DESCR_CLASSI]))
composition.refresh()
filename =os.path.join(self.reports_folder, '{}_zones.pdf'.format(info[Const.REFCAT]))
exporter = QgsLayoutExporter(composition)
exporter.exportToPdf(filename,QgsLayoutExporter.PdfExportSettings())
openFile(filename)
def destroyDialog():
self.dialog = None
# Connect the click signal to the functions
self.dialog.ui.lblClass.linkActivated.connect(self.webDialog)
self.dialog.ui.btnParcelaPdf.clicked.connect(makeShowUbicacioPdf)
self.dialog.ui.btnClauPdf_1.clicked.connect(makeShowZonesPdf)
self.dialog.destroyed.connect(destroyDialog)
# SHow the dialog (execute it)
self.dialog.exec_()
def webDialog(self, url):
QgsMessageLog.logMessage("Opened url: " + url)
dialog = self.initDialog(Ui_DocsView, Qt.WindowSystemMenuHint | Qt.WindowTitleHint | Qt.WindowMaximizeButtonHint)
dialog.ui.webView.setUrl(QUrl(url))
# TODO export & print
def printBtn():
printer = askPrinter()
if printer is not None:
# printer.setPageMargins(left, top, right, bottom, QPrinter.Millimeter)
dialog.ui.webView.print_(printer)
def exportPDF():
printer = self.getPDFPrinter(
os.path.splitext(os.path.basename(url))[0] # Get name without extension
)
if printer is not None:
# printer.setPageMargins(left, top, right, bottom, QPrinter.Millimeter)
dialog.ui.webView.print_(printer)
dialog.ui.imprimirBtn.clicked.connect(printBtn)
dialog.ui.pdfBtn.clicked.connect(exportPDF)
dialog.exec_()
def initDialog(self, Class, flags=Qt.WindowSystemMenuHint | Qt.WindowTitleHint):
"""Initializes a Dialog with the usual parameters of this plugin."""
# This function makes the code more pretty
dialog = QDialog(None, flags)
dialog.ui = Class()
dialog.ui.setupUi(dialog)
dialog.setAttribute(Qt.WA_DeleteOnClose)
dialog.setWindowIcon(self.icon)
dialog.setWindowModality(Qt.WindowModal)
return dialog
def getPDFPrinter(self, name):
printer = QPrinter(QPrinter.HighResolution)
path = QFileDialog.getSaveFileName(
None,
None,
os.path.join(
self.settings.value("save path", os.path.expanduser("~")), # default folder
name + ".pdf" # default filename
),
"PDF (*.pdf)"
)
if path[0] is not None and path != "":
self.settings.setValue("save path", os.path.dirname(path[0]))
printer.setOutputFileName(path[0])
return printer
else:
return None
def sectorLink(self, id):
filename = '{:s}.htm'.format(id)
return Const.LINK_NORMATIVA.format(os.path.join(self.sector_folder, filename))
def classiLink(self, id):
filename = '{:s}.htm'.format(id)
return Const.LINK_NORMATIVA.format(os.path.join(self.classi_folder, filename))
def ordLink(self, code):
filename = '{:s}.htm'.format(code)
filepath = os.path.join(self.ord_folder, filename)
if os.path.isfile(filepath):
return Const.LINK_ORDENACIO.format(filepath, code)
else:
return code
def error(self, msg):
# The QGis documentation recommends using the more user-friendly QGIS Message Bar
# instead of modal message boxes to show information to the user
self.iface.messageBar().pushCritical("Error", msg)
# messageBox = QMessageBox(QMessageBox.Critical, tr("Error"), msg)
# messageBox.setWindowIcon(self.icon)
# messageBox.exec_()
class Config:
"""Class that loads and shows the configuration"""
def __init__(self, file):
config = configparser.RawConfigParser()
try:
config.readfp(codecs.open(file, 'r', 'utf8'))
except UnicodeDecodeError: #unicode error
config.readfp(codecs.open(file, 'r', 'cp1252'))
for service in config.sections():
if config.has_option(service, 'docs_folder'):
docs = config.get(service, 'docs_folder')
if os.path.isabs(docs):
self.docs_folder = docs
else:
self.docs_folder = os.path.join(os.path.dirname(file), docs)
else:
self.docs_folder = os.path.join(os.path.dirname(__file__), 'html')
if config.has_option(service, 'service'):
self.service = config.get(service, 'service')
if config.has_option(service, 'id_name'):
self.plot_id = config.get(service, 'id_name')
else:
self.plot_id = 'id'
if config.has_option(service, 'layer_name'):
self.layer_name = config.get(service, 'layer_name')
else:
self.layer_name = None
class FichaUrbanisticaTool(QgsMapTool):
def __init__(self, canvas, plugin):
super(QgsMapTool, self).__init__(canvas)
self.canvas = canvas
self.plugin = plugin
self.setCursor(QCursor(QPixmap(os.path.join(plugin.plugin_dir, 'cursor.png')), 1, 1))
def canvasReleaseEvent(self, e):
# Activate config layer
if self.plugin.config.layer_name:
registry = QgsProject.instance()
layer = registry.mapLayersByName(self.plugin.config.layer_name)[0]
self.plugin.iface.setActiveLayer(layer)
layer = self.canvas.currentLayer()
if layer is None:
return
point = e.mapPoint()
radius = self.canvas.mapUnitsPerPixel()
rect = QgsRectangle(point.x(), point.y(), point.x() + radius, point.y() + radius)
layer.selectByRect(rect)
self.plugin.run()
# Utilities
def openFile(path):
"""Opens a file with the default application."""
# Multiple OS support
if sys.platform.startswith('darwin'):
subprocess.Popen(['open', path])
elif os.name == 'nt':
os.startfile(path)
elif os.name == 'posix':
subprocess.Popen(['xdg-open', path])
def get_pgservices_conf(path):
r = {}
if not path:
return r
try:
with open(path) as file:
config_sample = file.read()
except IOError:
return r
config = configparser.RawConfigParser()
config.readfp(io.StringIO(config_sample))
for service in config.sections():
if (config.has_option(service, 'host') and
config.has_option(service, 'dbname') and
config.has_option(service, 'user') and
config.has_option(service, 'password')):
if config.has_option(service, 'port'):
port = config.get(service, 'port')
else:
port = '5432'
r[service] = u'host={} port={} dbname={} user={} password={}'.format(
config.get(service, 'host'),
port,
config.get(service, 'dbname'),
config.get(service, 'user'),
config.get(service, 'password')
)
return r
def getServiceUri(config_service):
this_folder = os.path.dirname(__file__)
# Look at the pg_config files
pg_services = get_pgservices_conf(os.path.join(this_folder, 'config', 'pg_service.conf'))
pg_services.update(get_pgservices_conf(os.path.expanduser('~/.pg_service.conf')))
pg_services.update(get_pgservices_conf(os.path.join(os.environ.get('PGSYSCONFDIR') or '', 'pg_service.conf')))
pg_services.update(get_pgservices_conf(os.environ.get('PGserviceFILE')))
if config_service:
return pg_services.get(config_service)
elif len(pg_services) == 1:
return pg_services.values()[0]
def centerMap(map, feature):
newExtent = centerRect(map.extent(), feature.geometry().boundingBox().center())
map.setExtent(newExtent)
def centerRect(rect, point):
hw = rect.width() / 2
hh = rect.height() / 2
xMin = point.x() - hw
xMax = point.x() + hw
yMin = point.y() - hh
yMax = point.y() + hh
return type(rect)(xMin, yMin, xMax, yMax)
def moveLayer(layer, pos):
root = QgsProject.instance().layerTreeRoot()
node = root.findLayer(layer.id())
clone = node.clone()
parent = node.parent()
parent.insertChildNode(pos, clone)
parent.removeChildNode(node)
def askPrinter():
printer = QPrinter()
select = QPrintDialog(printer)
if select.exec_():
return printer
else:
return None
def layout_item(layout, item_id, item_class):
"""Fetch a specific item according to its type in a layout.
There's some sip casting conversion issues with QgsLayout::itemById.
Don't use it, and use this function instead.
See https://github.com/inasafe/inasafe/issues/4271
:param layout: The layout to look in.
:type layout: QgsLayout
:param item_id: The ID of the item to look for.
:type item_id: basestring
:param item_class: The expected class name.
:type item_class: cls
:return: The layout item, inherited class of QgsLayoutItem.
"""
item = layout.itemById(item_id)
if item is None:
# no match!
return item
if issubclass(item_class, QgsLayoutMultiFrame):
# finding a multiframe by frame id
frame = sip.cast(item, QgsLayoutFrame)
multi_frame = frame.multiFrame()
return sip.cast(multi_frame, item_class)
else:
# force sip to correctly cast item to required type
return sip.cast(item, item_class)
# Unicode QString generator function
try:
qu = QtCore.QString.fromUtf8
except AttributeError:
def qu(s):
return s
# Qt translate function
try:
def _translate(context, text, disambig):
return QApplication.translate(context, text, disambig, QApplication.UnicodeUTF8)
except AttributeError:
def _translate(context, text, disambig):
return QApplication.translate(context, text, disambig)
def tr(text):
return _translate("ficha_urbanistica", text, None)