Compare commits

...
8 Commits
Author SHA1 Message Date
tlaveille 7df08ae02a flake8 postgis 2025-07-29 13:35:11 +02:00
tlaveille 133e785568 flake8 automap 2025-07-29 10:53:30 +02:00
tlaveille 9b7ab9ab15 3.5 flux 2025-07-29 10:24:51 +02:00
tlaveille c02da75f0b bug fix pg no raster_columnes views 2025-07-29 10:17:45 +02:00
tlaveille d4b181ff61 flake8 2025-07-28 16:53:26 +02:00
tlaveille 7a3814a429 flake8 2025-07-28 16:45:44 +02:00
tlaveille 1cd816c706 flake8 2025-07-28 16:23:25 +02:00
tlaveille 94cac31fbb Vue du type vecteur ou raster dans SIG 2025-07-23 16:15:28 +02:00
20 changed files with 1070 additions and 1345 deletions
+6 -40
View File
@@ -4,9 +4,9 @@ __email__ = "info@3liz.org"
from qgis.core import QgsApplication from qgis.core import QgsApplication
from qgis.PyQt.QtCore import QCoreApplication, Qt, QTranslator, QUrl from qgis.PyQt.QtCore import Qt, QUrl
from qgis.PyQt.QtGui import QDesktopServices, QIcon from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox from qgis.PyQt.QtWidgets import QAction
from qgis.utils import iface from qgis.utils import iface
import qgis import qgis
@@ -24,8 +24,10 @@ from pg_metadata.processing.provider import PgMetadataProvider
from pg_metadata.qgis_plugin_tools.tools.custom_logging import setup_logger from pg_metadata.qgis_plugin_tools.tools.custom_logging import setup_logger
''' '''
import os import os
from qgis.PyQt.QtCore import QSettings
from .about_form import AboutDialog
from .tools.resources import ( from .tools.resources import (
plugin_path, # plugin_path,
resources_path, resources_path,
pyperclip, pyperclip,
maj_verif, maj_verif,
@@ -34,10 +36,6 @@ pyperclip()
from .canvas_editor import AutoMap_Editor from .canvas_editor import AutoMap_Editor
from .style_invoke import AutoMap_Style from .style_invoke import AutoMap_Style
from .about_form import AboutDialog
from qgis.PyQt.QtCore import *
class PgAutoMap: class PgAutoMap:
@@ -90,45 +88,13 @@ class PgAutoMap:
if os.environ['USERNAME'] == 'tlaveille' or os.environ['USERNAME'] == 'lpoulin' or os.environ['USERNAME'] == 'rclement': if os.environ['USERNAME'] == 'tlaveille' or os.environ['USERNAME'] == 'lpoulin' or os.environ['USERNAME'] == 'rclement':
iface.addDockWidget(Qt.DockWidgetArea(0x1), self.style_dock) iface.addDockWidget(Qt.DockWidgetArea(0x1), self.style_dock)
'''
if not self.locator_filter:
self.locator_filter = LocatorFilter(iface)
iface.registerLocatorFilter(self.locator_filter)
@staticmethod
def check_invalid_connection_names():
""" Check for invalid connection names in the QgsSettings. """
valid, invalid = validate_connections_names()
n_invalid = len(invalid)
if n_invalid == 0:
return
invalid_text = ', '.join(invalid)
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setWindowTitle(tr('PgMetadata: Database connection(s) not available'))
msg.setText(tr(
f'{n_invalid} connection(s) listed in PgMetadata’s settings are invalid or '
f'no longer available: {invalid_text}'))
msg.setInformativeText(tr(
'Do you want to remove these connection(s) from the PgMetadata settings? '
'(You can also do this later with the “Set Connections” tool.)'))
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
clicked = msg.exec()
if clicked == QMessageBox.Yes:
iface.messageBar().pushSuccess('PgMetadata', tr(f'{n_invalid} invalid connection(s) removed.'))
store_connections(valid)
if clicked == QMessageBox.No:
iface.messageBar().pushInfo('PgMetadata', tr(f'Keeping {n_invalid} invalid connections.'))
'''
def open_about_dialog(self): def open_about_dialog(self):
""" """
About dialog About dialog
""" """
dialog = AboutDialog(iface) dialog = AboutDialog(iface)
dialog.exec() dialog.exec()
def open_help(): def open_help():
""" Open the online help. """ """ Open the online help. """
QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/')) QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/'))
+1 -1
View File
@@ -3,7 +3,7 @@ import os.path
from pathlib import Path from pathlib import Path
from qgis.PyQt import uic from qgis.PyQt import uic
from qgis.PyQt.QtGui import QPixmap # from qgis.PyQt.QtGui import QPixmap
from qgis.PyQt.QtWidgets import QDialog from qgis.PyQt.QtWidgets import QDialog
from .tools.resources import devlog from .tools.resources import devlog
+45 -78
View File
@@ -1,80 +1,41 @@
import logging import logging
import os import os
from collections import namedtuple
from enum import Enum
from functools import partial
from pathlib import Path
from xml.dom.minidom import parseString
from qgis.gui import *
import qgis
from importlib import import_module
from qgis.core import ( from qgis.core import (
NULL,
QgsApplication,
QgsScaleBarSettings, QgsScaleBarSettings,
QgsDataSourceUri,
QgsProject, QgsProject,
QgsProviderConnectionException,
QgsProviderRegistry,
QgsRasterLayer, QgsRasterLayer,
QgsSettings, QgsSettings,
QgsVectorLayer, QgsVectorLayer,
QgsGeometry,
QgsPrintLayout, QgsPrintLayout,
QgsReadWriteContext, QgsReadWriteContext,
QgsLayoutItemMap, QgsLayoutItemMap,
QgsLayoutItemPage, QgsLayoutItemPage,
QgsLayoutSize,
QgsUnitTypes, QgsUnitTypes,
QgsLayoutPoint,
QgsLayoutItemLabel, QgsLayoutItemLabel,
QgsLayoutItemPicture, QgsLayoutItemPicture,
QgsLayoutItemLegend, QgsLayoutItemLegend,
QgsLegendStyle, QgsLegendStyle,
QgsLayoutItemScaleBar, QgsLayoutItemScaleBar,
QgsLayerTreeGroup, QgsLayerTreeGroup,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsLayerTree,
QgsLayoutTableColumn,
QgsRectangle, QgsRectangle,
QgsLayoutItemMapOverviewStack,
) )
from qgis.PyQt.QtCore import QLocale, QUrl, QDateTime, Qt from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QDesktopServices, QIcon, QColor, QFont, QMovie from qgis.PyQt.QtGui import QColor, QFont
from qgis.PyQt.QtPrintSupport import QPrinter
#from qgis.PyQt.QtWebKitWidgets import QWebPage
from qgis.PyQt.QtWidgets import ( from qgis.PyQt.QtWidgets import (
QDialog, QDialog,
QAction,
QMessageBox, QMessageBox,
QPushButton, QPushButton,
QDockWidget,
QFileDialog, QFileDialog,
QInputDialog,
QMenu,
QToolButton,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
) )
from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtCore import QSettings
from qgis.PyQt import QtGui from qgis.PyQt import QtGui
from qgis.PyQt import QtWidgets
from qgis.PyQt.QtXml import QDomDocument from qgis.PyQt.QtXml import QDomDocument
from qgis.utils import iface from qgis.utils import iface
import glob import glob
from .tools.resources import ( from .tools.resources import (
load_ui, load_ui,
resources_path, resources_path,
send_issues,
) )
from .issues import CenRa_Issues
from datetime import date from datetime import date
EDITOR_CLASS = load_ui('CenRa_AutoMap_base.ui') EDITOR_CLASS = load_ui('CenRa_AutoMap_base.ui')
@@ -109,8 +70,8 @@ data_source = [
A4_size = {'Portrait': {'RIGHT': 210, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 297}, 'Landscape': {'RIGHT': 297, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 210}} A4_size = {'Portrait': {'RIGHT': 210, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 297}, 'Landscape': {'RIGHT': 297, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 210}}
A3_size = {'Portrait': {'RIGHT': 298, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 420}, 'Landscape': {'RIGHT': 420, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 298}} A3_size = {'Portrait': {'RIGHT': 298, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 420}, 'Landscape': {'RIGHT': 420, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 298}}
class AutoMap_Editor(QDialog, EDITOR_CLASS):
class AutoMap_Editor(QDialog, EDITOR_CLASS):
def __init__(self, parent=None): def __init__(self, parent=None):
_ = parent _ = parent
super().__init__() super().__init__()
@@ -140,13 +101,12 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.CustomeLogo.clicked.connect(self.deflogoteck) self.CustomeLogo.clicked.connect(self.deflogoteck)
self.verticalScrollBar.valueChanged.connect(self.moveFrame) self.verticalScrollBar.valueChanged.connect(self.moveFrame)
## On ajoute le nom des templates à la liste déroulante de l'onglet "mises en page" : # On ajoute le nom des templates à la liste déroulante de l'onglet "mises en page" :
mises_en_page = [] mises_en_page = []
for filename in glob.glob(resources_path("mises_en_pages", "*.py")): for filename in glob.glob(resources_path("mises_en_pages", "*.py")):
mises_en_page.append(filename) mises_en_page.append(filename)
for i, filename in enumerate(mises_en_page): for i, filename in enumerate(mises_en_page):
nom_fichier = os.path.basename(filename) nom_fichier = os.path.basename(filename)
self.comboBox.addItem(nom_fichier) self.comboBox.addItem(nom_fichier)
@@ -204,17 +164,19 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
else: else:
vsb = self.verticalScrollBar.value() - 20 vsb = self.verticalScrollBar.value() - 20
self.verticalScrollBar.setValue(vsb) self.verticalScrollBar.setValue(vsb)
def moveFrame(self): def moveFrame(self):
self.frame.move(self.frame.x(), self.verticalScrollBar.value()) self.frame.move(self.frame.x(), self.verticalScrollBar.value())
def update_logo_library(self): def update_logo_library(self):
self.mComboBox_4.clear() self.mComboBox_4.clear()
logo_library = [] logo_library = []
custome_bibliotech = glob.glob(self.s.value("automap/logoteck", 1, type=str) + '*.*') custome_bibliotech = glob.glob(self.s.value("automap/logoteck", 1, type=str) + '*.*')
for l,logo_x in enumerate(custome_bibliotech): for number, logo_x in enumerate(custome_bibliotech):
logo_library.append(' ' + os.path.basename(logo_x)) logo_library.append(' ' + os.path.basename(logo_x))
bibliotech = glob.glob(resources_path("logo_library", "*.png")) bibliotech = glob.glob(resources_path("logo_library", "*.png"))
for l,logo_x in enumerate(bibliotech): for number, logo_x in enumerate(bibliotech):
logo_library.append(os.path.basename(logo_x)) logo_library.append(os.path.basename(logo_x))
self.mComboBox_4.addItems(sorted(logo_library)) self.mComboBox_4.addItems(sorted(logo_library))
@@ -237,16 +199,20 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
try: try:
layout_subtitle = project_subtitle.layoutManager().layoutByName(self.comboBox_7.currentText()) layout_subtitle = project_subtitle.layoutManager().layoutByName(self.comboBox_7.currentText())
self.lineEdit_3.setText(layout_subtitle.itemById("SubTitle").text()) self.lineEdit_3.setText(layout_subtitle.itemById("SubTitle").text())
except: except NameError:
print("") print("")
def load_ortho(self): def load_ortho(self):
global myGroup, last_group global myGroup, last_group
runing = False runing = False
try: myGroup try:
except NameError: runing = True myGroup
try: last_group except NameError:
except NameError: last_group = '' runing = True
try:
last_group
except NameError:
last_group = ''
if runing or (last_group != '' and last_group != 'ortho'): if runing or (last_group != '' and last_group != 'ortho'):
layername = False layername = False
layerAll = QgsProject.instance().layerTreeRoot().children() layerAll = QgsProject.instance().layerTreeRoot().children()
@@ -287,10 +253,14 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
def load_osm(self): def load_osm(self):
global myGroup, last_group global myGroup, last_group
runing = False runing = False
try: myGroup try:
except NameError: runing = True myGroup
try: last_group except NameError:
except NameError: last_group = '' runing = True
try:
last_group
except NameError:
last_group = ''
if runing or (last_group != '' and last_group != 'osm'): if runing or (last_group != '' and last_group != 'osm'):
layername = False layername = False
layerAll = QgsProject.instance().layerTreeRoot().children() layerAll = QgsProject.instance().layerTreeRoot().children()
@@ -365,6 +335,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.show_map() self.show_map()
else: else:
self.hide_map() self.hide_map()
def show_map(self): def show_map(self):
self.groupBox_3.setEnabled(True) self.groupBox_3.setEnabled(True)
self.groupBox_3.show() self.groupBox_3.show()
@@ -378,6 +349,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.show_titre() self.show_titre()
else: else:
self.hide_titre() self.hide_titre()
def show_titre(self): def show_titre(self):
self.lineEdit_2.setEnabled(False) self.lineEdit_2.setEnabled(False)
self.lineEdit_2.hide() self.lineEdit_2.hide()
@@ -395,6 +367,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.show_source() self.show_source()
else: else:
self.hide_source() self.hide_source()
def show_source(self): def show_source(self):
self.lineEdit_4.setEnabled(False) self.lineEdit_4.setEnabled(False)
self.lineEdit_4.hide() self.lineEdit_4.hide()
@@ -441,13 +414,13 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
layout_name = self.comboBox_7.currentText() layout_name = self.comboBox_7.currentText()
else: else:
layout_name = self.lineEdit_2.text() layout_name = self.lineEdit_2.text()
layouts_list = self.manager.printLayouts() # layouts_list = self.manager.printLayouts()
for filename in glob.glob(resources_path("mises_en_pages", "*.qpt")): for filename in glob.glob(resources_path("mises_en_pages", "*.qpt")):
with open(os.path.join(os.getcwd(), filename), 'r') as f: with open(os.path.join(os.getcwd(), filename), 'r') as f:
self.layout = QgsPrintLayout(project) self.layout = QgsPrintLayout(project)
self.layout.initializeDefaults() self.layout.initializeDefaults()
myAtlas=self.layout.atlas() # myAtlas = self.layout.atlas()
template_content = f.read() template_content = f.read()
doc = QDomDocument() doc = QDomDocument()
doc.setContent(template_content) doc.setContent(template_content)
@@ -455,7 +428,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
try: try:
cutLayout = layout_name.index("") cutLayout = layout_name.index("")
except: except ValueError:
cutLayout = 0 cutLayout = 0
if cutLayout >= 1: if cutLayout >= 1:
@@ -473,11 +446,12 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
logo_div = A3_size['Portrait']['RIGHT'] logo_div = A3_size['Portrait']['RIGHT']
if self.radioButton_5.isChecked() and self.radioButton_8.isChecked(): if self.radioButton_5.isChecked() and self.radioButton_8.isChecked():
logo_div = A3_size['Portrait']['BOTTOM'] logo_div = A3_size['Portrait']['BOTTOM']
if True:#os.path.basename(filename) == "1. Modèle carto standard (consolidé).qpt": # os.path.basename(filename) == "1. Modèle carto standard (consolidé).qpt":
if True:
self.actualisation_mise_en_page() self.actualisation_mise_en_page()
## Add map to layout # Add map to layout
self.map_modele_test = QgsLayoutItemMap(self.layout) self.map_modele_test = QgsLayoutItemMap(self.layout)
# Charger une carte vide # Charger une carte vide
self.map_modele_test.setRect(20, 20, 20, 20) self.map_modele_test.setRect(20, 20, 20, 20)
@@ -525,7 +499,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.layout.addLayoutItem(self.map_modele_test) self.layout.addLayoutItem(self.map_modele_test)
self.map_modele_test.setId("carte_principale") self.map_modele_test.setId("carte_principale")
## Ajout d'un titre à la mise en page # Ajout d'un titre à la mise en page
title = QgsLayoutItemLabel(self.layout) title = QgsLayoutItemLabel(self.layout)
self.layout.addLayoutItem(title) self.layout.addLayoutItem(title)
titre = titre_layout_name titre = titre_layout_name
@@ -542,8 +516,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
title.setHAlign(Qt.AlignmentFlag(0x0004)) title.setHAlign(Qt.AlignmentFlag(0x0004))
title.setVAlign(Qt.AlignmentFlag(0x0080)) title.setVAlign(Qt.AlignmentFlag(0x0080))
# Ajout d'un sous titre à la mise en page
## Ajout d'un sous titre à la mise en page
subtitle = QgsLayoutItemLabel(self.layout) subtitle = QgsLayoutItemLabel(self.layout)
self.layout.addLayoutItem(subtitle) self.layout.addLayoutItem(subtitle)
titre = self.lineEdit_3.text() titre = self.lineEdit_3.text()
@@ -561,8 +534,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
subtitle.setHAlign(Qt.AlignmentFlag(0x0004)) subtitle.setHAlign(Qt.AlignmentFlag(0x0004))
subtitle.setVAlign(Qt.AlignmentFlag(0x0080)) subtitle.setVAlign(Qt.AlignmentFlag(0x0080))
# Ajout du logo CEN NA en haut à gauche de la page
## Ajout du logo CEN NA en haut à gauche de la page
logo = QgsLayoutItemPicture(self.layout) logo = QgsLayoutItemPicture(self.layout)
logo.setResizeMode(QgsLayoutItemPicture.Zoom) logo.setResizeMode(QgsLayoutItemPicture.Zoom)
logo.setMode(QgsLayoutItemPicture.FormatRaster) logo.setMode(QgsLayoutItemPicture.FormatRaster)
@@ -573,8 +545,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
logo.setId('logo') logo.setId('logo')
self.layout.addLayoutItem(logo) self.layout.addLayoutItem(logo)
# Ajout de la legende :
## Ajout de la legende :
legend = QgsLayoutItemLegend(self.layout) legend = QgsLayoutItemLegend(self.layout)
legend.setId('legende_model1') legend.setId('legende_model1')
@@ -619,7 +590,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
layertreelayer = root.findLayer(layer.id()) layertreelayer = root.findLayer(layer.id())
# get the parent of the layer tree layer (layer tree root, or group) # get the parent of the layer tree layer (layer tree root, or group)
if layertreelayer != None: if layertreelayer is not None:
parent = layertreelayer.parent() parent = layertreelayer.parent()
# if the parent is a group and has a name, find it and remove the layer # if the parent is a group and has a name, find it and remove the layer
@@ -630,7 +601,6 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
else: else:
root_group.removeLayer(layer) root_group.removeLayer(layer)
legend.setEqualColumnWidth(True) legend.setEqualColumnWidth(True)
legend.setSplitLayer(True) legend.setSplitLayer(True)
legend.setColumnSpace(5) legend.setColumnSpace(5)
@@ -647,7 +617,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
legend.updateLegend() legend.updateLegend()
legend.attemptMove(self.template_parameters['Legande_locals']) legend.attemptMove(self.template_parameters['Legande_locals'])
## Ajout de l'échelle numeric à la mise en page # Ajout de l'échelle numeric à la mise en page
self.scalebarnumeric_qpt = QgsLayoutItemScaleBar(self.layout) self.scalebarnumeric_qpt = QgsLayoutItemScaleBar(self.layout)
self.scalebarnumeric_qpt.setStyle('Numeric') self.scalebarnumeric_qpt.setStyle('Numeric')
self.scalebarnumeric_qpt.setLinkedMap(self.map_modele_test) self.scalebarnumeric_qpt.setLinkedMap(self.map_modele_test)
@@ -667,7 +637,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.layout.addLayoutItem(self.scalebarnumeric_qpt) self.layout.addLayoutItem(self.scalebarnumeric_qpt)
## Ajout de l'échelle à la mise en page # Ajout de l'échelle à la mise en page
self.scalebar_qpt = QgsLayoutItemScaleBar(self.layout) self.scalebar_qpt = QgsLayoutItemScaleBar(self.layout)
self.scalebar_qpt.setStyle('Single Box') self.scalebar_qpt.setStyle('Single Box')
self.scalebar_qpt.setLinkedMap(self.map_modele_test) self.scalebar_qpt.setLinkedMap(self.map_modele_test)
@@ -736,7 +706,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.layout.addLayoutItem(credit_text) self.layout.addLayoutItem(credit_text)
self.layout.addLayoutItem(credit_text2) self.layout.addLayoutItem(credit_text2)
## Ajout du logo credit en bas à droit de la page # Ajout du logo credit en bas à droit de la page
len_item = (len(self.mComboBox_4.checkedItems())) len_item = (len(self.mComboBox_4.checkedItems()))
for logo_run in self.mComboBox_4.checkedItems(): for logo_run in self.mComboBox_4.checkedItems():
logo_credit = QgsLayoutItemPicture(self.layout) logo_credit = QgsLayoutItemPicture(self.layout)
@@ -774,7 +744,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
# if self.radioButton_12.isChecked() != 1: # if self.radioButton_12.isChecked() != 1:
if self.QMBquestion == QMessageBox.StandardButton(0x00004000): if self.QMBquestion == QMessageBox.StandardButton(0x00004000):
project.layoutManager().removeLayout(existing_layout) project.layoutManager().removeLayout(existing_layout)
result = project.layoutManager().addLayout(self.layout) # result = project.layoutManager().addLayout(self.layout)
elif self.QMBquestion != QMessageBox.StandardButton(0x00010000): elif self.QMBquestion != QMessageBox.StandardButton(0x00010000):
LayoutCOUNT = 0 LayoutCOUNT = 0
arrayManager = [] arrayManager = []
@@ -792,8 +762,6 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
else: else:
existing_layout = True existing_layout = True
self.manager.addLayout(self.layout) self.manager.addLayout(self.layout)
if self.radioButton_9.isChecked() == 1: if self.radioButton_9.isChecked() == 1:
self.layout.atlas().setEnabled(True) self.layout.atlas().setEnabled(True)
@@ -811,10 +779,10 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
else: else:
TryMessage = False TryMessage = False
del self.QMBquestion del self.QMBquestion
except: except ValueError:
TryMessage = True TryMessage = True
if TryMessage == True: if TryMessage is True:
iface.openLayoutDesigner(layout_modifie) iface.openLayoutDesigner(layout_modifie)
self.close() self.close()
else: else:
@@ -844,7 +812,6 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
eval("exec('self.template_parameters = '+ values_page_import + '.fletch_canvas(self)')") eval("exec('self.template_parameters = '+ values_page_import + '.fletch_canvas(self)')")
def bar_echelle_auto(self, echelle, bar_echelle): def bar_echelle_auto(self, echelle, bar_echelle):
if True: if True:
if echelle.scale() >= 40000: if echelle.scale() >= 40000:
bar_echelle.setUnits(QgsUnitTypes.DistanceKilometers) bar_echelle.setUnits(QgsUnitTypes.DistanceKilometers)
+18 -13
View File
@@ -1,10 +1,4 @@
import os import os
plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\')+1
NAME = plugin_dir[end_find:]
#print(NAME)
from qgis.gui import * from qgis.gui import *
from qgis.core import ( from qgis.core import (
@@ -35,14 +29,20 @@ from qgis.utils import iface
from .tools.resources import ( from .tools.resources import (
load_ui, load_ui,
resources_path, # resources_path,
send_issues, send_issues,
) )
plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\') + 1
NAME = plugin_dir[end_find:]
# print(NAME)
EDITOR_CLASS = load_ui('CenRa_IssuesSend.ui') EDITOR_CLASS = load_ui('CenRa_IssuesSend.ui')
class CenRa_Issues(QDialog, EDITOR_CLASS):
class CenRa_Issues(QDialog, EDITOR_CLASS):
def __init__(self, parent=None): def __init__(self, parent=None):
_ = parent _ = parent
super().__init__() super().__init__()
@@ -63,11 +63,16 @@ class CenRa_Issues(QDialog, EDITOR_CLASS):
statu_autre = self.check_autre.isChecked() statu_autre = self.check_autre.isChecked()
statu = [] statu = []
if statu_bug == True : statu = statu + [1] if statu_bug is True:
if statu_aide == True : statu = statu + [3] statu = statu + [1]
if statu_question == True : statu = statu + [5] if statu_aide is True:
if statu_amelioration == True : statu = statu + [2] statu = statu + [3]
if statu_autre == True : statu = statu + [6] if statu_question is True:
statu = statu + [5]
if statu_amelioration is True:
statu = statu + [2]
if statu_autre is True:
statu = statu + [6]
if len(statu) >= 1: if len(statu) >= 1:
import qgis import qgis
+5 -11
View File
@@ -4,27 +4,23 @@ __email__ = "info@3liz.org"
from qgis.core import QgsApplication from qgis.core import QgsApplication
from qgis.PyQt.QtCore import QCoreApplication, Qt, QTranslator, QUrl from qgis.PyQt.QtCore import QUrl, QSettings
from qgis.PyQt.QtGui import QDesktopServices, QIcon from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox from qgis.PyQt.QtWidgets import QAction
from qgis.utils import iface from qgis.utils import iface
import qgis import qgis
# include <QSettings> # include <QSettings>
import socket from .about_form import AboutDialog
import os import os
from .tools.resources import ( from .tools.resources import (
plugin_path,
pyperclip, pyperclip,
resources_path, resources_path,
maj_verif, maj_verif,
) )
pyperclip() pyperclip()
from .flux_editor import Flux_Editor
from .about_form import AboutDialog
from qgis.PyQt.QtCore import * from .flux_editor import Flux_Editor
class PgFlux: class PgFlux:
@@ -65,8 +61,6 @@ class PgFlux:
self.help_action.triggered.connect(self.open_help) self.help_action.triggered.connect(self.open_help)
if not self.action_editor: if not self.action_editor:
self.action_editor = Flux_Editor() self.action_editor = Flux_Editor()
self.flux_editor = QAction(icon, 'SigCEN', None) self.flux_editor = QAction(icon, 'SigCEN', None)
self.toolBar.addAction(self.flux_editor) self.toolBar.addAction(self.flux_editor)
self.flux_editor.triggered.connect(self.open_editor) self.flux_editor.triggered.connect(self.open_editor)
@@ -80,6 +74,7 @@ class PgFlux:
""" """
dialog = AboutDialog(iface) dialog = AboutDialog(iface)
dialog.exec() dialog.exec()
def open_help(): def open_help():
""" Open the online help. """ """ Open the online help. """
QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/')) QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/'))
@@ -93,7 +88,6 @@ class PgFlux:
if self.action_editor: if self.action_editor:
iface.removePluginMenu('CenRa_Flux', self.flux_editor) iface.removePluginMenu('CenRa_Flux', self.flux_editor)
if self.provider: if self.provider:
QgsApplication.processingRegistry().removeProvider(self.provider) QgsApplication.processingRegistry().removeProvider(self.provider)
del self.provider del self.provider
+1 -1
View File
@@ -3,7 +3,7 @@ import os.path
from pathlib import Path from pathlib import Path
from qgis.PyQt import uic from qgis.PyQt import uic
from qgis.PyQt.QtGui import QPixmap # from qgis.PyQt.QtGui import QPixmap
from qgis.PyQt.QtWidgets import QDialog from qgis.PyQt.QtWidgets import QDialog
from .tools.resources import devlog from .tools.resources import devlog
+64 -291
View File
@@ -2,59 +2,55 @@
from __future__ import absolute_import from __future__ import absolute_import
# Import the PyQt and QGIS libraries # Import the PyQt and QGIS libraries
from builtins import next # from builtins import next
from builtins import str from builtins import str
from builtins import object # from builtins import object
import qgis
from qgis.PyQt import QtCore from qgis.PyQt import QtCore, QtGui
from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtCore import QSettings
from qgis.PyQt import QtWidgets from qgis.PyQt import QtWidgets
from qgis.PyQt.QtWidgets import QAction, QMenu, QDialog # from qgis.PyQt.QtWidgets import QDialog
from qgis.PyQt.QtGui import QIcon from qgis.PyQt.QtGui import QIcon
try:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtGui
except:
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6 import QtGui
from qgis.core import * # from qgis.PyQt.QtCore import *
from qgis.core import QgsDataSourceUri
# from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsSettings
from qgis.core import QgsDataSourceUri, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsSettings, QgsApplication, QgsVectorLayer, QgsRasterLayer, QgsWkbTypes
from qgis.PyQt.QtWidgets import ( from qgis.PyQt.QtWidgets import (
QDialog, QDialog,
QAction, # QAction,
QDockWidget, # QDockWidget,
QFileDialog, # QFileDialog,
QInputDialog, # QInputDialog,
QMenu, # QMenu,
QToolButton, # QToolButton,
QTableWidget, # QTableWidget,
QTableWidgetItem, QTableWidgetItem,
QMessageBox, QMessageBox,
QVBoxLayout, QVBoxLayout,
) )
from .tools.SQLRequet import * from .tools.SQLRequet import schemaname_list, schemaname_list_ref, schemaname_distinct
from .tools.resources import ( from .tools.resources import (
load_ui, load_ui,
resources_path, resources_path,
send_issues, # send_issues,
) )
try: try:
from .tools.PythonSQL import login_base from .tools.PythonSQL import login_base
except: except NameError:
print('Pas de fichier PythonSQL') print('Pas de fichier PythonSQL')
from .issues import CenRa_Issues
from ast import literal_eval # from .issues import CenRa_Issues
# from ast import literal_eval
from qgis.utils import iface from qgis.utils import iface
import os.path # import os.path
import webbrowser, os # import os
# import webbrowser
import psycopg2 import psycopg2
import psycopg2.extras import psycopg2.extras
import base64 # import base64
global DeBUG global DeBUG
DeBUG = 0 DeBUG = 0
@@ -79,125 +75,17 @@ try:
sigdb = account[5] sigdb = account[5]
refdb = account[6] refdb = account[6]
except: except NameError:
print('Fails to login DB for account') print('Fails to login DB for account')
EDITOR_CLASS = load_ui('CenRa_Flux_base.ui') EDITOR_CLASS = load_ui('CenRa_Flux_base.ui')
html = '''<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
crossorigin=""></script>
<style>
body { padding: 0; margin: 0; }
html, body, #map { height: 100%; }
.leaflet-control-layers-toggle {
background-image: url(https://intranet.cenra-outils.org/Intranet/css/images/layers.png);
}
.legend_parc {
border-radius: 15px;
box-shadow: 2px 2px 3px 0 #6a6a6a;
background-color: #fefafab3;
opacity:0;
}
.legend_parc:hover{
opacity:1;
}
.popup-with-no-events {
pointer-events: none;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="map.js"></script>
</body>
</html>
<script>'''
font = '''var OrthoIGN = L.tileLayer('https://wmts.geopf.fr/wmts?'+
'&LAYER={ignLayer}&STYLE={style}&TILEMATRIXSET=PM'+
'&SERVICE={service}&REQUEST=GetTile&VERSION=1.0.0'+
'&FORMAT={format}&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}',
{
ignLayer: 'ORTHOIMAGERY.ORTHOPHOTOS',
style: 'normal',
service: 'WMTS',
format: 'image/jpeg',
minZoom: 0,
maxZoom: 19,
attribution: '&copy; IGN'
}).addTo(map);
// Plan IGN avec une transparence de 50%
var PlanIGN = L.tileLayer('https://wmts.geopf.fr/wmts?'+
'&LAYER={ignLayer}&STYLE={style}&TILEMATRIXSET=PM'+
'&SERVICE={service}&REQUEST=GetTile&VERSION=1.0.0'+
'&FORMAT={format}&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}',
{
ignLayer: 'GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2',
style: 'normal',
service: 'WMTS',
format: 'image/png',
minZoom: 0,
maxZoom: 19,
attribution: '&copy; IGN'
});
var baseMaps = {
// "BDORTHO2" : bdortho,
// "Openstreetmap": openStreetMap,
// "Opentopomap": openTopoMap,
"BDORTHO" : OrthoIGN,
"PlanIGN": PlanIGN
};
var overlayMaps = {
"Sites": Sites,
//"Parcelle":JSON
};
L.control.layers(baseMaps,overlayMaps).addTo(map);
var scale = L.control.scale({position: 'bottomleft', metric:true, imperial:false});
scale.addTo(map);
var legend = L.control({position: 'bottomleft'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend_parc'),
labels = [];
labels.push('<i style="background:#73004c;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Acquisition')
labels.push('<i style="background:#ff00c5;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Acquis en partie BND')
labels.push('<i style="background:#f0ade1ab;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Acquisition pour partie')
labels.push('<i style="background:#73462e;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Acquisition / Convention')
labels.push('<i style="background:#e69800;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Convention')
labels.push('<i style="background:#ffd37f;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Convention en partie BND')
labels.push('<i style="background:#ffebaf;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Convention pour partie')
labels.push('<i style="background:#c8c8c8;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Autre')
labels.push('<i style="background:#f9ff08;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Projet en cours')
labels.push('<i style="background:#fe0000;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Problème de mise à jour')
labels.push('<i style="background:#000;width:18px;height:18px;float:left;margin-right:8px;opacity: 0.7;"></i> Pas de maitrise')
div.innerHTML = labels.join('<br>');
return div;
};
legend.addTo(map);
</script>'''
targetCrs = QgsCoordinateReferenceSystem('EPSG:4326') targetCrs = QgsCoordinateReferenceSystem('EPSG:4326')
layerCrs = QgsCoordinateReferenceSystem('EPSG:2154') layerCrs = QgsCoordinateReferenceSystem('EPSG:2154')
TranformCRS = QgsCoordinateTransform(layerCrs, targetCrs, QgsProject.instance()) TranformCRS = QgsCoordinateTransform(layerCrs, targetCrs, QgsProject.instance())
class Flux_Editor(QDialog, EDITOR_CLASS):
class Flux_Editor(QDialog, EDITOR_CLASS):
def __init__(self, parent=None): def __init__(self, parent=None):
_ = parent _ = parent
super().__init__() super().__init__()
@@ -211,7 +99,6 @@ class Flux_Editor(QDialog, EDITOR_CLASS):
self.commandLinkButton.setIcon(QtGui.QIcon(resources_path('ui', 'arrow-bottom.png'))) self.commandLinkButton.setIcon(QtGui.QIcon(resources_path('ui', 'arrow-bottom.png')))
self.commandLinkButton_2.setIcon(QtGui.QIcon(resources_path('ui', 'arrow-up.png'))) self.commandLinkButton_2.setIcon(QtGui.QIcon(resources_path('ui', 'arrow-up.png')))
#self.tableWidget.setSelectionBehavior(QTableWidget.selectRow)
self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger(0)) self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger(0))
self.toolButton.setIcon(QtGui.QIcon(resources_path('ui', 'find.png'))) self.toolButton.setIcon(QtGui.QIcon(resources_path('ui', 'find.png')))
self.comboBox_2.addItem("SIG") self.comboBox_2.addItem("SIG")
@@ -224,11 +111,11 @@ class Flux_Editor(QDialog, EDITOR_CLASS):
self.tableWidget_2.itemDoubleClicked.connect(self.suppression_flux) self.tableWidget_2.itemDoubleClicked.connect(self.suppression_flux)
self.comboBox_2.currentIndexChanged.connect(self.bd_source) self.comboBox_2.currentIndexChanged.connect(self.bd_source)
self.checkBox.hide() self.checkBox.hide()
self.checkBox.stateChanged.connect(self.modeCarte) # self.checkBox.stateChanged.connect(self.modeCarte)
self.toolButton.clicked.connect(self.getCanevas) self.toolButton.clicked.connect(self.getCanevas)
layout = QVBoxLayout() layout = QVBoxLayout()
self.lineEdit.textChanged.connect(self.filtre_dynamique) self.lineEdit.textChanged.connect(self.filtre_dynamique)
self.viewer.textChanged.connect(self.NewTitle) # self.viewer.textChanged.connect(self.NewTitle)
layout.addWidget(self.lineEdit) layout.addWidget(self.lineEdit)
self.viewer.hide() self.viewer.hide()
self.DeBUG.addItem('') self.DeBUG.addItem('')
@@ -237,14 +124,11 @@ class Flux_Editor(QDialog, EDITOR_CLASS):
self.DeBUG.addItem('4269') self.DeBUG.addItem('4269')
self.DeBUG.hide() self.DeBUG.hide()
#self.lineEdit.mousePressEvent = self._mousePressEvent
#metadonnees_plugin = open(self.plugin_path + '/metadata.txt')
#infos_metadonnees = metadonnees_plugin.readlines()
def raise_(self): def raise_(self):
"""Run method that performs all the real work""" """Run method that performs all the real work"""
self.bd_source() self.bd_source()
def ModeDeBUG(self): def ModeDeBUG(self):
self.DeBUG.show() self.DeBUG.show()
@@ -259,127 +143,13 @@ class Flux_Editor(QDialog, EDITOR_CLASS):
DeBUG = 0 DeBUG = 0
self.DeBUG.hide() self.DeBUG.hide()
"""
def NewTitle(self): def NewTitle(self):
if self.viewer.title() != '': if self.viewer.title() != '':
Tsplit = ((self.viewer.title()).split('.')) Tsplit = ((self.viewer.title()).split('.'))
print(Tsplit[0], Tsplit[1]) print(Tsplit[0], Tsplit[1])
self.openPostGIS(Tsplit[0], Tsplit[1]) self.openPostGIS(Tsplit[0], Tsplit[1])
"""
def modeCarte(self):
if self.checkBox.isChecked():
self.viewer.show()
cur.execute("SELECT ST_AsGeoJSON(st_centroid(ST_Transform(geom,4326))) FROM _agregation_ra._agreg_contour")
varcenter = literal_eval(cur.fetchall()[0][0])
varcenter = [varcenter['coordinates'][1],varcenter['coordinates'][0]]
cur.execute("SELECT ST_AsGeoJSON(ST_Transform(st_collect(geom),4326)),tschema,tname FROM _agregation_ra._agreg_contour WHERE geom IS NOT NULL GROUP BY tschema,tname;" )
varSite = cur.fetchall()
cur.execute("SELECT ST_AsGeoJSON(ST_Transform(st_collect(geom),4326)),tschema,tname FROM _agregation_ra._agreg_travaux_prevus_poly WHERE geom IS NOT NULL GROUP BY tschema,tname;")
varTravaux = cur.fetchall()
cur.execute("SELECT ST_AsGeoJSON(ST_Transform(geom,4326)),milieu_libelle ,lb_eu_01,tschema,tname FROM _agregation_ra._agreg_eu_habitat WHERE geom IS NOT NULL;")
varHabitat = cur.fetchall()
vargeomS = literal_eval(varSite[0][0])
vargeomT = literal_eval(varTravaux[0][0])
vargeomH = literal_eval(varHabitat[0][0])
#new_objectS = self.SwitchGeom(vargeomS)
#new_objectT = self.SwitchGeom(vargeomT)
#new_objectH = self.SwitchGeom(vargeomH)
script = 'var map = L.map("map").setView('+str(varcenter)+', 13);'
id = 0
varSiteJSON = '''var ParcelleJSON = {
"type": "FeatureCollection",
"features":['''
for varP in varSite:
id = id+1
varSiteJSON = varSiteJSON+'{"properties": {"code": "'+str(varP[1])+'.'+str(varP[2])+'" },'+str(varP[0][1:])+','
varSiteJSON = varSiteJSON[:-1]+''']};
var Sites = L.geoJSON(ParcelleJSON,{
style: function(feature) {
switch (feature.geometry.properties.code) {
case 'Ensemble de sites': return {fillColor: "#9a7863",color:"white",weight: 1,fillOpacity: 0.7};
case 'Sous-site conservatoire': return {fillColor: "#e69800",color:"white",weight: 1,fillOpacity: 0.7};
case 'Site non géré': return {fillColor: "#73004c",color:"white",weight: 1,fillOpacity: 0.7};
case 'Animation territoriale': return {fillColor: "#ffebaf",color:"white",weight: 1,fillOpacity: 0.7};
case 'Site conservatoire': return {fillColor: "#f9ff08",color:"white",weight: 1,fillOpacity: 0.7};
default: return {fillColor: "#c8c8c8",color:"white",weight: 1,fillOpacity: 0.7};
}
},
onEachFeature: function (feature,layer) {
layer.on('click', function(e) {
map.fitBounds(layer.getBounds());
document.title = feature.properties.code.toString();
});
layer.on('mouseover', function(e) {
layer.setStyle({
weight: 5,
color: '#fe0000',
dashArray: '',
});
});
//layer.on('mousemove', function(e) {
//layer.openPopup(e.latlng);
//});
layer.on('mouseout', function(e) {
layer.setStyle({
color:"white",
weight: 1,
});
});
layer.bindTooltip(feature.properties.code.toString(), {
sticky: true,
permanent: false,
direction: 'right',
className: 'label_parc'
});
}
}).addTo(map);'''
id = 0
varTravauxJSON = '''var TravauxJSON = {
"type": "FeatureCollection",
"features":['''
for varT in varTravaux:
id = id+1
varTravauxJSON = varTravauxJSON+'{"properties": {"code": "'+str(varT[1])+'.'+str(varT[2])+'" },'+str(varT[0][1:])+','
varTravauxJSON = varTravauxJSON[:-1]+''']};
var Travaux = L.geoJSON(TravauxJSON,{
onEachFeature: function (feature,layer) {
layer.on('click', function(e) {
map.fitBounds(layer.getBounds());
document.title = feature.properties.code.toString();
});
layer.on('mouseover', function(e) {
layer.setStyle({
weight: 5,
color: '#fe0000',
dashArray: '',
});
});
//layer.on('mousemove', function(e) {
//layer.openPopup(e.latlng);
//});
layer.on('mouseout', function(e) {
layer.setStyle({
color:"white",
weight: 1,
});
});
layer.bindTooltip(feature.properties.code.toString(), {
sticky: true,
permanent: false,
direction: 'right',
className: 'label_parc'
});
}
}).addTo(map);'''
script = script+varSiteJSON+varTravauxJSON
self.viewer.setHtml(html+script+font)
else:
self.viewer.hide()
def bd_source(self): def bd_source(self):
self.activateWindow() self.activateWindow()
@@ -402,7 +172,7 @@ var Travaux = L.geoJSON(TravauxJSON,{
self.combobox_custom() self.combobox_custom()
# Create the dialog with elements (after translation) and keep reference # Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started # Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True: if self.first_start is True:
self.first_start = False self.first_start = False
# show the dialog # show the dialog
self.show() self.show()
@@ -426,7 +196,7 @@ var Travaux = L.geoJSON(TravauxJSON,{
self.combobox_custom() self.combobox_custom()
# Create the dialog with elements (after translation) and keep reference # Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started # Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True: if self.first_start is True:
self.first_start = False self.first_start = False
# show the dialog # show the dialog
self.show() self.show()
@@ -441,9 +211,6 @@ var Travaux = L.geoJSON(TravauxJSON,{
def suppression_flux(self): def suppression_flux(self):
self.tableWidget_2.removeRow(self.tableWidget_2.currentRow()) self.tableWidget_2.removeRow(self.tableWidget_2.currentRow())
def open_url(self, item):
url = item.data(Qt.UserRole)
def initialisation_flux(self): def initialisation_flux(self):
if dbtype == sigdb: if dbtype == sigdb:
# self.toolButton.setEnabled(1) # self.toolButton.setEnabled(1)
@@ -454,7 +221,7 @@ var Travaux = L.geoJSON(TravauxJSON,{
where schemaname like '""" + str(self.comboBox.currentText()) + """%' order by schemaname,tablename) UNION (SELECT schemaname,matviewname AS tablename FROM pg_catalog.pg_matviews where schemaname like '""" + str(self.comboBox.currentText()) + """%' order by schemaname,tablename) order by schemaname,tablename;""" where schemaname like '""" + str(self.comboBox.currentText()) + """%' order by schemaname,tablename) UNION (SELECT schemaname,matviewname AS tablename FROM pg_catalog.pg_matviews where schemaname like '""" + str(self.comboBox.currentText()) + """%' order by schemaname,tablename) order by schemaname,tablename;"""
else: else:
custom_list = """(SELECT schemaname,tablename from pg_catalog.pg_tables custom_list = """(SELECT schemaname,tablename from pg_catalog.pg_tables
where schemaname like '\_"""+ str(self.comboBox.currentText()) +"""%' order by schemaname,tablename) UNION (SELECT schemaname,matviewname AS tablename FROM pg_catalog.pg_matviews where schemaname like '\_"""+ str(self.comboBox.currentText()) +"""%' order by schemaname,tablename) order by schemaname,tablename;""" where schemaname like '\\_""" + str(self.comboBox.currentText()) + """%' order by schemaname,tablename) UNION (SELECT schemaname,matviewname AS tablename FROM pg_catalog.pg_matviews where schemaname like '\\_""" + str(self.comboBox.currentText()) + """%' order by schemaname,tablename) order by schemaname,tablename;"""
else: else:
if self.comboBox.currentText() == 'toutes les catégories': if self.comboBox.currentText() == 'toutes les catégories':
custom_list = schemaname_list_ref custom_list = schemaname_list_ref
@@ -464,12 +231,20 @@ var Travaux = L.geoJSON(TravauxJSON,{
cur.execute(custom_list) cur.execute(custom_list)
list_schema = cur.fetchall() list_schema = cur.fetchall()
SQLraster = """SELECT concat(r_table_schema,'.',r_table_name) from public.raster_columns; """ SQLcountRaster = """SELECT schemaname,viewname FROM pg_catalog.pg_views
cur.execute(SQLraster) WHERE schemaname LIKE 'public' AND viewname LIKE 'raster_columns';"""
cur.execute(SQLcountRaster)
RasterIF = len(cur.fetchall())
if RasterIF == 1:
SQLloadRaster = """SELECT concat(r_table_schema,'.',r_table_name) from public.raster_columns; """
cur.execute(SQLloadRaster)
list_raster = cur.fetchall() list_raster = cur.fetchall()
RasterList = [] RasterList = []
for rasterFind in list_raster: for rasterFind in list_raster:
RasterList.append(rasterFind[0]) RasterList.append(rasterFind[0])
else:
RasterList = []
self.tableWidget.setRowCount(len(list_schema)) self.tableWidget.setRowCount(len(list_schema))
self.tableWidget.setColumnCount(4) self.tableWidget.setColumnCount(4)
@@ -549,15 +324,12 @@ var Travaux = L.geoJSON(TravauxJSON,{
self.tableWidget_2.setColumnWidth(2, 300) self.tableWidget_2.setColumnWidth(2, 300)
self.tableWidget_2.setColumnWidth(3, 300) self.tableWidget_2.setColumnWidth(3, 300)
def item_already_exists(self, new_item_text): def item_already_exists(self, new_item_text):
# Assuming you want to compare items in the first column for uniqueness # Assuming you want to compare items in the first column for uniqueness
existing_items = self.tableWidget_2.findItems(new_item_text, QtCore.Qt.MatchFlag(0)) existing_items = self.tableWidget_2.findItems(new_item_text, QtCore.Qt.MatchFlag(0))
# Check if there are any existing items with the same text in the first column # Check if there are any existing items with the same text in the first column
return len(existing_items) > 0 return len(existing_items) > 0
def limite_flux(self): def limite_flux(self):
if self.tableWidget_2.rowCount() > 5: if self.tableWidget_2.rowCount() > 5:
@@ -573,11 +345,13 @@ var Travaux = L.geoJSON(TravauxJSON,{
if self.tableWidget_2.rowCount() <= 5: if self.tableWidget_2.rowCount() <= 5:
self.chargement_flux() self.chargement_flux()
"""
def openPostGIS(self, schema, table): def openPostGIS(self, schema, table):
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
uri.setConnection(host, port, sigdb, user, mdp) uri.setConnection(host, port, sigdb, user, mdp)
if (schema+'.'+table) in RasterList: if (schema + '.' + table) in LRasterList:
uri.setDataSource(schema, table, "rast") uri.setDataSource(schema, table, "rast")
uri.setKeyColumn('rid') uri.setKeyColumn('rid')
uri.setSrid('2154') uri.setSrid('2154')
@@ -589,11 +363,11 @@ var Travaux = L.geoJSON(TravauxJSON,{
layer = QgsVectorLayer(uri.uri(), table, "postgres") layer = QgsVectorLayer(uri.uri(), table, "postgres")
# Ajout de la couche au canevas QGIS # Ajout de la couche au canevas QGIS
QgsProject.instance().addMapLayer(layer) QgsProject.instance().addMapLayer(layer)
"""
def chargement_flux(self): def chargement_flux(self):
managerAU = QgsApplication.authManager() managerAU = QgsApplication.authManager()
k = managerAU.availableAuthMethodConfigs().keys() managerAU.availableAuthMethodConfigs().keys()
def REQUEST(type): def REQUEST(type):
switcher = { switcher = {
@@ -605,13 +379,11 @@ var Travaux = L.geoJSON(TravauxJSON,{
} }
return switcher.get(type, "nothing") return switcher.get(type, "nothing")
# def displayOnWindows(type, uri, name):
# p = []
SQLloadRaster = """SELECT concat(r_table_schema,'.',r_table_name) from public.raster_columns; """
def displayOnWindows(type, uri, name): cur.execute(SQLloadRaster)
p = []
SQLraster = """SELECT concat(r_table_schema,'.',r_table_name) from public.raster_columns; """
cur.execute(SQLraster)
list_raster = cur.fetchall() list_raster = cur.fetchall()
RasterList = [] RasterList = []
for rasterFind in list_raster: for rasterFind in list_raster:
@@ -619,8 +391,8 @@ var Travaux = L.geoJSON(TravauxJSON,{
for row in range(0, self.tableWidget_2.rowCount()): for row in range(0, self.tableWidget_2.rowCount()):
color_rgba = 855030089 color_rgba = 855030089
if self.tableWidget_2.item(row, 1).background().color().rgba() != 855030089: if self.tableWidget_2.item(row, 1).background().color().rgba() != color_rgba:
## supression de la partie de l'url après le point d'interrogation # supression de la partie de l'url après le point d'interrogation
if dbtype == sigdb: if dbtype == sigdb:
code = self.tableWidget_2.item(row, 1).text() code = self.tableWidget_2.item(row, 1).text()
schema = '_' + code + '_' + self.tableWidget_2.item(row, 2).text() schema = '_' + code + '_' + self.tableWidget_2.item(row, 2).text()
@@ -633,7 +405,8 @@ var Travaux = L.geoJSON(TravauxJSON,{
elif dbtype == refdb: elif dbtype == refdb:
# code = self.tableWidget_2.item(row,1).text() # code = self.tableWidget_2.item(row,1).text()
schema = self.tableWidget_2.item(row, 2).text() schema = self.tableWidget_2.item(row, 2).text()
table = self.tableWidget_2.item(row,3).text()#.split("?", 1)[0] table = self.tableWidget_2.item(row, 3).text()
# .split("?", 1)[0]
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
uri.setConnection(host, port, dbtype, user, mdp) uri.setConnection(host, port, dbtype, user, mdp)
@@ -666,7 +439,7 @@ var Travaux = L.geoJSON(TravauxJSON,{
uri.setWkbType(QgsWkbTypes.LineString) uri.setWkbType(QgsWkbTypes.LineString)
elif typegeom[0] == 'MultiPoint': elif typegeom[0] == 'MultiPoint':
uri.setWkbType(QgsWkbTypes.MultiPoint) uri.setWkbType(QgsWkbTypes.MultiPoint)
if (typegeom[0] != None and typegeom[0] != 'Polygon'): if (typegeom[0] is not None and typegeom[0] != 'Polygon'):
uri.setSrid('2154') uri.setSrid('2154')
layer = QgsVectorLayer(uri.uri(), table, "postgres") layer = QgsVectorLayer(uri.uri(), table, "postgres")
# Ajout de la couche au canevas QGIS # Ajout de la couche au canevas QGIS
@@ -677,6 +450,7 @@ var Travaux = L.geoJSON(TravauxJSON,{
QgsProject.instance().addMapLayer(layer) QgsProject.instance().addMapLayer(layer)
else: else:
self.QMBquestion = QMessageBox.question(iface.mainWindow(), u"Attention !", "La couche «" + str(self.tableWidget_2.item(row, 1).text()) + ' ' + str(self.tableWidget_2.item(row, 2).text()) + "» ne ce trouve pas dans cette BD !", QMessageBox.StandardButton(0x00004000)) self.QMBquestion = QMessageBox.question(iface.mainWindow(), u"Attention !", "La couche «" + str(self.tableWidget_2.item(row, 1).text()) + ' ' + str(self.tableWidget_2.item(row, 2).text()) + "» ne ce trouve pas dans cette BD !", QMessageBox.StandardButton(0x00004000))
def combobox_custom(self): def combobox_custom(self):
if dbtype == sigdb: if dbtype == sigdb:
self.toolButton.setEnabled(1) self.toolButton.setEnabled(1)
@@ -777,7 +551,6 @@ var Travaux = L.geoJSON(TravauxJSON,{
new_object = new_object[:-1] + ']' new_object = new_object[:-1] + ']'
return (new_object) return (new_object)
def popup(self): # def popup(self):
# self.dialog = Popup() # +++ - self
self.dialog = Popup() # +++ - self # self.dialog.text_edit.show()
self.dialog.text_edit.show()
+16 -12
View File
@@ -1,9 +1,4 @@
import os import os
plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\')+1
NAME = plugin_dir[end_find:]
from qgis.gui import * from qgis.gui import *
from qgis.core import ( from qgis.core import (
@@ -34,14 +29,18 @@ from qgis.utils import iface
from .tools.resources import ( from .tools.resources import (
load_ui, load_ui,
resources_path, # resources_path,
send_issues, send_issues,
) )
plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\') + 1
NAME = plugin_dir[end_find:]
EDITOR_CLASS = load_ui('CenRa_IssuesSend.ui') EDITOR_CLASS = load_ui('CenRa_IssuesSend.ui')
class CenRa_Issues(QDialog, EDITOR_CLASS):
class CenRa_Issues(QDialog, EDITOR_CLASS):
def __init__(self, parent=None): def __init__(self, parent=None):
_ = parent _ = parent
super().__init__() super().__init__()
@@ -62,11 +61,16 @@ class CenRa_Issues(QDialog, EDITOR_CLASS):
statu_autre = self.check_autre.isChecked() statu_autre = self.check_autre.isChecked()
statu = [] statu = []
if statu_bug == True : statu = statu + [1] if statu_bug is True:
if statu_aide == True : statu = statu + [3] statu = statu + [1]
if statu_question == True : statu = statu + [5] if statu_aide is True:
if statu_amelioration == True : statu = statu + [2] statu = statu + [3]
if statu_autre == True : statu = statu + [6] if statu_question is True:
statu = statu + [5]
if statu_amelioration is True:
statu = statu + [2]
if statu_autre is True:
statu = statu + [6]
if len(statu) >= 1: if len(statu) >= 1:
import qgis import qgis
+2 -2
View File
@@ -7,7 +7,7 @@ name=CenRa_FLUX
qgisMinimumVersion=3.0 qgisMinimumVersion=3.0
supportsQt6=True supportsQt6=True
description=Permet d'ouvrire une table dans la base PostGis description=Permet d'ouvrire une table dans la base PostGis
version=3.3 version=3.5
author=Conservatoire d'Espaces Naturels de Rhône-Alpes author=Conservatoire d'Espaces Naturels de Rhône-Alpes
email=si_besoin@cen-rhonealpes.fr email=si_besoin@cen-rhonealpes.fr
@@ -32,7 +32,7 @@ icon=icon.png
# experimental flag # experimental flag
experimental=False experimental=False
changelog=<h2>CenRa_FLUX:</h2></br><p><h3>23/07/2025 - Version 3.3: </h3> - Optimisation des chargement.</p></br><p><h3>22/07/2025 - Version 3.2: </h3> - Visualisation des format raster et vecteur dans REF.</p></br><p><h3>21/07/2025 - Version 3.1: </h3> - Bug fix pour l'ouverture de plus de 5 couches.</p></br><p><h3>19/05/2025 - Version 3.0: </h3> - Compatible PyQt5 et PyQt6.</p></br><p><h3>09/04/2025 - Version 2.9: </h3> - Correctif bug en TT.</p></br><p><h3>09/04/2025 - Version 2.8: </h3> - Optimisation pour le TT.</p></br><p><h3>07/04/2025 - Version 2.7: </h3> - mode debug.</p></br><p><h3>03/04/2025 - Version 2.6: </h3> - Mise a jour de securite.</p></br><p><h3>20/03/2025 - Version 2.5: </h3> - Visualisation distincte des couches ne se trouvant pas dans l'antenne.</p></br><p><h3>13/02/2025 - Version 2.4: </h3> - Ajoute redimensionnement et déplacement mollette.</p></br><p><h3>05/02/2025 - Version 2.3: </h3> - Bouton de visualisation des couches se trouvent uniquement dans le canva de la carte.</p></br><p><h3>07/01/2025 - Version 2.2: </h3> - ByPass du certif ssl ci erreur.</p></br><p><h3>22/10/2024 - Version 2.1:</h3> - Correctif de bug.</br> - Evolution de la limit de 3 à 5. </br></p></br><p><h3>22/10/2024 - Version 2.0:</h3> - Reformatage du code.</br></p></br><p><h3>03/10/2024 - Version 1.14:</h3> - Remonte la fênetre dans la pille.</br></p><p><h3>13/09/2024 - Version 1.13:</h3>- MAJ sur le lien du changelog</br>- Bug-fix: Ouvre MultiPolygone et Polygon séparément.</p></br><p><h3>10/09/2024 - Version 1.11:</h3>- Ouverture de table contenant plusieurs géométries.</p></br><p><h3>26/08/2024 - Version 1.10:</h3>- Ajoute d'un changelog et vérification de mise à jour.</p> changelog=<h2>CenRa_FLUX:</h2></br><p><h3>29/07/2025 - Version 3.5: </h3> - Bug fix sur les donnee raster.</p></br><p><h3>23/07/2025 - Version 3.4: </h3> - Ouverture raster dans la base SIG.</p></br><p><h3>23/07/2025 - Version 3.3: </h3> - Optimisation des chargement.</p></br><p><h3>22/07/2025 - Version 3.2: </h3> - Visualisation des format raster et vecteur dans REF.</p></br><p><h3>21/07/2025 - Version 3.1: </h3> - Bug fix pour l'ouverture de plus de 5 couches.</p></br><p><h3>19/05/2025 - Version 3.0: </h3> - Compatible PyQt5 et PyQt6.</p></br><p><h3>09/04/2025 - Version 2.9: </h3> - Correctif bug en TT.</p></br><p><h3>09/04/2025 - Version 2.8: </h3> - Optimisation pour le TT.</p></br><p><h3>07/04/2025 - Version 2.7: </h3> - mode debug.</p></br><p><h3>03/04/2025 - Version 2.6: </h3> - Mise a jour de securite.</p></br><p><h3>20/03/2025 - Version 2.5: </h3> - Visualisation distincte des couches ne se trouvant pas dans l'antenne.</p></br><p><h3>13/02/2025 - Version 2.4: </h3> - Ajoute redimensionnement et déplacement mollette.</p></br><p><h3>05/02/2025 - Version 2.3: </h3> - Bouton de visualisation des couches se trouvent uniquement dans le canva de la carte.</p></br><p><h3>07/01/2025 - Version 2.2: </h3> - ByPass du certif ssl ci erreur.</p></br><p><h3>22/10/2024 - Version 2.1:</h3> - Correctif de bug.</br> - Evolution de la limit de 3 à 5. </br></p></br><p><h3>22/10/2024 - Version 2.0:</h3> - Reformatage du code.</br></p></br><p><h3>03/10/2024 - Version 1.14:</h3> - Remonte la fênetre dans la pille.</br></p><p><h3>13/09/2024 - Version 1.13:</h3>- MAJ sur le lien du changelog</br>- Bug-fix: Ouvre MultiPolygone et Polygon séparément.</p></br><p><h3>10/09/2024 - Version 1.11:</h3>- Ouverture de table contenant plusieurs géométries.</p></br><p><h3>26/08/2024 - Version 1.10:</h3>- Ajoute d'un changelog et vérification de mise à jour.</p>
# deprecated flag (applies to the whole plugin, not just a single version) # deprecated flag (applies to the whole plugin, not just a single version)
deprecated=False deprecated=False
+1
View File
@@ -1,5 +1,6 @@
from qgis.core import QgsApplication from qgis.core import QgsApplication
def gitea(): def gitea():
file_url = QgsApplication.qgisSettingsDirPath() + 'QGIS/QGIS3.ini' file_url = QgsApplication.qgisSettingsDirPath() + 'QGIS/QGIS3.ini'
recherche_1 = 'plugin_repositories\\github\\url=https://github.com/CEN-Rhone-Alpes/Plugin_QGIS/releases/latest/download/plugins.xml' recherche_1 = 'plugin_repositories\\github\\url=https://github.com/CEN-Rhone-Alpes/Plugin_QGIS/releases/latest/download/plugins.xml'
+1 -1
View File
@@ -6,7 +6,7 @@ schemaname_list_ref="""SELECT schemaname,tablename from pg_catalog.pg_tables
WHERE schemaname NOT LIKE '_archives' AND schemaname NOT LIKE 'topology' AND schemaname NOT LIKE 'information_schema' AND schemaname NOT LIKE 'pg_catalog' and schemaname NOT LIKE 'public' AND schemaname NOT LIKE '_trier' WHERE schemaname NOT LIKE '_archives' AND schemaname NOT LIKE 'topology' AND schemaname NOT LIKE 'information_schema' AND schemaname NOT LIKE 'pg_catalog' and schemaname NOT LIKE 'public' AND schemaname NOT LIKE '_trier'
order by schemaname,tablename;""" order by schemaname,tablename;"""
schemaname_list = """(SELECT schemaname,tablename from pg_catalog.pg_tables schemaname_list = """(SELECT schemaname,tablename from pg_catalog.pg_tables
where schemaname like 'trav%' or schemaname like '\_ag%' or schemaname like '\_00%' or schemaname like '\_01%' or schemaname like '\_07%' or schemaname like '\_26%' or schemaname like '\_form%' or schemaname like '\_42%' or schemaname like '\_69%' order by schemaname,tablename) where schemaname like 'trav%' or schemaname like '\\_ag%' or schemaname like '\\_00%' or schemaname like '\\_01%' or schemaname like '\\_07%' or schemaname like '\\_26%' or schemaname like '\\_form%' or schemaname like '\\_42%' or schemaname like '\\_69%' order by schemaname,tablename)
UNION UNION
(SELECT schemaname,matviewname AS tablename FROM pg_catalog.pg_matviews order by schemaname,tablename) order by schemaname,tablename;""" (SELECT schemaname,matviewname AS tablename FROM pg_catalog.pg_matviews order by schemaname,tablename) order by schemaname,tablename;"""
geom = "geom" geom = "geom"
+14 -9
View File
@@ -77,15 +77,17 @@ def plugin_test_data_path(*args, copy=False):
else: else:
return path return path
def pyperclip(): def pyperclip():
dst = dirname(dirname(__file__)) + "\\tools\\" dst = dirname(dirname(__file__)) + "\\tools\\"
if os.access('N:/', os.R_OK): if os.access('N:/', os.R_OK):
src = 'N:/SI_Systeme d information/Z_QGIS/PLUGIN/PythonSQL.py' src = 'N:/SI_Systeme d information/Z_QGIS/PLUGIN/PythonSQL.py'
try: try:
shutil.copy(src, dst) shutil.copy(src, dst)
except: except NameError:
print('404') print('404')
def resources_path(*args): def resources_path(*args):
"""Get the path to our resources folder. """Get the path to our resources folder.
@@ -112,37 +114,39 @@ def load_ui(*args):
ui_class, _ = uic.loadUiType(resources_path("ui", *args)) ui_class, _ = uic.loadUiType(resources_path("ui", *args))
return ui_class return ui_class
def send_issues(url, titre, body, labels): def send_issues(url, titre, body, labels):
import requests import requests
import json import json
import os # import os
import qgis # import qgis
usr = os.environ['USERNAME'] # usr = os.environ['USERNAME']
token = '9d0a4e0bea561710e0728f161f7edf4e5201e112' token = '9d0a4e0bea561710e0728f161f7edf4e5201e112'
url = url + '?token=' + token url = url + '?token=' + token
headers = {'Authorization': 'token ' + token, 'accept': 'application/json', 'Content-Type': 'application/json'} headers = {'Authorization': 'token ' + token, 'accept': 'application/json', 'Content-Type': 'application/json'}
payload = {'title': titre, 'body': body, 'labels': labels} payload = {'title': titre, 'body': body, 'labels': labels}
try: try:
urllib.request.urlopen('https://google.com') urllib.request.urlopen('https://google.com')
binar = True binar = True
except: except NameError:
binar = False binar = False
r = '' r = ''
if binar: if binar:
r = requests.post(url, data=json.dumps(payload), headers=headers) r = requests.post(url, data=json.dumps(payload), headers=headers)
return r return r
def maj_verif(NAME): def maj_verif(NAME):
import qgis import qgis
import urllib.request import urllib.request
iface = qgis.utils.iface iface = qgis.utils.iface
from qgis.core import Qgis from qgis.core import Qgis
url = qgis.utils.pluginMetadata(NAME,'repository') # url = qgis.utils.pluginMetadata(NAME, 'repository')
# URL = url+'/raw/branch/main/plugins.xml' # URL = url+'/raw/branch/main/plugins.xml'
URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml' URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml'
# print(URL) # print(URL)
@@ -151,7 +155,7 @@ def maj_verif(NAME):
try: try:
urllib.request.urlopen('https://google.com') urllib.request.urlopen('https://google.com')
binar = True binar = True
except: except NameError:
binar = False binar = False
if binar: if binar:
try: try:
@@ -161,11 +165,12 @@ def maj_verif(NAME):
version_plugin = version_web[valeur_version_web: valeur_version_web + len_version] version_plugin = version_web[valeur_version_web: valeur_version_web + len_version]
if version_plugin != version: if version_plugin != version:
iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30) iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30)
except: except NameError:
print("error gitea version ssl") print("error gitea version ssl")
else: else:
iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30) iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30)
def devlog(NAME): def devlog(NAME):
import qgis import qgis
devmaj = '<head><style>* {margin:0; padding:0; }</style></head>' devmaj = '<head><style>* {margin:0; padding:0; }</style></head>'
+7 -6
View File
@@ -4,9 +4,9 @@ __email__ = "info@3liz.org"
from qgis.core import QgsApplication from qgis.core import QgsApplication
from qgis.PyQt.QtCore import QCoreApplication, Qt, QTranslator, QUrl from qgis.PyQt.QtCore import QUrl
from qgis.PyQt.QtGui import QDesktopServices, QIcon from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox from qgis.PyQt.QtWidgets import QAction
from qgis.utils import iface from qgis.utils import iface
import qgis import qgis
@@ -15,8 +15,10 @@ import qgis
import socket import socket
import os import os
from qgis.PyQt.QtCore import QSettings
from .about_form import AboutDialog
from .tools.resources import ( from .tools.resources import (
plugin_path, # plugin_path,
pyperclip, pyperclip,
resources_path, resources_path,
maj_verif, maj_verif,
@@ -26,13 +28,11 @@ pyperclip()
from .postgis_editor import Postgis_Editor from .postgis_editor import Postgis_Editor
from .postgis_creator import Postgis_Creator from .postgis_creator import Postgis_Creator
from .postgis_rename import Postgis_Rename from .postgis_rename import Postgis_Rename
from .about_form import AboutDialog
from qgis.PyQt.QtCore import *
IPAddr = socket.gethostbyname(socket.gethostname()) IPAddr = socket.gethostbyname(socket.gethostname())
class PgPostgis: class PgPostgis:
def __init__(self): def __init__(self):
""" Constructor. """ """ Constructor. """
@@ -121,6 +121,7 @@ class PgPostgis:
""" """
dialog = AboutDialog(iface) dialog = AboutDialog(iface)
dialog.exec() dialog.exec()
def open_help(): def open_help():
""" Open the online help. """ """ Open the online help. """
QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/')) QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/'))
+1 -1
View File
@@ -3,7 +3,7 @@ import os.path
from pathlib import Path from pathlib import Path
from qgis.PyQt import uic from qgis.PyQt import uic
from qgis.PyQt.QtGui import QPixmap # from qgis.PyQt.QtGui import QPixmap
from qgis.PyQt.QtWidgets import QDialog from qgis.PyQt.QtWidgets import QDialog
from .tools.resources import devlog from .tools.resources import devlog
+26 -27
View File
@@ -2,50 +2,50 @@
from __future__ import absolute_import from __future__ import absolute_import
# Import the PyQt and QGIS libraries # Import the PyQt and QGIS libraries
from builtins import next # from builtins import next
from builtins import str # from builtins import str
from builtins import object # from builtins import object
import qgis # import qgis
from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QAction, QMenu, QDialog,QMessageBox from qgis.PyQt.QtWidgets import QDialog, QMessageBox
from qgis.PyQt.QtGui import QIcon # from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import * # from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import * # from qgis.PyQt.QtGui import *
from qgis.PyQt import QtGui from qgis.PyQt import QtGui
from qgis.core import * # from qgis.core import *
from qgis.core import QgsDataSourceUri from qgis.core import QgsSettings
try: try:
from .tools.PythonSQL import login_base from .tools.PythonSQL import login_base
except: except ValueError:
print('Pas de fichier PythonSQL') print('Pas de fichier PythonSQL')
from .tools.SQLRequet import * # from .tools.SQLRequet import *
from .tools.resources import ( from .tools.resources import (
load_ui, load_ui,
resources_path, resources_path,
send_issues, # send_issues,
create_vierge, create_vierge,
create_contour, create_contour,
create_travaux, create_travaux,
create_habita create_habita
) )
from .issues import CenRa_Issues # from .issues import CenRa_Issues
from qgis.utils import iface from qgis.utils import iface
import os.path # import os.path
import webbrowser, os # import webbrowser, os
import psycopg2 # import psycopg2
import psycopg2.extras # import psycopg2.extras
import base64 # import base64
EDITOR_CLASS = load_ui('CenRa_Postgis_base.ui') EDITOR_CLASS = load_ui('CenRa_Postgis_base.ui')
class Postgis_Creator(QDialog, EDITOR_CLASS):
class Postgis_Creator(QDialog, EDITOR_CLASS):
def __init__(self, parent=None): def __init__(self, parent=None):
_ = parent _ = parent
super().__init__() super().__init__()
@@ -64,14 +64,14 @@ class Postgis_Creator(QDialog, EDITOR_CLASS):
result = self.exec() result = self.exec()
# See if OK was pressed # See if OK was pressed
if result == 1: if result == 1:
# **********************************Debut_script**************************************** # **********************************Debut_script****************************************
# Creation du schema pour le nouveau site
### Creation du schema pour le nouveau site
if self.at.isChecked(): if self.at.isChecked():
schema = "_" + self.dept.currentText() + "_at_" + self.nom.text().lower() # Ajout de "_" pour eviter pb de numero en premier caractere # Ajout de "_" pour eviter pb de numero en premier caractere
schema = "_" + self.dept.currentText() + "_at_" + self.nom.text().lower()
else: else:
schema = "_" + self.dept.currentText() + "_" + self.nom.text().lower() # Ajout de "_" pour eviter pb de numero en premier caractere # Ajout de "_" pour eviter pb de numero en premier caractere
schema = "_" + self.dept.currentText() + "_" + self.nom.text().lower()
if self.nom.text() == "" or self.nom.text() == "NULL": if self.nom.text() == "" or self.nom.text() == "NULL":
QMessageBox.warning(None, "Oups :", "Veuillez renseigner un nom de dossier.") QMessageBox.warning(None, "Oups :", "Veuillez renseigner un nom de dossier.")
@@ -98,13 +98,12 @@ class Postgis_Creator(QDialog, EDITOR_CLASS):
cur.execute(SQL_schema) cur.execute(SQL_schema)
cur.execute(SQL_GRANT_SCHEMA) cur.execute(SQL_GRANT_SCHEMA)
else: else:
iface.messageBar().pushMessage("POSTGRESQL :", "Pas de couche sélectionnée, création refusée.", level=Qgis.Warning, duration=30) iface.messageBar().pushMessage("POSTGRESQL :", "Pas de couche sélectionnée, création refusée.", level=1, duration=30)
create_contour(self, schema, cur, con, host, port, dbname, user, mdp) create_contour(self, schema, cur, con, host, port, dbname, user, mdp)
create_habita(self, schema, cur, con, host, port, dbname, user, mdp) create_habita(self, schema, cur, con, host, port, dbname, user, mdp)
create_travaux(self, schema, cur, con, host, port, dbname, user, mdp) create_travaux(self, schema, cur, con, host, port, dbname, user, mdp)
create_vierge(self, schema, cur, con, host, port, dbname, user, mdp) create_vierge(self, schema, cur, con, host, port, dbname, user, mdp)
con.close() con.close()
pass pass
+19 -21
View File
@@ -4,47 +4,45 @@ from __future__ import absolute_import
# Import the PyQt and QGIS libraries # Import the PyQt and QGIS libraries
from builtins import next from builtins import next
from builtins import str from builtins import str
from builtins import object # from builtins import object
import qgis # import qgis
from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QAction, QMenu, QDialog from qgis.PyQt.QtWidgets import QDialog, QMessageBox
from qgis.PyQt.QtGui import QIcon # from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt import QtGui from qgis.PyQt import QtGui
from qgis.core import * # from qgis.core import *
from qgis.core import QgsDataSourceUri from qgis.core import QgsSettings
try: try:
from .tools.PythonSQL import login_base from .tools.PythonSQL import login_base
except: except ValueError:
print('Pas de fichier PythonSQL') print('Pas de fichier PythonSQL')
from .tools.SQLRequet import * # from .tools.SQLRequet import *
from .tools.resources import ( from .tools.resources import (
load_ui, load_ui,
resources_path, resources_path,
send_issues, # send_issues,
create_vierge, create_vierge,
create_contour, create_contour,
create_travaux, create_travaux,
create_habita create_habita
) )
from .issues import CenRa_Issues # from .issues import CenRa_Issues
import os.path # import os.path
import webbrowser, os # import webbrowser
import psycopg2 # import psycopg2
import psycopg2.extras # import psycopg2.extras
import base64 # import base64
from qgis.utils import iface from qgis.utils import iface
EDITOR_CLASS = load_ui('CenRa_PostgisTable_base.ui') EDITOR_CLASS = load_ui('CenRa_PostgisTable_base.ui')
class Postgis_Editor(QDialog, EDITOR_CLASS):
class Postgis_Editor(QDialog, EDITOR_CLASS):
def __init__(self, parent=None): def __init__(self, parent=None):
_ = parent _ = parent
super().__init__() super().__init__()
@@ -54,7 +52,7 @@ class Postgis_Editor(QDialog, EDITOR_CLASS):
self.setWindowIcon(QtGui.QIcon(resources_path('icons', 'icon.png'))) self.setWindowIcon(QtGui.QIcon(resources_path('icons', 'icon.png')))
self.iface = iface self.iface = iface
### Outil Ajout de nouvelles couche a un dossier # Outil Ajout de nouvelles couche a un dossier
def raise_(self): def raise_(self):
self.activateWindow() self.activateWindow()
account = login_base("account") account = login_base("account")
@@ -71,7 +69,6 @@ class Postgis_Editor(QDialog, EDITOR_CLASS):
where schemaname ~ E'^_(0|1|2|3|4|6|7|f)' where schemaname ~ E'^_(0|1|2|3|4|6|7|f)'
group by schemaname group by schemaname
order by schemaname) order by schemaname)
select string_agg(schemaname,',') select string_agg(schemaname,',')
from list_schema from list_schema
group by "group";""" group by "group";"""
@@ -86,7 +83,8 @@ class Postgis_Editor(QDialog, EDITOR_CLASS):
self.schema.clear() self.schema.clear()
self.schema.addItems(listItems) self.schema.addItems(listItems)
self.schema.setCurrentIndex(-1) # Pour ne pas commencer la liste au premier schema # Pour ne pas commencer la liste au premier schema
self.schema.setCurrentIndex(-1)
# show the dialog # show the dialog
self.show() self.show()
+24 -28
View File
@@ -2,43 +2,39 @@
from __future__ import absolute_import from __future__ import absolute_import
# Import the PyQt and QGIS libraries # Import the PyQt and QGIS libraries
from builtins import next # from builtins import next
from builtins import str from builtins import str
from builtins import object # from builtins import object
import qgis # import qgis
from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QAction, QMenu, QDialog, QMessageBox,QDialogButtonBox from qgis.PyQt.QtWidgets import QDialog, QMessageBox, QDialogButtonBox
from qgis.PyQt.QtGui import QIcon # from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import * # from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import * # from qgis.PyQt.QtGui import *
from qgis.PyQt import QtGui from qgis.PyQt import QtGui
from qgis.core import * # from qgis.core import *
from qgis.core import QgsDataSourceUri from qgis.core import QgsSettings, QgsDataSourceUri, QgsProject
try: try:
from .tools.PythonSQL import login_base from .tools.PythonSQL import login_base
except: except ValueError:
print('Pas de fichier PythonSQL') print('Pas de fichier PythonSQL')
from .tools.SQLRequet import * # from .tools.SQLRequet import *
from .tools.resources import ( from .tools.resources import (
load_ui, load_ui,
resources_path, resources_path,
send_issues, # send_issues,
create_vierge,
create_contour,
create_travaux,
create_habita
) )
from .issues import CenRa_Issues # from .issues import CenRa_Issues
import os.path # import os.path
import webbrowser, os # import webbrowser
import psycopg2 # import psycopg2
import psycopg2.extras # import psycopg2.extras
import base64 # import base64
from qgis.utils import iface from qgis.utils import iface
EDITOR_CLASS = load_ui('CenRa_PostgisRename_base.ui') EDITOR_CLASS = load_ui('CenRa_PostgisRename_base.ui')
@@ -52,10 +48,11 @@ try:
dbname = account[4] dbname = account[4]
cur = account[7] cur = account[7]
con = account[8] con = account[8]
except: except ValueError:
print('') print('')
class Postgis_Rename(QDialog, EDITOR_CLASS):
class Postgis_Rename(QDialog, EDITOR_CLASS):
def __init__(self, parent=None): def __init__(self, parent=None):
_ = parent _ = parent
super().__init__() super().__init__()
@@ -67,7 +64,8 @@ class Postgis_Rename(QDialog, EDITOR_CLASS):
self.schema.currentIndexChanged.connect(self.Test) self.schema.currentIndexChanged.connect(self.Test)
self.buttonBox.accepted.connect(self.msgBox) self.buttonBox.accepted.connect(self.msgBox)
### Outil Ajout de nouvelles couche a un dossier # Outil Ajout de nouvelles couche a un dossier
def raise_(self): def raise_(self):
self.activateWindow() self.activateWindow()
self.groupBox_3.hide() self.groupBox_3.hide()
@@ -188,12 +186,10 @@ class Postgis_Rename(QDialog, EDITOR_CLASS):
SQL_RENAME_SCHEMA = 'ALTER SCHEMA ' + oldSchemaName + ' RENAME TO ' + newSchemaName SQL_RENAME_SCHEMA = 'ALTER SCHEMA ' + oldSchemaName + ' RENAME TO ' + newSchemaName
allSQLrun = allSQLrun + SQL_RENAME_SCHEMA allSQLrun = allSQLrun + SQL_RENAME_SCHEMA
cur.execute(SQL_RENAME_SCHEMA) cur.execute(SQL_RENAME_SCHEMA)
#print(allSQLrun)
con.commit() con.commit()
for LayerOpen in allTableList: for LayerOpen in allTableList:
self.UnloadLoadLayers(LayerOpen[0], LayerOpen[1], LayerOpen[2]) self.UnloadLoadLayers(LayerOpen[0], LayerOpen[1], LayerOpen[2])
def UnloadLoadLayers(self, OldName, NewSchema, NewTable): def UnloadLoadLayers(self, OldName, NewSchema, NewTable):
allLayers = (QgsProject.instance().mapLayers().values()) allLayers = (QgsProject.instance().mapLayers().values())
listLayers = [] listLayers = []
@@ -210,7 +206,7 @@ class Postgis_Rename(QDialog, EDITOR_CLASS):
host = QgsDataSourceUri(provider.dataSourceUri()).host() host = QgsDataSourceUri(provider.dataSourceUri()).host()
port = QgsDataSourceUri(provider.dataSourceUri()).port() port = QgsDataSourceUri(provider.dataSourceUri()).port()
### Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
+55 -39
View File
@@ -3,13 +3,13 @@
import configparser import configparser
import shutil import shutil
import tempfile import tempfile
import base64 # import base64
import psycopg2 # import psycopg2
import psycopg2.extras # import psycopg2.extras
import os import os
from os.path import abspath, join, pardir, dirname from os.path import abspath, join, pardir, dirname
from qgis.core import QgsDataSourceUri from qgis.core import QgsDataSourceUri
from .SQLRequet import * from .SQLRequet import geom, champ_contour, champ_travaux_prevus_multilinestring, champ_travaux_prevus_point, champ_travaux_prevus_multipolygon, champ_vegethab_multipolygon, champ_vegethab_multilinestring, champ_vegethab_point, champ_viergeLigne, champ_viergePoint, champ_viergePolygone
from qgis.PyQt import uic from qgis.PyQt import uic
__copyright__ = "Copyright 2019, 3Liz" __copyright__ = "Copyright 2019, 3Liz"
@@ -109,46 +109,51 @@ def load_ui(*args):
return ui_class return ui_class
def pyperclip(): def pyperclip():
dst = dirname(dirname(__file__)) + "\\tools\\" dst = dirname(dirname(__file__)) + "\\tools\\"
if os.access('N:/', os.R_OK): if os.access('N:/', os.R_OK):
src = 'N:/SI_Systeme d information/Z_QGIS/PLUGIN/PythonSQL.py' src = 'N:/SI_Systeme d information/Z_QGIS/PLUGIN/PythonSQL.py'
try: try:
shutil.copy(src, dst) shutil.copy(src, dst)
except: except FileNotFoundError:
print('404') print('404')
except UnboundLocalError:
print('404')
def send_issues(url, titre, body, labels): def send_issues(url, titre, body, labels):
import requests import requests
import urllib.request
import json import json
import os # import os
import qgis # import qgis
usr = os.environ['USERNAME'] # usr = os.environ['USERNAME']
token = '9d0a4e0bea561710e0728f161f7edf4e5201e112' token = '9d0a4e0bea561710e0728f161f7edf4e5201e112'
url = url + '?token=' + token url = url + '?token=' + token
headers = {'Authorization': 'token ' + token, 'accept': 'application/json', 'Content-Type': 'application/json'} headers = {'Authorization': 'token ' + token, 'accept': 'application/json', 'Content-Type': 'application/json'}
payload = {'title': titre, 'body': body, 'labels': labels} payload = {'title': titre, 'body': body, 'labels': labels}
try: try:
urllib.request.urlopen('https://google.com') urllib.request.urlopen('https://google.com')
binar = True binar = True
except: except ValueError:
binar = False binar = False
r = '' r = ''
if binar: if binar:
r = requests.post(url, data=json.dumps(payload), headers=headers) r = requests.post(url, data=json.dumps(payload), headers=headers)
return r return r
def maj_verif(NAME): def maj_verif(NAME):
import qgis import qgis
import urllib.request import urllib.request
iface = qgis.utils.iface iface = qgis.utils.iface
from qgis.core import Qgis from qgis.core import Qgis
url = qgis.utils.pluginMetadata(NAME,'repository') # url = qgis.utils.pluginMetadata(NAME, 'repository')
# URL = url+'/raw/branch/main/plugins.xml' # URL = url+'/raw/branch/main/plugins.xml'
URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml' URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml'
# print(URL) # print(URL)
@@ -157,7 +162,7 @@ def maj_verif(NAME):
try: try:
urllib.request.urlopen('https://google.com') urllib.request.urlopen('https://google.com')
binar = True binar = True
except: except urllib.error.URLError:
binar = False binar = False
if binar: if binar:
try: try:
@@ -167,20 +172,23 @@ def maj_verif(NAME):
version_plugin = version_web[valeur_version_web:valeur_version_web + len_version] version_plugin = version_web[valeur_version_web:valeur_version_web + len_version]
if version_plugin != version: if version_plugin != version:
iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30) iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30)
except: except urllib.error.URLError:
print("error gitea version ssl") print("error gitea version ssl")
else: else:
iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30) iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30)
def devlog(NAME): def devlog(NAME):
import qgis import qgis
devmaj = '<head><style>* {margin:0; padding:0; }</style></head>' devmaj = '<head><style>* {margin:0; padding:0; }</style></head>'
devmaj = devmaj + qgis.utils.pluginMetadata(NAME, 'changelog') devmaj = devmaj + qgis.utils.pluginMetadata(NAME, 'changelog')
return devmaj return devmaj
def create_contour(self, schema, cur, con, host, port, dbname, user, mdp): def create_contour(self, schema, cur, con, host, port, dbname, user, mdp):
### Creation de la table contour # Creation de la table contour
if self.couche_contour.isChecked(): # Verifie si la checkbox est cochee # Verifie si la checkbox est cochee
if self.couche_contour.isChecked():
if self.annee_1.text() == 'aaaa' or self.annee_1.text() == '': if self.annee_1.text() == 'aaaa' or self.annee_1.text() == '':
tablename = schema + "_contour" tablename = schema + "_contour"
else: else:
@@ -211,21 +219,24 @@ def create_contour(self,schema,cur,con,host ,port ,dbname ,user ,mdp):
cur.execute(SQL_trigger_area_ha) cur.execute(SQL_trigger_area_ha)
cur.execute(SQL_trigger_date_creation) cur.execute(SQL_trigger_date_creation)
cur.execute(SQL_trigger_date_maj) cur.execute(SQL_trigger_date_maj)
cur.execute(SQL_style) ## Enregistrement du style (comme style par defaut) dans la table layer_styles # Enregistrement du style (comme style par defaut) dans la table layer_styles
cur.execute(SQL_style)
cur.execute(SQL_GRANT_TABLE) cur.execute(SQL_GRANT_TABLE)
con.commit() con.commit()
## Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause) # set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename, geom) uri.setDataSource(schema, tablename, geom)
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres") self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
def create_travaux(self, schema, cur, con, host, port, dbname, user, mdp): def create_travaux(self, schema, cur, con, host, port, dbname, user, mdp):
### Creation de la table travaux prevus # Creation de la table travaux prevus
if self.couche_travaux_prevus.isChecked(): if self.couche_travaux_prevus.isChecked():
# **********Poly # **********Poly
if self.annee_5.text() == 'aaaa' or self.annee_5.text() == '': if self.annee_5.text() == 'aaaa' or self.annee_5.text() == '':
@@ -241,7 +252,6 @@ def create_travaux(self,schema,cur,con,host,port,dbname,user,mdp):
cur.execute(RETURNE) cur.execute(RETURNE)
sequence_name = cur.fetchone()[0] sequence_name = cur.fetchone()[0]
SQL_pkey = "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename[len(schema):] + "_pkey" + " PRIMARY KEY (gid)" SQL_pkey = "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename[len(schema):] + "_pkey" + " PRIMARY KEY (gid)"
SQL_trigger_date_creation = "CREATE TRIGGER date_creation" + tablename + " BEFORE INSERT ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_creation();" SQL_trigger_date_creation = "CREATE TRIGGER date_creation" + tablename + " BEFORE INSERT ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_creation();"
SQL_trigger_date_maj = "CREATE TRIGGER date_maj" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_maj();" SQL_trigger_date_maj = "CREATE TRIGGER date_maj" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.date_maj();"
@@ -259,19 +269,20 @@ def create_travaux(self,schema,cur,con,host,port,dbname,user,mdp):
cur.execute(SQL_trigger_date_maj) cur.execute(SQL_trigger_date_maj)
cur.execute(SQL_trigger_area_m2) cur.execute(SQL_trigger_area_m2)
cur.execute(SQL_trigger_area_ha) cur.execute(SQL_trigger_area_ha)
cur.execute(SQL_style) ## Enregistrement du style (comme style par defaut) dans la table layer_styles # Enregistrement du style (comme style par defaut) dans la table layer_styles
cur.execute(SQL_style)
cur.execute(SQL_GRANT_TABLE) cur.execute(SQL_GRANT_TABLE)
con.commit() con.commit()
## Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause) # set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename, geom) uri.setDataSource(schema, tablename, geom)
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres") self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
# **********ligne # **********ligne
if self.annee_5.text() == 'aaaa' or self.annee_5.text() == '': if self.annee_5.text() == 'aaaa' or self.annee_5.text() == '':
@@ -304,19 +315,20 @@ def create_travaux(self,schema,cur,con,host,port,dbname,user,mdp):
cur.execute(SQL_trigger_date_maj) cur.execute(SQL_trigger_date_maj)
cur.execute(SQL_trigger_length_m) cur.execute(SQL_trigger_length_m)
cur.execute(SQL_trigger_length_km) cur.execute(SQL_trigger_length_km)
cur.execute(SQL_style) ## Enregistrement du style (comme style par defaut) dans la table layer_styles # Enregistrement du style (comme style par defaut) dans la table layer_styles
cur.execute(SQL_style)
cur.execute(SQL_GRANT_TABLE) cur.execute(SQL_GRANT_TABLE)
con.commit() con.commit()
## Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause) # set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename, geom) uri.setDataSource(schema, tablename, geom)
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres") self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
# **********point # **********point
if self.annee_5.text() == 'aaaa' or self.annee_5.text() == '': if self.annee_5.text() == 'aaaa' or self.annee_5.text() == '':
@@ -347,22 +359,24 @@ def create_travaux(self,schema,cur,con,host,port,dbname,user,mdp):
cur.execute(SQL_trigger_date_creation) cur.execute(SQL_trigger_date_creation)
cur.execute(SQL_trigger_date_maj) cur.execute(SQL_trigger_date_maj)
cur.execute(SQL_trigger_coordonnees) cur.execute(SQL_trigger_coordonnees)
cur.execute(SQL_style) ## Enregistrement du style (comme style par defaut) dans la table layer_styles # Enregistrement du style (comme style par defaut) dans la table layer_styles
cur.execute(SQL_style)
cur.execute(SQL_GRANT_TABLE) cur.execute(SQL_GRANT_TABLE)
con.commit() con.commit()
## Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause) # set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename, geom) uri.setDataSource(schema, tablename, geom)
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres") self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
def create_habita(self, schema, cur, con, host, port, dbname, user, mdp): def create_habita(self, schema, cur, con, host, port, dbname, user, mdp):
### Creation de la table habitat # Creation de la table habitat
if self.couche_habitat.isChecked(): if self.couche_habitat.isChecked():
if self.annee_2.text() == 'aaaa' or self.annee_2.text() == '': if self.annee_2.text() == 'aaaa' or self.annee_2.text() == '':
tablename = schema + "_habitat" tablename = schema + "_habitat"
@@ -395,14 +409,14 @@ def create_habita(self,schema,cur,con,host ,port ,dbname ,user ,mdp):
cur.execute(SQL_GRANT_TABLE) cur.execute(SQL_GRANT_TABLE)
con.commit() con.commit()
### Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause) # set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename_1, geom) uri.setDataSource(schema, tablename_1, geom)
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres") self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
tablename_2 = tablename + "_lignes" tablename_2 = tablename + "_lignes"
RETURNE = "SELECT pg_get_serial_sequence('" + schema + "." + tablename_2 + "','gid')" RETURNE = "SELECT pg_get_serial_sequence('" + schema + "." + tablename_2 + "','gid')"
@@ -429,14 +443,14 @@ def create_habita(self,schema,cur,con,host ,port ,dbname ,user ,mdp):
cur.execute(SQL_GRANT_TABLE) cur.execute(SQL_GRANT_TABLE)
con.commit() con.commit()
### Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause) # set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename_2, geom) uri.setDataSource(schema, tablename_2, geom)
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres") self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
tablename_3 = tablename + "_polygones" tablename_3 = tablename + "_polygones"
RETURNE = "SELECT pg_get_serial_sequence('" + schema + "." + tablename_3 + "','gid')" RETURNE = "SELECT pg_get_serial_sequence('" + schema + "." + tablename_3 + "','gid')"
@@ -463,16 +477,18 @@ def create_habita(self,schema,cur,con,host ,port ,dbname ,user ,mdp):
cur.execute(SQL_GRANT_TABLE) cur.execute(SQL_GRANT_TABLE)
con.commit() con.commit()
### Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause) # set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename_3, geom) uri.setDataSource(schema, tablename_3, geom)
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres") self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
def create_vierge(self, schema, cur, con, host, port, dbname, user, mdp): def create_vierge(self, schema, cur, con, host, port, dbname, user, mdp):
### Creation de la table vierge # Creation de la table vierge
if self.couche_vierge.isChecked(): if self.couche_vierge.isChecked():
if self.annee_4.text() == 'aaaa' or self.annee_4.text() == '': if self.annee_4.text() == 'aaaa' or self.annee_4.text() == '':
tablename = schema + "_" + self.nom_couche_vierge.text().lower() tablename = schema + "_" + self.nom_couche_vierge.text().lower()
@@ -521,11 +537,11 @@ def create_vierge(self,schema,cur,con,host ,port ,dbname ,user ,mdp):
con.commit() con.commit()
### Affichage de la table # Affichage de la table
uri = QgsDataSourceUri() uri = QgsDataSourceUri()
# set host name, port, database name, username and password # set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp) uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause) # set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename, geom) uri.setDataSource(schema, tablename, geom)
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres") self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
+3 -3
View File
@@ -50,9 +50,9 @@
<tags>cenra,sicen</tags> <tags>cenra,sicen</tags>
</pyqgis_plugin> </pyqgis_plugin>
<pyqgis_plugin name="CenRa_FLUX" version="3.3"> <pyqgis_plugin name="CenRa_FLUX" version="3.5">
<description>Depot pour les extensiont QGIS du CEN Rhone-Alpes, sur GitHub.</description> <description>Depot pour les extensiont QGIS du CEN Rhone-Alpes, sur GitHub.</description>
<version>3.3</version> <version>3.5</version>
<qgis_minimum_version>3.16</qgis_minimum_version> <qgis_minimum_version>3.16</qgis_minimum_version>
<homepage>https://plateformesig.cenra-outils.org/</homepage> <homepage>https://plateformesig.cenra-outils.org/</homepage>
<file_name>CenRa_FLUX.zip</file_name> <file_name>CenRa_FLUX.zip</file_name>
@@ -61,7 +61,7 @@
<download_url>https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/CenRa_FLUX.zip</download_url> <download_url>https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/CenRa_FLUX.zip</download_url>
<uploaded_by>CEN-Rhone-Alpes</uploaded_by> <uploaded_by>CEN-Rhone-Alpes</uploaded_by>
<create_date>2024-02-06</create_date> <create_date>2024-02-06</create_date>
<update_date>2025-07-23</update_date> <update_date>2025-07-29</update_date>
<experimental>False</experimental> <experimental>False</experimental>
<deprecated>False</deprecated> <deprecated>False</deprecated>
<tags>cenra,flux</tags> <tags>cenra,flux</tags>