Compare commits

..
6 Commits
Author SHA1 Message Date
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
tlaveille 2690220a02 Vue du type vecteur ou raster dans SIG 2025-07-23 16:00:36 +02:00
14 changed files with 455 additions and 658 deletions
+10 -11
View File
@@ -11,7 +11,7 @@ from qgis.utils import iface
import qgis import qgis
#include <QSettings> # include <QSettings>
''' '''
from pg_metadata.connection_manager import ( from pg_metadata.connection_manager import (
store_connections, store_connections,
@@ -24,8 +24,9 @@ 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 .tools.resources import ( from .tools.resources import (
plugin_path, # plugin_path,
resources_path, resources_path,
pyperclip, pyperclip,
maj_verif, maj_verif,
@@ -37,9 +38,6 @@ from .style_invoke import AutoMap_Style
from .about_form import AboutDialog from .about_form import AboutDialog
from qgis.PyQt.QtCore import *
class PgAutoMap: class PgAutoMap:
def __init__(self): def __init__(self):
""" Constructor. """ """ Constructor. """
@@ -51,18 +49,18 @@ class PgAutoMap:
self.dock_action = None self.dock_action = None
self.help_action = None self.help_action = None
plugin_dir = os.path.dirname(__file__) plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\')+1 end_find = plugin_dir.rfind('\\') + 1
global NAME global NAME
NAME = plugin_dir[end_find:] NAME = plugin_dir[end_find:]
maj_verif(NAME) maj_verif(NAME)
# Display About window on first use # Display About window on first use
version = qgis.utils.pluginMetadata('CenRa_AUTOMAP','version') version = qgis.utils.pluginMetadata('CenRa_AUTOMAP', 'version')
s = QSettings() s = QSettings()
versionUse = s.value("automap/version", 1, type=str) versionUse = s.value("automap/version", 1, type=str)
if str(versionUse) != str(version) : if str(versionUse) != str(version):
s.setValue("automap/version", str(version)) s.setValue("automap/version", str(version))
print(versionUse,version) print(versionUse, version)
self.open_about_dialog() self.open_about_dialog()
def initGui(self): def initGui(self):
@@ -80,7 +78,7 @@ class PgAutoMap:
if not self.canvas_editor: if not self.canvas_editor:
self.canvas_editor = AutoMap_Editor() self.canvas_editor = AutoMap_Editor()
self.automap_action = QAction(icon, 'CenRa_AutoMap',None) self.automap_action = QAction(icon, 'CenRa_AutoMap', None)
self.toolBar.addAction(self.automap_action) self.toolBar.addAction(self.automap_action)
self.automap_action.triggered.connect(self.open_editor) self.automap_action.triggered.connect(self.open_editor)
@@ -129,6 +127,7 @@ class PgAutoMap:
""" """
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/'))
@@ -140,7 +139,7 @@ class PgAutoMap:
def unload(self): def unload(self):
""" Unload the plugin. """ """ Unload the plugin. """
if self.canvas_editor: if self.canvas_editor:
iface.removePluginMenu('CenRa_AutoMap',self.automap_action) iface.removePluginMenu('CenRa_AutoMap', self.automap_action)
if self.provider: if self.provider:
QgsApplication.processingRegistry().removeProvider(self.provider) QgsApplication.processingRegistry().removeProvider(self.provider)
+148 -143
View File
@@ -44,7 +44,7 @@ from qgis.core import (
from qgis.PyQt.QtCore import QLocale, QUrl, QDateTime, Qt from qgis.PyQt.QtCore import QLocale, QUrl, QDateTime, Qt
from qgis.PyQt.QtGui import QDesktopServices, QIcon, QColor, QFont, QMovie from qgis.PyQt.QtGui import QDesktopServices, QIcon, QColor, QFont, QMovie
from qgis.PyQt.QtPrintSupport import QPrinter from qgis.PyQt.QtPrintSupport import QPrinter
#from qgis.PyQt.QtWebKitWidgets import QWebPage # from qgis.PyQt.QtWebKitWidgets import QWebPage
from qgis.PyQt.QtWidgets import ( from qgis.PyQt.QtWidgets import (
QDialog, QDialog,
QAction, QAction,
@@ -55,14 +55,13 @@ from qgis.PyQt.QtWidgets import (
QInputDialog, QInputDialog,
QMenu, QMenu,
QToolButton, QToolButton,
QTableWidget, QTableWidget,
QTableWidgetItem, QTableWidgetItem,
QVBoxLayout, QVBoxLayout,
) )
from qgis.PyQt.QtCore import QSettings from qgis.PyQt.QtCore import QSettings
from qgis.PyQt import QtGui from qgis.PyQt import QtGui, QtWidgets
from qgis.PyQt import QtWidgets
from qgis.PyQt.QtXml import QDomDocument from qgis.PyQt.QtXml import QDomDocument
@@ -71,7 +70,7 @@ import glob
from .tools.resources import ( from .tools.resources import (
load_ui, load_ui,
resources_path, resources_path,
send_issues, # send_issues,
) )
from .issues import CenRa_Issues from .issues import CenRa_Issues
@@ -84,48 +83,48 @@ url_ortho = 'http://tiles.craig.fr/ortho/service/?crs=EPSG:2154&featureCount=10&
url_mnt = 'http://tiles.craig.fr/mnt/crs=EPSG:2154&featureCount=10&format=image/png&layers=relief&maxHeight=256&maxWidth=256&styles=&url=http://tiles.craig.fr/mnt' url_mnt = 'http://tiles.craig.fr/mnt/crs=EPSG:2154&featureCount=10&format=image/png&layers=relief&maxHeight=256&maxWidth=256&styles=&url=http://tiles.craig.fr/mnt'
url_pente = 'http://tiles.craig.fr/mnt/crs=EPSG:2154&featureCount=10&format=image/png&layers=pente&maxHeight=256&maxWidth=256&styles=&url=http://tiles.craig.fr/mnt' url_pente = 'http://tiles.craig.fr/mnt/crs=EPSG:2154&featureCount=10&format=image/png&layers=pente&maxHeight=256&maxWidth=256&styles=&url=http://tiles.craig.fr/mnt'
data_source = [ data_source = [
'CENRA', 'CENRA',
'IGN', 'IGN',
'CRAIG', 'CRAIG',
'OpenStreetMap', 'OpenStreetMap',
'Sandre', 'Sandre',
'BRGM', 'BRGM',
'MUSÉUM NATIONAL D’HISTOIRE NATURELLE', 'MUSÉUM NATIONAL D’HISTOIRE NATURELLE',
"Muséum national d'Histoire naturelle", "Muséum national d'Histoire naturelle",
'ONF', 'ONF',
'20xx LPO', '20xx LPO',
'ofb.gouv.fr', 'ofb.gouv.fr',
'Stamen Design', 'Stamen Design',
'MTES', 'MTES',
'MTES', 'MTES',
'FEDER', 'FEDER',
'DREAL Auvergne-Rhône-Alpes', 'DREAL Auvergne-Rhône-Alpes',
'INSEE', 'INSEE',
'DGFiP', 'DGFiP',
'Fédération des Conservatoires d’espaces naturels', 'Fédération des Conservatoires d’espaces naturels',
'Plan cadastral informatisé - Etalab - juillet 202X', 'Plan cadastral informatisé - Etalab - juillet 202X',
'Parcellaire Express - IGN - 202X', 'Parcellaire Express - IGN - 202X',
] ]
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__()
self.setupUi(self) self.setupUi(self)
self.settings = QgsSettings() self.settings = QgsSettings()
self.s = QSettings() self.s = QSettings()
self.setWindowIcon(QtGui.QIcon(resources_path('icons','icon.png'))) self.setWindowIcon(QtGui.QIcon(resources_path('icons', 'icon.png')))
path = '' path = ''
ix = 0 ix = 0
plugin_dir = str(os.path.dirname(os.path.abspath(__file__))).split(os.sep) plugin_dir = str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
for i in plugin_dir[1:]: for i in plugin_dir[1:]:
ix = ix+1 ix = ix + 1
path = path+'/'+i path = path + '/' + i
#self.tabWidget.setStyleSheet('background-image: url('+path+'/tools/bg/Capture.png);') # self.tabWidget.setStyleSheet('background-image: url('+path+'/tools/bg/Capture.png);')
self.verticalScrollBar.hide() self.verticalScrollBar.hide()
self.commandLinkButton.clicked.connect(self.chargement_qpt) self.commandLinkButton.clicked.connect(self.chargement_qpt)
@@ -140,13 +139,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)
@@ -154,35 +152,35 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.template_parameters = { self.template_parameters = {
'Carte_size': None, 'Carte_size': None,
'Carte_locals' : None, 'Carte_locals': None,
'Carte_rotate':None, 'Carte_rotate': None,
'Carte_2_size' : None, 'Carte_2_size': None,
'Carte_2_locals' : None, 'Carte_2_locals': None,
'Carte_2_rotate':None, 'Carte_2_rotate': None,
'Legande_size': None, 'Legande_size': None,
'Legande_locals': None, 'Legande_locals': None,
'Legande_rotate':None, 'Legande_rotate': None,
'Arrow_size': None, 'Arrow_size': None,
'Arrow_locals': None, 'Arrow_locals': None,
'Arrow_rotate':None, 'Arrow_rotate': None,
'Echelle_size': None, 'Echelle_size': None,
'Echelle_locals': None, 'Echelle_locals': None,
'Echelle_rotate':None, 'Echelle_rotate': None,
'Logo_size': None, 'Logo_size': None,
'Logo_locals': None, 'Logo_locals': None,
'Logo_rotate':None, 'Logo_rotate': None,
'Titre_size':None, 'Titre_size': None,
'Titre_locals':None, 'Titre_locals': None,
'Titre_rotate':None, 'Titre_rotate': None,
'Sous_titre_size':None, 'Sous_titre_size': None,
'Sous_titre_locals':None, 'Sous_titre_locals': None,
'Sous_titre_rotate':None, 'Sous_titre_rotate': None,
'Credit_size': None, 'Credit_size': None,
'Credit_locals': None, 'Credit_locals': None,
'Credit_rotate':None, 'Credit_rotate': None,
'Source_size': None, 'Source_size': None,
'Source_locals': None, 'Source_locals': None,
'Source_rotate':None, 'Source_rotate': None,
'Logo_2_size': None, 'Logo_2_size': None,
'Logo_2_locals': None, 'Logo_2_locals': None,
'Logo_2_rotate': None, 'Logo_2_rotate': None,
@@ -198,23 +196,25 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.hide_source() self.hide_source()
self.hide_atlas() self.hide_atlas()
def wheelEvent(self,event): def wheelEvent(self, event):
if (event.angleDelta().y() >= 1): if (event.angleDelta().y() >= 1):
vsb = self.verticalScrollBar.value()+20 vsb = self.verticalScrollBar.value() + 20
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 l, 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 l, 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))
@@ -222,7 +222,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
options = QFileDialog.Options() options = QFileDialog.Options()
options |= QFileDialog.ShowDirsOnly options |= QFileDialog.ShowDirsOnly
folder = QFileDialog.getExistingDirectory(self, "Sélection du dossier parent", options=options) folder = QFileDialog.getExistingDirectory(self, "Sélection du dossier parent", options=options)
return folder+'/' return folder + '/'
def deflogoteck(self): def deflogoteck(self):
folder = self.select_file() folder = self.select_file()
@@ -237,16 +237,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()
@@ -255,7 +259,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
if layeritem.name() == 'SuperFont': if layeritem.name() == 'SuperFont':
myGroup = layerAll[xl] myGroup = layerAll[xl]
layername = True layername = True
xl = xl+1 xl = xl + 1
if layername: if layername:
(QgsProject.instance().layerTreeRoot()).removeChildNode(myGroup) (QgsProject.instance().layerTreeRoot()).removeChildNode(myGroup)
runing = True runing = True
@@ -265,32 +269,36 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
myGroup = (QgsProject.instance().layerTreeRoot()).addGroup("SuperFont") myGroup = (QgsProject.instance().layerTreeRoot()).addGroup("SuperFont")
last_group = 'ortho' last_group = 'ortho'
#OSM_RASTER = QgsRasterLayer(url_osm, 'OpenStreetMap Backgound', 'wms') # OSM_RASTER = QgsRasterLayer(url_osm, 'OpenStreetMap Backgound', 'wms')
ORTHO_RASTER = QgsRasterLayer(url_ortho, 'Orthophoto AURA', 'wms') ORTHO_RASTER = QgsRasterLayer(url_ortho, 'Orthophoto AURA', 'wms')
MNT_RASTER = QgsRasterLayer(url_mnt, 'MNT RGE Alti (<= 1:100000)', 'wms') MNT_RASTER = QgsRasterLayer(url_mnt, 'MNT RGE Alti (<= 1:100000)', 'wms')
PENTE_RASTER = QgsRasterLayer(url_pente, 'Pente RGE Alti 0 à 90°(<= 1:100000)', 'wms') PENTE_RASTER = QgsRasterLayer(url_pente, 'Pente RGE Alti 0 à 90°(<= 1:100000)', 'wms')
#OSM_RASTER.loadNamedStyle(resources_path("font","osm_background.qml")) # OSM_RASTER.loadNamedStyle(resources_path("font", "osm_background.qml"))
ORTHO_RASTER.loadNamedStyle(resources_path("font","ortho_aura.qml")) ORTHO_RASTER.loadNamedStyle(resources_path("font", "ortho_aura.qml"))
MNT_RASTER.loadNamedStyle(resources_path("font","mnt_alti.qml")) MNT_RASTER.loadNamedStyle(resources_path("font", "mnt_alti.qml"))
#QgsProject.instance().addMapLayer(OSM_RASTER,False) # QgsProject.instance().addMapLayer(OSM_RASTER,False)
QgsProject.instance().addMapLayer(ORTHO_RASTER,False) QgsProject.instance().addMapLayer(ORTHO_RASTER, False)
QgsProject.instance().addMapLayer(MNT_RASTER,False) QgsProject.instance().addMapLayer(MNT_RASTER, False)
QgsProject.instance().addMapLayer(PENTE_RASTER,False) QgsProject.instance().addMapLayer(PENTE_RASTER, False)
#myGroup.addLayer(OSM_RASTER) # myGroup.addLayer(OSM_RASTER)
myGroup.addLayer(ORTHO_RASTER) myGroup.addLayer(ORTHO_RASTER)
myGroup.addLayer(MNT_RASTER) myGroup.addLayer(MNT_RASTER)
myGroup.addLayer(PENTE_RASTER) myGroup.addLayer(PENTE_RASTER)
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()
@@ -299,7 +307,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
if layeritem.name() == 'SuperFont': if layeritem.name() == 'SuperFont':
myGroup = layerAll[xl] myGroup = layerAll[xl]
layername = True layername = True
xl = xl+1 xl = xl + 1
if layername: if layername:
(QgsProject.instance().layerTreeRoot()).removeChildNode(myGroup) (QgsProject.instance().layerTreeRoot()).removeChildNode(myGroup)
runing = True runing = True
@@ -309,21 +317,21 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
last_group = 'osm' last_group = 'osm'
OSM_RASTER = QgsRasterLayer(url_osm, 'OpenStreetMap Backgound', 'wms') OSM_RASTER = QgsRasterLayer(url_osm, 'OpenStreetMap Backgound', 'wms')
#ORTHO_RASTER = QgsRasterLayer(url_ortho, 'Orthophoto AURA', 'wms') # ORTHO_RASTER = QgsRasterLayer(url_ortho, 'Orthophoto AURA', 'wms')
MNT_RASTER = QgsRasterLayer(url_mnt, 'MNT RGE Alti (<= 1:100000)', 'wms') MNT_RASTER = QgsRasterLayer(url_mnt, 'MNT RGE Alti (<= 1:100000)', 'wms')
PENTE_RASTER = QgsRasterLayer(url_pente, 'Pente RGE Alti 0 à 90°(<= 1:100000)', 'wms') PENTE_RASTER = QgsRasterLayer(url_pente, 'Pente RGE Alti 0 à 90°(<= 1:100000)', 'wms')
OSM_RASTER.loadNamedStyle(resources_path("font","osm_background.qml")) OSM_RASTER.loadNamedStyle(resources_path("font", "osm_background.qml"))
#ORTHO_RASTER.loadNamedStyle(resources_path("font","ortho_aura.qml")) # ORTHO_RASTER.loadNamedStyle(resources_path("font","ortho_aura.qml"))
MNT_RASTER.loadNamedStyle(resources_path("font","mnt_alti.qml")) MNT_RASTER.loadNamedStyle(resources_path("font", "mnt_alti.qml"))
QgsProject.instance().addMapLayer(OSM_RASTER,False) QgsProject.instance().addMapLayer(OSM_RASTER, False)
#QgsProject.instance().addMapLayer(ORTHO_RASTER,False) # QgsProject.instance().addMapLayer(ORTHO_RASTER,False)
QgsProject.instance().addMapLayer(MNT_RASTER,False) QgsProject.instance().addMapLayer(MNT_RASTER, False)
QgsProject.instance().addMapLayer(PENTE_RASTER,False) QgsProject.instance().addMapLayer(PENTE_RASTER, False)
myGroup.addLayer(OSM_RASTER) myGroup.addLayer(OSM_RASTER)
#myGroup.addLayer(ORTHO_RASTER) # myGroup.addLayer(ORTHO_RASTER)
myGroup.addLayer(MNT_RASTER) myGroup.addLayer(MNT_RASTER)
myGroup.addLayer(PENTE_RASTER) myGroup.addLayer(PENTE_RASTER)
@@ -365,6 +373,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 +387,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 +405,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()
@@ -427,7 +438,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.comboBox_4.clear() self.comboBox_4.clear()
if self.comboBox_2.currentText() != '': if self.comboBox_2.currentText() != '':
layer = QgsProject.instance().mapLayersByName(self.comboBox_2.currentText())[0] layer = QgsProject.instance().mapLayersByName(self.comboBox_2.currentText())[0]
#BUG sur layer.fields() pas défini sur ce qui est pas vecteur # BUG sur layer.fields() pas défini sur ce qui est pas vecteur
for vfields in layer.fields(): for vfields in layer.fields():
fields.append(vfields.name()) fields.append(vfields.name())
self.comboBox_3.addItems(sorted(fields)) self.comboBox_3.addItems(sorted(fields))
@@ -443,11 +454,11 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
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)
@@ -457,10 +468,10 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
cutLayout = layout_name.index("") cutLayout = layout_name.index("")
except: except:
cutLayout = 0 cutLayout = 0
if cutLayout >= 1: if cutLayout >= 1:
self.layout.setName(layout_name) self.layout.setName(layout_name)
titre_layout_name=layout_name[:cutLayout] titre_layout_name = layout_name[:cutLayout]
else: else:
self.layout.setName(layout_name) self.layout.setName(layout_name)
titre_layout_name = layout_name titre_layout_name = layout_name
@@ -473,11 +484,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)
@@ -499,18 +511,18 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
if self.radioButton_12.isChecked() == 1: if self.radioButton_12.isChecked() == 1:
self.position_map = QgsLayoutItemMap(self.layout) self.position_map = QgsLayoutItemMap(self.layout)
self.position_map.setRect(20, 20, 20, 20) self.position_map.setRect(20, 20, 20, 20)
self.position_map.setExtent(QgsRectangle(641552,6647386, 995856,6331104)) self.position_map.setExtent(QgsRectangle(641552, 6647386, 995856, 6331104))
self.position_map.setFollowVisibilityPreset(True) self.position_map.setFollowVisibilityPreset(True)
self.position_map.setFollowVisibilityPresetName(self.comboBox_6.currentText()) self.position_map.setFollowVisibilityPresetName(self.comboBox_6.currentText())
self.position_map.setItemRotation(self.template_parameters['Carte_2_rotate']) self.position_map.setItemRotation(self.template_parameters['Carte_2_rotate'])
self.position_map.attemptResize(self.template_parameters['Carte_2_size']) self.position_map.attemptResize(self.template_parameters['Carte_2_size'])
self.position_map.attemptMove(self.template_parameters['Carte_2_locals']) self.position_map.attemptMove(self.template_parameters['Carte_2_locals'])
self.position_map.overview().setLinkedMap(self.map_modele_test) self.position_map.overview().setLinkedMap(self.map_modele_test)
#overviewitem = QgsLayoutItemMapOverviewStack(self.position_map) # overviewitem = QgsLayoutItemMapOverviewStack(self.position_map)
#map_overview = self.position_map.overview() # map_overview = self.position_map.overview()
#map_overview.setLinkedMap(self.map_modele_test) # map_overview.setLinkedMap(self.map_modele_test)
#map_overview.setCentered(True) # map_overview.setCentered(True)
#overviewitem.addOverview(map_overview) # overviewitem.addOverview(map_overview)
self.position_map.refresh() self.position_map.refresh()
self.map_modele_test.setFrameEnabled(True) self.map_modele_test.setFrameEnabled(True)
@@ -525,7 +537,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 +554,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,20 +572,18 @@ 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)
logo.setItemRotation(self.template_parameters['Logo_rotate']) logo.setItemRotation(self.template_parameters['Logo_rotate'])
logo.setFixedSize(self.template_parameters['Logo_size']) logo.setFixedSize(self.template_parameters['Logo_size'])
logo.attemptMove(self.template_parameters['Logo_locals']) logo.attemptMove(self.template_parameters['Logo_locals'])
logo.setPicturePath(resources_path("icons","CEN_RA.png")) logo.setPicturePath(resources_path("icons", "CEN_RA.png"))
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 +628,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 +639,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 +655,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 +675,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)
@@ -690,7 +698,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
# ajout de la fleche du Nord # ajout de la fleche du Nord
north = QgsLayoutItemPicture(self.layout) north = QgsLayoutItemPicture(self.layout)
north.setPicturePath(resources_path("mises_en_pages","NorthArrow_02.svg")) north.setPicturePath(resources_path("mises_en_pages", "NorthArrow_02.svg"))
self.layout.addLayoutItem(north) self.layout.addLayoutItem(north)
north.attemptMove(self.template_parameters['Arrow_locals']) north.attemptMove(self.template_parameters['Arrow_locals'])
north.attemptResize(self.template_parameters['Arrow_size']) north.attemptResize(self.template_parameters['Arrow_size'])
@@ -701,16 +709,16 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
if self.radioButton_10.isChecked() == 1: if self.radioButton_10.isChecked() == 1:
text_source = ' ' text_source = ' '
for Item_mComboBox_3 in self.mComboBox_3.checkedItems(): for Item_mComboBox_3 in self.mComboBox_3.checkedItems():
text_source = text_source+Item_mComboBox_3+',' text_source = text_source + Item_mComboBox_3 + ','
text_source = text_source[:-1] text_source = text_source[:-1]
info_text = ["Source :" + text_source][0] info_text = ["Source :" + text_source][0]
else: else:
info_text = ["Source : " + self.lineEdit_4.text()][0] info_text = ["Source : " + self.lineEdit_4.text()][0]
# ajout note info: # ajout note info:
if self.radioButton_14.isChecked() == 1: if self.radioButton_14.isChecked() == 1:
self.s.setValue("automap/prenom_nom",self.lineEdit_5.text()) self.s.setValue("automap/prenom_nom", self.lineEdit_5.text())
prenom_nom = self.s.value("automap/prenom_nom", 1, type=str) prenom_nom = self.s.value("automap/prenom_nom", 1, type=str)
info = ["Réalisation : " + "CEN Rhône-Alpes (" + date.today().strftime("%d/%m/%Y") + ") par "+prenom_nom] info = ["Réalisation : " + "CEN Rhône-Alpes (" + date.today().strftime("%d/%m/%Y") + ") par " + prenom_nom]
else: else:
info = ["Réalisation : " + "CEN Rhône-Alpes (" + date.today().strftime("%d/%m/%Y") + ")"] info = ["Réalisation : " + "CEN Rhône-Alpes (" + date.today().strftime("%d/%m/%Y") + ")"]
credit_text = QgsLayoutItemLabel(self.layout) credit_text = QgsLayoutItemLabel(self.layout)
@@ -736,7 +744,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)
@@ -745,14 +753,14 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
cur_x = self.template_parameters['Logo_2_locals'].x() cur_x = self.template_parameters['Logo_2_locals'].x()
logo_credit.attemptMove(self.template_parameters['Logo_2_locals']) logo_credit.attemptMove(self.template_parameters['Logo_2_locals'])
print(logo_credit.pictureAnchor()) print(logo_credit.pictureAnchor())
#logo_credit.setPictureAnchor(4) # logo_credit.setPictureAnchor(4)
self.template_parameters['Logo_2_locals'].setX(cur_x+(logo_div/len_item)) self.template_parameters['Logo_2_locals'].setX(cur_x + (logo_div / len_item))
logo_credit.setFixedSize(self.template_parameters['Logo_2_size']) logo_credit.setFixedSize(self.template_parameters['Logo_2_size'])
if logo_run[0] == ' ': if logo_run[0] == ' ':
logo_credit.setPicturePath(self.s.value("automap/logoteck", 1, type=str)+logo_run[1:]) logo_credit.setPicturePath(self.s.value("automap/logoteck", 1, type=str) + logo_run[1:])
else: else:
logo_credit.setPicturePath(resources_path("logo_library",logo_run)) logo_credit.setPicturePath(resources_path("logo_library", logo_run))
logo_credit.setId('logo_'+logo_run) logo_credit.setId('logo_' + logo_run)
logo_credit.setBackgroundEnabled(True) logo_credit.setBackgroundEnabled(True)
logo_credit.setBackgroundColor(QColor(255, 255, 255, 130)) logo_credit.setBackgroundColor(QColor(255, 255, 255, 130))
self.layout.addLayoutItem(logo_credit) self.layout.addLayoutItem(logo_credit)
@@ -767,33 +775,31 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
self.QMBquestion.setWindowTitle(u"Attention !") self.QMBquestion.setWindowTitle(u"Attention !")
self.QMBquestion.setIcon(QMessageBox.Icon.Warning) self.QMBquestion.setIcon(QMessageBox.Icon.Warning)
self.QMBquestion.setText("Mise en page existante, la mise en page va être écrasée !") self.QMBquestion.setText("Mise en page existante, la mise en page va être écrasée !")
self.QMBquestion.setStandardButtons(QMessageBox.StandardButton(0x00004000)|QMessageBox.StandardButton(0x00010000)) self.QMBquestion.setStandardButtons(QMessageBox.StandardButton(0x00004000) | QMessageBox.StandardButton(0x00010000))
self.QMBquestion.addButton(QPushButton('Autre mise en page'),QMessageBox.ButtonRole(0)) self.QMBquestion.addButton(QPushButton('Autre mise en page'), QMessageBox.ButtonRole(0))
self.QMBquestion = self.QMBquestion.exec() self.QMBquestion = self.QMBquestion.exec()
#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 = []
for AddArrayManager in project.layoutManager().layouts(): for AddArrayManager in project.layoutManager().layouts():
arrayManager.append(AddArrayManager.name()) arrayManager.append(AddArrayManager.name())
arrayManager.sort() arrayManager.sort()
for LayoutNAME in arrayManager: for LayoutNAME in arrayManager:
if LayoutNAME == layout_name: if LayoutNAME == layout_name:
LayoutCOUNT = LayoutCOUNT+1 LayoutCOUNT = LayoutCOUNT + 1
if LayoutNAME == layout_name+""+str(LayoutCOUNT): if LayoutNAME == layout_name + "" + str(LayoutCOUNT):
LayoutCOUNT=LayoutCOUNT+1 LayoutCOUNT = LayoutCOUNT + 1
layout_name = (layout_name+""+str(LayoutCOUNT)) layout_name = (layout_name + "" + str(LayoutCOUNT))
self.layout.setName(layout_name) self.layout.setName(layout_name)
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)
@@ -814,7 +820,7 @@ class AutoMap_Editor(QDialog, EDITOR_CLASS):
except: except:
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,15 +850,14 @@ 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)
bar_echelle.setUnitLabel("km") bar_echelle.setUnitLabel("km")
bar_echelle.setUnitsPerSegment(round((echelle.scale()*0.04)/1000)) bar_echelle.setUnitsPerSegment(round((echelle.scale() * 0.04) / 1000))
else: else:
bar_echelle.setUnits(QgsUnitTypes.DistanceMeters) bar_echelle.setUnits(QgsUnitTypes.DistanceMeters)
bar_echelle.setUnitLabel("m") bar_echelle.setUnitLabel("m")
bar_echelle.setUnitsPerSegment(round(echelle.scale()*0.04)) bar_echelle.setUnitsPerSegment(round(echelle.scale() * 0.04))
bar_echelle.update() bar_echelle.update()
+22 -17
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 (
@@ -27,7 +21,7 @@ from qgis.PyQt.QtWidgets import (
QInputDialog, QInputDialog,
QMenu, QMenu,
QToolButton, QToolButton,
QTableWidget, QTableWidget,
QTableWidgetItem, QTableWidgetItem,
) )
from qgis.utils import iface from qgis.utils import iface
@@ -35,21 +29,27 @@ 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__()
self.setupUi(self) self.setupUi(self)
self.settings = QgsSettings() self.settings = QgsSettings()
#place connect here # place connect here
self.annuler_button.clicked.connect(self.close) self.annuler_button.clicked.connect(self.close)
self.ok_button.clicked.connect(self.run_sendissues) self.ok_button.clicked.connect(self.run_sendissues)
@@ -63,17 +63,22 @@ 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
url = qgis.utils.pluginMetadata(NAME,'tracker') url = qgis.utils.pluginMetadata(NAME, 'tracker')
print(text_message) print(text_message)
send_info = send_issues(url,text_titre,text_message,statu) send_info = send_issues(url, text_titre, text_message, statu)
code = send_info.status_code code = send_info.status_code
print(code) print(code)
else: else:
+12 -17
View File
@@ -4,28 +4,25 @@ __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
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 .flux_editor import Flux_Editor
from .about_form import AboutDialog from .about_form import AboutDialog
from qgis.PyQt.QtCore import *
class PgFlux: class PgFlux:
def __init__(self): def __init__(self):
@@ -37,18 +34,18 @@ class PgFlux:
self.dock_action = None self.dock_action = None
self.help_action = None self.help_action = None
plugin_dir = os.path.dirname(__file__) plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\')+1 end_find = plugin_dir.rfind('\\') + 1
global NAME global NAME
NAME = plugin_dir[end_find:] NAME = plugin_dir[end_find:]
maj_verif(NAME) maj_verif(NAME)
# Display About window on first use # Display About window on first use
version = qgis.utils.pluginMetadata('CenRa_FLUX','version') version = qgis.utils.pluginMetadata('CenRa_FLUX', 'version')
s = QSettings() s = QSettings()
versionUse = s.value("flux/version", 1, type=str) versionUse = s.value("flux/version", 1, type=str)
if str(versionUse) != str(version) : if str(versionUse) != str(version):
s.setValue("flux/version", str(version)) s.setValue("flux/version", str(version))
print(versionUse,version) print(versionUse, version)
self.open_about_dialog() self.open_about_dialog()
def initGui(self): def initGui(self):
@@ -65,13 +62,11 @@ 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)
self.flux_editor.setEnabled(False) self.flux_editor.setEnabled(False)
if os.access('N:/',os.R_OK): if os.access('N:/', os.R_OK):
self.flux_editor.setEnabled(True) self.flux_editor.setEnabled(True)
def open_about_dialog(self): def open_about_dialog(self):
@@ -80,6 +75,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/'))
@@ -91,8 +87,7 @@ class PgFlux:
def unload(self): def unload(self):
""" Unload the plugin. """ """ Unload the plugin. """
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)
+2 -2
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
@@ -43,4 +43,4 @@ class AboutDialog(QDialog, ABOUT_FORM_CLASS):
Run some actions when Run some actions when
the user closes the dialog the user closes the dialog
""" """
self.close() self.close()
+195 -410
View File
@@ -2,63 +2,69 @@
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
itemIconRaster = QTableWidgetItem()
icon = QIcon()
icon.addPixmap(QtGui.QPixmap(resources_path('icons', 'mIconRaster.svg')), QIcon.Mode(0), QIcon.State(1))
itemIconRaster.setIcon(icon)
itemIconVecteur = QTableWidgetItem()
icon = QIcon()
icon.addPixmap(QtGui.QPixmap(resources_path('icons', 'mIconVecteur.svg')), QIcon.Mode(0), QIcon.State(1))
itemIconVecteur.setIcon(icon)
try: try:
account = login_base('account') account = login_base('account')
user = account[0] user = account[0]
@@ -69,142 +75,32 @@ try:
sigdb = account[5] sigdb = account[5]
refdb = account[6] refdb = account[6]
except NameError:
print('Fails to login DB for account')
except:
print('')
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__()
self.setupUi(self) self.setupUi(self)
self.settings = QgsSettings() self.settings = QgsSettings()
self.s = QSettings() self.s = QSettings()
self.setWindowIcon(QtGui.QIcon(resources_path('icons','icon.png'))) self.setWindowIcon(QtGui.QIcon(resources_path('icons', 'icon.png')))
self.first_start = None self.first_start = None
self.iface = iface self.iface = iface
self.label_3.setPixmap(QtGui.QPixmap(resources_path('ui','logo.png'))) self.label_3.setPixmap(QtGui.QPixmap(resources_path('ui', 'logo.png')))
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")
self.comboBox_2.addItem('REF') self.comboBox_2.addItem('REF')
self.comboBox.currentIndexChanged.connect(self.initialisation_flux) self.comboBox.currentIndexChanged.connect(self.initialisation_flux)
@@ -215,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('')
@@ -228,21 +124,18 @@ 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()
def mousePressEvent(self, event): def mousePressEvent(self, event):
global DeBUG global DeBUG
if 330 <= event.pos().x() <= 560 and 5 <= event.pos().y() <= 75: if 330 <= event.pos().x() <= 560 and 5 <= event.pos().y() <= 75:
DeBUG = DeBUG+1 DeBUG = DeBUG + 1
if DeBUG == 3: if DeBUG == 3:
DeBUG = 0 DeBUG = 0
self.ModeDeBUG() self.ModeDeBUG()
@@ -250,131 +143,17 @@ 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()
bd_origine=self.comboBox_2.currentText() bd_origine = self.comboBox_2.currentText()
if bd_origine == 'REF': if bd_origine == 'REF':
self.run_ref() self.run_ref()
if bd_origine == 'SIG': if bd_origine == 'SIG':
@@ -383,17 +162,17 @@ var Travaux = L.geoJSON(TravauxJSON,{
def run_ref(self): def run_ref(self):
"""Run method that performs all the real work""" """Run method that performs all the real work"""
while self.tableWidget_2.rowCount() > 0: while self.tableWidget_2.rowCount() > 0:
self.tableWidget_2.removeRow(self.tableWidget_2.rowCount()-1) self.tableWidget_2.removeRow(self.tableWidget_2.rowCount() - 1)
# print(self.tableWidget_2.rowCount()) # print(self.tableWidget_2.rowCount())
global cur,con,dbtype global cur, con, dbtype
dbtype=refdb dbtype = refdb
con = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbtype+" user=" + user + " password=" + mdp) con = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + dbtype + " user=" + user + " password=" + mdp)
cur = con.cursor(cursor_factory = psycopg2.extras.DictCursor) cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
self.initialisation_flux() self.initialisation_flux()
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()
@@ -408,16 +187,16 @@ var Travaux = L.geoJSON(TravauxJSON,{
def run_sig(self): def run_sig(self):
"""Run method that performs all the real work""" """Run method that performs all the real work"""
while self.tableWidget_2.rowCount() > 0: while self.tableWidget_2.rowCount() > 0:
self.tableWidget_2.removeRow(self.tableWidget_2.rowCount()-1) self.tableWidget_2.removeRow(self.tableWidget_2.rowCount() - 1)
global cur,con,dbtype global cur, con, dbtype
dbtype=sigdb dbtype = sigdb
con = psycopg2.connect("host=" + host + " port=" + port + " dbname="+dbtype+" user=" + user + " password=" + mdp) con = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + dbtype + " user=" + user + " password=" + mdp)
cur = con.cursor(cursor_factory = psycopg2.extras.DictCursor) cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
self.initialisation_flux() self.initialisation_flux()
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()
@@ -432,133 +211,132 @@ 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)
if self.comboBox.currentText() == 'toutes les catégories': if self.comboBox.currentText() == 'toutes les catégories':
custom_list=schemaname_list custom_list = schemaname_list
elif self.comboBox.currentText() == 'travaux': elif self.comboBox.currentText() == 'travaux':
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:
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
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;""" where schemaname like '""" + str(self.comboBox.currentText()) + """' order by schemaname,tablename;"""
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';"""
list_raster = cur.fetchall() cur.execute(SQLcountRaster)
RasterList = [] RasterIF = len(cur.fetchall())
for rasterFind in list_raster:
RasterList.append(rasterFind[0]) if RasterIF == 1:
SQLloadRaster = """SELECT concat(r_table_schema,'.',r_table_name) from public.raster_columns; """
cur.execute(SQLloadRaster)
list_raster = cur.fetchall()
RasterList = []
for rasterFind in list_raster:
RasterList.append(rasterFind[0])
else:
RasterList = []
self.tableWidget.setRowCount(len(list_schema)) self.tableWidget.setRowCount(len(list_schema))
self.tableWidget.setColumnCount(3) self.tableWidget.setColumnCount(4)
i=0 i = 0
for value in list_schema: for value in list_schema:
if dbtype == sigdb: if dbtype == sigdb:
type_val = str(value[0])[1:3] type_val = str(value[0])[1:3]
schema_name=str(value[0])[4:] schema_name = str(value[0])[4:]
table_name=str(value[1][len(value[0])+1:]) table_name = str(value[1][len(value[0]) + 1:])
if value[0] == value[1][:len(value[0])]: if value[0] == value[1][:len(value[0])]:
table_name=str(value[1][len(value[0])+1:]) table_name = str(value[1][len(value[0]) + 1:])
else: else:
table_name=str(value[1]) table_name = str(value[1])
else: else:
type_val = '' type_val = ''
schema_name=str(value[0]) schema_name = str(value[0])
table_name=str(value[1]) table_name = str(value[1])
if type_val == 'fo': if type_val == 'fo':
type_val=str(value[0])[1:5] type_val = str(value[0])[1:5]
schema_name=str(value[0])[6:] schema_name = str(value[0])[6:]
if value[0] == value[1][:len(value[0])]: if value[0] == value[1][:len(value[0])]:
table_name=str(value[1][len(value[0])+1:]) table_name = str(value[1][len(value[0]) + 1:])
else: else:
table_name=str(value[1]) table_name = str(value[1])
elif type_val == 'ra': elif type_val == 'ra':
type_val='travaux' type_val = 'travaux'
schema_name=str(value[0]) schema_name = str(value[0])
table_name=str(value[1]) table_name = str(value[1])
elif type_val != '00' and type_val != '01' and type_val != '07' and type_val != '26' and type_val != '42' and type_val != '69' and type_val != 'ra': elif type_val != '00' and type_val != '01' and type_val != '07' and type_val != '26' and type_val != '42' and type_val != '69' and type_val != 'ra':
if dbtype == refdb: type_val = 'agregation'
if (schema_name+'.'+table_name) in RasterList: schema_name = str(value[0])
SVG = 'mIconRaster.svg' table_name = str(value[1])
else:
SVG = 'mIconWfs.svg'
itemIcon = QTableWidgetItem()
icon = QIcon()
icon.addPixmap(QtGui.QPixmap(resources_path('icons',SVG)), QIcon.Mode(0), QIcon.State(1))
itemIcon.setIcon(icon)
else: if (str(value[0]) + '.' + str(value[1])) in RasterList:
type_val='agregation' SVG = 'mIconRaster.svg'
schema_name=str(value[0])
table_name=str(value[1])
item = QTableWidgetItem(type_val)
if dbtype == refdb:
self.tableWidget.setItem(i,0,itemIcon)
else: else:
self.tableWidget.setCellWidget(i,0,None) SVG = 'mIconVecteur.svg'
self.tableWidget.setItem(i,0,item)
itemIcon = QTableWidgetItem()
icon = QIcon()
icon.addPixmap(QtGui.QPixmap(resources_path('icons', SVG)), QIcon.Mode(0), QIcon.State(1))
itemIcon.setIcon(icon)
self.tableWidget.setItem(i, 0, itemIcon)
item = QTableWidgetItem(type_val)
self.tableWidget.setItem(i, 1, item)
item = QTableWidgetItem(schema_name) item = QTableWidgetItem(schema_name)
self.tableWidget.setItem(i,1,item) self.tableWidget.setItem(i, 2, item)
item = QTableWidgetItem(table_name) item = QTableWidgetItem(table_name)
self.tableWidget.setItem(i,2,item) self.tableWidget.setItem(i, 3, item)
i=i+1 i = i + 1
self.tableWidget.setColumnWidth(0, 20) self.tableWidget.setColumnWidth(0, 20)
self.tableWidget.setColumnWidth(1, 300) self.tableWidget.setColumnWidth(1, 70)
self.tableWidget.setColumnWidth(2, 300) self.tableWidget.setColumnWidth(2, 300)
self.tableWidget.setHorizontalHeaderLabels(["Code","Schema","Table"]) self.tableWidget.setColumnWidth(3, 300)
self.tableWidget.setHorizontalHeaderLabels(["Type", "Code", "Schema", "Table"])
def selection_flux(self): def selection_flux(self):
selected_row = 0 selected_row = 0
selected_items = self.tableWidget.selectedItems() selected_items = self.tableWidget.selectedItems()
# Assuming you want to compare items in the first column for uniqueness # Assuming you want to compare items in the first column for uniqueness
svgTake = (selected_items[2].tableWidget().cellWidget(0,0)) # svgTake = (selected_items[2].tableWidget().cellWidget(0,0))
new_item_text = selected_items[2].text() new_item_text = selected_items[3].text()
if not self.item_already_exists(new_item_text): if not self.item_already_exists(new_item_text):
self.tableWidget_2.insertRow(selected_row) self.tableWidget_2.insertRow(selected_row)
for column in range(self.tableWidget.columnCount()): for column in range(self.tableWidget.columnCount()):
cloned_item = selected_items[column].clone() cloned_item = selected_items[column].clone()
self.tableWidget_2.setHorizontalHeaderLabels(["Code","Schema", "Table"]) self.tableWidget_2.setHorizontalHeaderLabels(["Type", "Code", "Schema", "Table"])
self.tableWidget_2.setColumnCount(3) self.tableWidget_2.setColumnCount(4)
self.tableWidget_2.setItem(selected_row, column, cloned_item) self.tableWidget_2.setItem(selected_row, column, cloned_item)
self.tableWidget_2.setColumnWidth(0, 50) self.tableWidget_2.setColumnWidth(0, 20)
self.tableWidget_2.setColumnWidth(1, 300) self.tableWidget_2.setColumnWidth(1, 70)
self.tableWidget_2.setColumnWidth(2, 300) self.tableWidget_2.setColumnWidth(2, 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:
self.QMBquestion = QMessageBox.question(iface.mainWindow(), u"Attention !", self.QMBquestion = QMessageBox.question(iface.mainWindow(), u"Attention !",
"Le nombre de flux à charger en une seule fois est limité à 5 pour des questions de performances. Souhaitez vous tout de même charger les " + str( "Le nombre de flux à charger en une seule fois est limité à 5 pour des questions de performances. Souhaitez vous tout de même charger les " + str(
self.tableWidget_2.rowCount()) + " flux sélectionnés ? (risque de plantage de QGIS)", self.tableWidget_2.rowCount()) + " flux sélectionnés ? (risque de plantage de QGIS)",
QMessageBox.StandardButton(0x00004000)|QMessageBox.StandardButton(0x00010000)) QMessageBox.StandardButton(0x00004000) | QMessageBox.StandardButton(0x00010000))
if self.QMBquestion == QMessageBox.StandardButton(0x00004000): if self.QMBquestion == QMessageBox.StandardButton(0x00004000):
self.chargement_flux() self.chargement_flux()
@@ -567,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):
uri = QgsDataSourceUri()
uri.setConnection(host ,port ,sigdb ,user ,mdp)
if (schema+'.'+table) in RasterList: """
def openPostGIS(self, schema, table):
uri = QgsDataSourceUri()
uri.setConnection(host, port, sigdb, user, mdp)
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')
@@ -583,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 = {
@@ -599,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:
@@ -613,27 +391,27 @@ 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, 0).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,0).text() code = self.tableWidget_2.item(row, 1).text()
schema = '_'+code+'_'+self.tableWidget_2.item(row,1).text() schema = '_' + code + '_' + self.tableWidget_2.item(row, 2).text()
if code == 'travaux' or code == 'agregation': if code == 'travaux' or code == 'agregation':
schema = self.tableWidget_2.item(row,1).text() schema = self.tableWidget_2.item(row, 2).text()
table = self.tableWidget_2.item(row,2).text() table = self.tableWidget_2.item(row, 3).text()
else: else:
table = self.tableWidget_2.item(row,2).text() table = self.tableWidget_2.item(row, 3).text()
table = schema+'_'+table table = schema + '_' + table
if dbtype == refdb: elif dbtype == refdb:
# code = self.tableWidget_2.item(row,0).text() # code = self.tableWidget_2.item(row,1).text()
schema = self.tableWidget_2.item(row,1).text() schema = self.tableWidget_2.item(row, 2).text()
table = self.tableWidget_2.item(row,2).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)
# nom du schéma à remplacer: "hydrographie" à supprimer et mettre "couches_collaboratives" lorsqu'on aura regroupé les couches à modifier dans un même schéma # nom du schéma à remplacer: "hydrographie" à supprimer et mettre "couches_collaboratives" lorsqu'on aura regroupé les couches à modifier dans un même schéma
if (schema + '.' + table) in RasterList:
if (schema+'.'+table) in RasterList:
uri.setDataSource(schema, table, "rast") uri.setDataSource(schema, table, "rast")
uri.setKeyColumn('rid') uri.setKeyColumn('rid')
uri.setSrid('2154') uri.setSrid('2154')
@@ -644,7 +422,7 @@ var Travaux = L.geoJSON(TravauxJSON,{
uri.setKeyColumn('gid') uri.setKeyColumn('gid')
# Chargement de la couche PostGIS # Chargement de la couche PostGIS
geom_type ='SELECT right(st_geometrytype(geom),-3) as a FROM '+schema+'.'+table+' GROUP BY a' geom_type = 'SELECT right(st_geometrytype(geom),-3) as a FROM ' + schema + '.' + table + ' GROUP BY a'
cur.execute(geom_type) cur.execute(geom_type)
list_typegeom = cur.fetchall() list_typegeom = cur.fetchall()
if len(list_typegeom) > 1: if len(list_typegeom) > 1:
@@ -661,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
@@ -671,7 +449,8 @@ var Travaux = L.geoJSON(TravauxJSON,{
# Ajout de la couche au canevas QGIS # Ajout de la couche au canevas QGIS
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)
@@ -688,7 +467,7 @@ var Travaux = L.geoJSON(TravauxJSON,{
self.comboBox.addItem('form') self.comboBox.addItem('form')
if dbtype == refdb: if dbtype == refdb:
self.toolButton.setEnabled(0) self.toolButton.setEnabled(0)
custom_list=schemaname_distinct custom_list = schemaname_distinct
cur.execute(custom_list) cur.execute(custom_list)
list_schema = cur.fetchall() list_schema = cur.fetchall()
self.comboBox.clear() self.comboBox.clear()
@@ -698,7 +477,7 @@ var Travaux = L.geoJSON(TravauxJSON,{
def filtre_dynamique(self, filter_text): def filtre_dynamique(self, filter_text):
if filter_text.find(' ') >= 0: if filter_text.find(' ') >= 0:
filter_text=filter_text.replace(" ","_") filter_text = filter_text.replace(" ", "_")
for i in range(self.tableWidget.rowCount()): for i in range(self.tableWidget.rowCount()):
for j in range(self.tableWidget.columnCount()): for j in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(i, j) item = self.tableWidget.item(i, j)
@@ -709,14 +488,14 @@ var Travaux = L.geoJSON(TravauxJSON,{
def getCanevas(self): def getCanevas(self):
poly = iface.mapCanvas().extent() poly = iface.mapCanvas().extent()
geom = (str(poly.xMinimum())+','+str(poly.yMinimum())+','+str(poly.xMaximum())+','+str(poly.yMaximum())) geom = (str(poly.xMinimum()) + ',' + str(poly.yMinimum()) + ',' + str(poly.xMaximum()) + ',' + str(poly.yMaximum()))
SQL_GEOM_CONTOUR = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_contour" WHERE st_intersects(geom,ST_MakeEnvelope("""+geom+",2154)) ORDER BY tname" SQL_GEOM_CONTOUR = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_contour" WHERE st_intersects(geom,ST_MakeEnvelope(""" + geom + ",2154)) ORDER BY tname"
SQL_GEOM_HABITAT = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_habitat" WHERE st_intersects(geom,ST_MakeEnvelope("""+geom+",2154)) ORDER BY tname" SQL_GEOM_HABITAT = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_habitat" WHERE st_intersects(geom,ST_MakeEnvelope(""" + geom + ",2154)) ORDER BY tname"
SQL_GEOM_EU_HABITAT = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_eu_habitat" WHERE st_intersects(geom,ST_MakeEnvelope("""+geom+",2154)) ORDER BY tname" SQL_GEOM_EU_HABITAT = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_eu_habitat" WHERE st_intersects(geom,ST_MakeEnvelope(""" + geom + ",2154)) ORDER BY tname"
SQL_GEOM_TRAVAUX_PREVUS_LIGNE = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_travaux_prevus_ligne" WHERE st_intersects(geom,ST_MakeEnvelope("""+geom+",2154)) ORDER BY tname" SQL_GEOM_TRAVAUX_PREVUS_LIGNE = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_travaux_prevus_ligne" WHERE st_intersects(geom,ST_MakeEnvelope(""" + geom + ",2154)) ORDER BY tname"
SQL_GEOM_TRAVAUX_PREVUS_POINT = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_travaux_prevus_point" WHERE st_intersects(geom,ST_MakeEnvelope("""+geom+",2154)) ORDER BY tname" SQL_GEOM_TRAVAUX_PREVUS_POINT = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_travaux_prevus_point" WHERE st_intersects(geom,ST_MakeEnvelope(""" + geom + ",2154)) ORDER BY tname"
SQL_GEOM_TRAVAUX_PREVUS_POLY = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_travaux_prevus_poly" WHERE st_intersects(geom,ST_MakeEnvelope("""+geom+",2154)) ORDER BY tname" SQL_GEOM_TRAVAUX_PREVUS_POLY = """SELECT DISTINCT tschema,tname FROM "_agregation_ra"."_agreg_travaux_prevus_poly" WHERE st_intersects(geom,ST_MakeEnvelope(""" + geom + ",2154)) ORDER BY tname"
cur.execute(SQL_GEOM_CONTOUR) cur.execute(SQL_GEOM_CONTOUR)
TableContour = cur.fetchall() TableContour = cur.fetchall()
@@ -731,11 +510,11 @@ var Travaux = L.geoJSON(TravauxJSON,{
cur.execute(SQL_GEOM_TRAVAUX_PREVUS_POLY) cur.execute(SQL_GEOM_TRAVAUX_PREVUS_POLY)
TableTravauxPoly = cur.fetchall() TableTravauxPoly = cur.fetchall()
TableHaveGeom = sorted(TableContour+TableHabitat+TableEuHabitat+TableTravauxLigne+TableTravauxPoint+TableTravauxPoly) TableHaveGeom = sorted(TableContour + TableHabitat + TableEuHabitat + TableTravauxLigne + TableTravauxPoint + TableTravauxPoly)
row_count = 0 row_count = 0
self.tableWidget.setRowCount(0) self.tableWidget.setRowCount(0)
for e in TableHaveGeom: for e in TableHaveGeom:
cur.execute("""SELECT DISTINCT count(*) FROM pg_catalog.pg_tables WHERE schemaname LIKE '"""+e[0]+"""' AND tablename LIKE '"""+e[1]+"""';""") cur.execute("""SELECT DISTINCT count(*) FROM pg_catalog.pg_tables WHERE schemaname LIKE '""" + e[0] + """' AND tablename LIKE '""" + e[1] + """';""")
TableSomme = cur.fetchall()[0][0] TableSomme = cur.fetchall()[0][0]
if e[0][1:3] != 'fo': if e[0][1:3] != 'fo':
@@ -744,28 +523,34 @@ var Travaux = L.geoJSON(TravauxJSON,{
else: else:
DepName = QTableWidgetItem('form') DepName = QTableWidgetItem('form')
SchemaName = QTableWidgetItem(e[0][6:]) SchemaName = QTableWidgetItem(e[0][6:])
TableName = QTableWidgetItem(e[1][len(e[0])+1:]) TableName = QTableWidgetItem(e[1][len(e[0]) + 1:])
self.tableWidget.insertRow(row_count) self.tableWidget.insertRow(row_count)
self.tableWidget.setItem(row_count,0,DepName)
self.tableWidget.setItem(row_count,1,SchemaName) itemIcon = QTableWidgetItem()
self.tableWidget.setItem(row_count,2,TableName) icon = QIcon()
icon.addPixmap(QtGui.QPixmap(resources_path('icons', 'mIconVecteur.svg')), QIcon.Mode(0), QIcon.State(1))
itemIcon.setIcon(icon)
self.tableWidget.setItem(row_count, 0, itemIcon)
self.tableWidget.setItem(row_count, 1, DepName)
self.tableWidget.setItem(row_count, 2, SchemaName)
self.tableWidget.setItem(row_count, 3, TableName)
if TableSomme == 0: if TableSomme == 0:
for j in range(self.tableWidget.columnCount()): for j in range(self.tableWidget.columnCount()):
self.tableWidget.item(row_count, j).setBackground(QtGui.QColor(246, 185, 73,50)) self.tableWidget.item(row_count, j).setBackground(QtGui.QColor(246, 185, 73, 50))
self.tableWidget.item(row_count,j).setToolTip('Couche dans une autre BD !') self.tableWidget.item(row_count, j).setToolTip('Couche dans une autre BD !')
row_count = row_count+1 row_count = row_count + 1
if self.lineEdit.text() != 'Recherche par mots-clés': if self.lineEdit.text() != 'Recherche par mots-clés':
self.filtre_dynamique(self.lineEdit.text()) self.filtre_dynamique(self.lineEdit.text())
def SwitchGeom(self,vargeom): def SwitchGeom(self, vargeom):
new_object = '[' new_object = '['
obj = vargeom['coordinates'][0][0] obj = vargeom['coordinates'][0][0]
for obj_X in obj: for obj_X in obj:
new_object = new_object+'['+str(obj_X[1])+','+str(obj_X[0])+'],' new_object = new_object + '[' + str(obj_X[1]) + ',' + str(obj_X[0]) + '],'
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()
+19 -15
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,21 +29,25 @@ 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__()
self.setupUi(self) self.setupUi(self)
self.settings = QgsSettings() self.settings = QgsSettings()
#place connect here # place connect here
self.annuler_button.clicked.connect(self.close) self.annuler_button.clicked.connect(self.close)
self.ok_button.clicked.connect(self.run_sendissues) self.ok_button.clicked.connect(self.run_sendissues)
@@ -62,17 +61,22 @@ 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
url = qgis.utils.pluginMetadata(NAME,'tracker') url = qgis.utils.pluginMetadata(NAME, 'tracker')
print(text_message) print(text_message)
send_info = send_issues(url,text_titre,text_message,statu) send_info = send_issues(url, text_titre, text_message, statu)
code = send_info.status_code code = send_info.status_code
print(code) print(code)
else: else:
+2 -4
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.2 version=3.4
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
@@ -19,7 +19,6 @@ email=si_besoin@cen-rhonealpes.fr
hasProcessingProvider=no hasProcessingProvider=no
# Uncomment the following line and add your changelog: # Uncomment the following line and add your changelog:
# changelog= correctif de sécurité: envoi du certificat d'authentification seulement pour les couches fonciercen et drone / intégration des styles RPG geoportail / modification des noms de couches pour plus de clarté
# Tags are comma separated with spaces allowed # Tags are comma separated with spaces allowed
tags=cenra, postgis, database tags=cenra, postgis, database
@@ -33,7 +32,7 @@ icon=icon.png
# experimental flag # experimental flag
experimental=False experimental=False
changelog=<h2>CenRa_FLUX:</h2></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>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
@@ -46,4 +45,3 @@ deprecated=False
# If the plugin can run on QGIS Server. # If the plugin can run on QGIS Server.
server=False server=False
+3 -2
View File
@@ -1,7 +1,8 @@
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'
replace_1 = 'plugin_repositories\\gitea\\url=https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml' replace_1 = 'plugin_repositories\\gitea\\url=https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml'
@@ -18,4 +19,4 @@ def gitea():
# Write the file out again # Write the file out again
with open(file_url, 'w') as file: with open(file_url, 'w') as file:
file.write(filedata) file.write(filedata)
+12 -12
View File
@@ -1,17 +1,17 @@
schemaname_distinct="""SELECT DISTINCT schemaname from pg_catalog.pg_tables schemaname_distinct = """SELECT DISTINCT schemaname 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;""" order by schemaname;"""
schemaname_list_ref="""SELECT schemaname,tablename from pg_catalog.pg_tables 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"
champ_travaux_prevus_multipolygon="""(gid serial NOT NULL, groupe_gestion text, gestion_lib text, id_gestion text, datedebut date, datefin date, commentaire text, surface_m2 double precision, surface_ha double precision, date_creation date, date_maj date, geom geometry(MultiPolygon,2154))""" champ_travaux_prevus_multipolygon = """(gid serial NOT NULL, groupe_gestion text, gestion_lib text, id_gestion text, datedebut date, datefin date, commentaire text, surface_m2 double precision, surface_ha double precision, date_creation date, date_maj date, geom geometry(MultiPolygon,2154))"""
champ_travaux_prevus_multilinestring="""(gid serial NOT NULL, groupe_gestion text, gestion_lib text, id_gestion text, datedebut date, datefin date, commentaire text, longueur_m double precision, longueur_km double precision, date_creation date, date_maj date, geom geometry(MultiLineString,2154))""" champ_travaux_prevus_multilinestring = """(gid serial NOT NULL, groupe_gestion text, gestion_lib text, id_gestion text, datedebut date, datefin date, commentaire text, longueur_m double precision, longueur_km double precision, date_creation date, date_maj date, geom geometry(MultiLineString,2154))"""
champ_travaux_prevus_point = """(gid serial NOT NULL, groupe_gestion text, gestion_lib text, id_gestion text, datedebut date, datefin date, commentaire text, x_wgs84 double precision, y_wgs84 double precision, date_creation date, date_maj date, geom geometry(Point,2154))""" champ_travaux_prevus_point = """(gid serial NOT NULL, groupe_gestion text, gestion_lib text, id_gestion text, datedebut date, datefin date, commentaire text, x_wgs84 double precision, y_wgs84 double precision, date_creation date, date_maj date, geom geometry(Point,2154))"""
champ_viergePolygone = """(gid serial NOT NULL, commentaire text, surface_m2 double precision, surface_ha double precision, geom geometry(MultiPolygon,2154))""" champ_viergePolygone = """(gid serial NOT NULL, commentaire text, surface_m2 double precision, surface_ha double precision, geom geometry(MultiPolygon,2154))"""
@@ -20,7 +20,7 @@ champ_viergePoint = """(gid serial NOT NULL, commentaire text, x_wgs84 double pr
champ_habitat = """(gid serial NOT NULL, cd_cb_01 text, lb_cb97_fr_01 text, occupation_01 integer, cd_cb_02 text, lb_cb97_fr_02 text, occupation_02 integer, cd_cb_03 text, lb_cb97_fr_03 text, occupation_03 integer, milieu_code text, milieu_libelle text, surface_m2 double precision, surface_ha double precision, commentaire text, date_creation date, date_maj date, geom geometry(MultiPolygon,2154))""" champ_habitat = """(gid serial NOT NULL, cd_cb_01 text, lb_cb97_fr_01 text, occupation_01 integer, cd_cb_02 text, lb_cb97_fr_02 text, occupation_02 integer, cd_cb_03 text, lb_cb97_fr_03 text, occupation_03 integer, milieu_code text, milieu_libelle text, surface_m2 double precision, surface_ha double precision, commentaire text, date_creation date, date_maj date, geom geometry(MultiPolygon,2154))"""
champ_contour="""(gid serial NOT NULL, date_creation date, date_maj date, utilisateur character varying, dept character(2), nom character varying, surface_m2 double precision, surface_ha double precision, type_site character varying, type_milieu character varying, date_premier_pg integer, date_debut_pg integer, date_fin_pg integer, referent character varying, gestion_deleguee character varying, terrain_militaire character(3), ens character(3), zh character(3), adapt_pmr character(3), inform character(3), guide character(3), ouverture_public character(3), obs character(3), anim character(3), n2000_anim character(3), contrat_n2000_conseil character(3), n2000_op character(3), contrat_n2000_benef character(3), contrat_agri character(3), bc_habitat integer, bc_amphibien integer, bc_coleoptere integer, bc_crustace integer, bc_mammifere integer, bc_chiroptere integer, bc_mollusque integer, bc_odonate integer, bc_oiseau integer, bc_orthoptere integer, bc_poisson integer, bc_reptile integer, bc_rhopalocere integer, bc_heterocere integer, bc_autre_invertebre integer, bc_flore integer, bc_bryophyte integer, bc_champignon integer, suiv_analyse_sol character(3), suiv_piezo character(3), suiv_climat character(3), suiv_topo character(3), suiv_habitat character(3), suiv_amphibien character(3), suiv_coleoptere character(3), suiv_crustace character(3), suiv_mammifere character(3), suiv_chiroptere character(3), suiv_mollusque character(3), suiv_odonate character(3), suiv_oiseau character(3), suiv_orthoptere character(3), suiv_poisson character(3), suiv_reptile character(3), suiv_rhopalocere character(3), suiv_heterocere character(3), suiv_autre_invertebre character(3), suiv_flore character(3), suiv_bryophyte character(3), suiv_champignon character(3), suiv_analyse_eau character(3), suiv_phenologie character(3), suiv_frequentation character(3), suiv_paysager character(3), suiv_autre character(3), commentaire text, geom geometry(MultiPolygon,2154)) champ_contour = """(gid serial NOT NULL, date_creation date, date_maj date, utilisateur character varying, dept character(2), nom character varying, surface_m2 double precision, surface_ha double precision, type_site character varying, type_milieu character varying, date_premier_pg integer, date_debut_pg integer, date_fin_pg integer, referent character varying, gestion_deleguee character varying, terrain_militaire character(3), ens character(3), zh character(3), adapt_pmr character(3), inform character(3), guide character(3), ouverture_public character(3), obs character(3), anim character(3), n2000_anim character(3), contrat_n2000_conseil character(3), n2000_op character(3), contrat_n2000_benef character(3), contrat_agri character(3), bc_habitat integer, bc_amphibien integer, bc_coleoptere integer, bc_crustace integer, bc_mammifere integer, bc_chiroptere integer, bc_mollusque integer, bc_odonate integer, bc_oiseau integer, bc_orthoptere integer, bc_poisson integer, bc_reptile integer, bc_rhopalocere integer, bc_heterocere integer, bc_autre_invertebre integer, bc_flore integer, bc_bryophyte integer, bc_champignon integer, suiv_analyse_sol character(3), suiv_piezo character(3), suiv_climat character(3), suiv_topo character(3), suiv_habitat character(3), suiv_amphibien character(3), suiv_coleoptere character(3), suiv_crustace character(3), suiv_mammifere character(3), suiv_chiroptere character(3), suiv_mollusque character(3), suiv_odonate character(3), suiv_oiseau character(3), suiv_orthoptere character(3), suiv_poisson character(3), suiv_reptile character(3), suiv_rhopalocere character(3), suiv_heterocere character(3), suiv_autre_invertebre character(3), suiv_flore character(3), suiv_bryophyte character(3), suiv_champignon character(3), suiv_analyse_eau character(3), suiv_phenologie character(3), suiv_frequentation character(3), suiv_paysager character(3), suiv_autre character(3), commentaire text, geom geometry(MultiPolygon,2154))
""" """
champ_vegethab_point = """( champ_vegethab_point = """(
@@ -148,4 +148,4 @@ champ_vegethab_multipolygon = """(
class_name character varying(254) COLLATE pg_catalog."default", class_name character varying(254) COLLATE pg_catalog."default",
geom geometry(MultiPolygon,2154) geom geometry(MultiPolygon,2154)
) )
""" """

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

+26 -21
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,62 +114,65 @@ 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)
version = qgis.utils.pluginMetadata(NAME,'version') version = qgis.utils.pluginMetadata(NAME, 'version')
len_version = len(version) len_version = len(version)
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:
version_web = str(urllib.request.urlopen(URL).read()) version_web = str(urllib.request.urlopen(URL).read())
plugin_num = version_web.find(NAME) plugin_num = version_web.find(NAME)
valeur_version_web = version_web.find('<version>',plugin_num)+9 valeur_version_web = version_web.find('<version>', plugin_num) + 9
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>'
devmaj = devmaj+qgis.utils.pluginMetadata(NAME,'changelog') devmaj = devmaj + qgis.utils.pluginMetadata(NAME, 'changelog')
return devmaj return devmaj
+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
+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.2"> <pyqgis_plugin name="CenRa_FLUX" version="3.4">
<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.2</version> <version>3.4</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-22</update_date> <update_date>2025-07-23</update_date>
<experimental>False</experimental> <experimental>False</experimental>
<deprecated>False</deprecated> <deprecated>False</deprecated>
<tags>cenra,flux</tags> <tags>cenra,flux</tags>