Compare commits

...

6 Commits

Author SHA1 Message Date
6c1af3c61c flake8 issues 2025-07-29 17:01:59 +02:00
d7267c0542 flake8 metabase 2025-07-29 16:56:54 +02:00
fd5d516f14 flake8 sicen 2025-07-29 15:19:47 +02:00
ca1d895eb1 flake8 sicen 2025-07-29 15:16:03 +02:00
e503423e49 flake8 pagerender 2025-07-29 14:34:32 +02:00
3564209574 flake8 copie 2025-07-29 13:58:00 +02:00
22 changed files with 1274 additions and 1390 deletions

View File

@ -4,27 +4,25 @@ __email__ = "info@3liz.org"
from qgis.core import QgsApplication
from qgis.PyQt.QtCore import QCoreApplication, Qt, QTranslator, QUrl
from qgis.PyQt.QtCore import QSettings, QUrl
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
import qgis
#include <QSettings>
import socket
# include <QSettings>
import os
from .about_form import AboutDialog
from .tools.resources import (
plugin_path,
# plugin_path,
pyperclip,
resources_path,
maj_verif,
)
pyperclip()
from .copie_editor import Copie_Editor
from .about_form import AboutDialog
from qgis.PyQt.QtCore import *
class PgCopie:
def __init__(self):
@ -36,18 +34,18 @@ class PgCopie:
self.dock_action = None
self.help_action = None
plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\')+1
end_find = plugin_dir.rfind('\\') + 1
global NAME
NAME = plugin_dir[end_find:]
maj_verif(NAME)
# Display About window on first use
version = qgis.utils.pluginMetadata('CenRa_COPIE','version')
version = qgis.utils.pluginMetadata('CenRa_COPIE', 'version')
s = QSettings()
versionUse = s.value("copie/version", 1, type=str)
if str(versionUse) != str(version) :
if str(versionUse) != str(version):
s.setValue("copie/version", str(version))
print(versionUse,version)
print(versionUse, version)
self.open_about_dialog()
def initGui(self):
@ -65,12 +63,12 @@ class PgCopie:
if not self.action_editor:
self.action_editor = Copie_Editor()
self.copie_editor = QAction(icon, 'Copie',None)
self.copie_editor = QAction(icon, 'Copie', None)
self.toolBar.addAction(self.copie_editor)
self.copie_editor.triggered.connect(self.open_editor)
self.copie_editor.setEnabled(False)
IPAddr=socket.gethostbyname(socket.gethostname())
if os.access('N:/',os.R_OK):
# IPAddr = socket.gethostbyname(socket.gethostname())
if os.access('N:/', os.R_OK):
self.copie_editor.setEnabled(True)
def open_about_dialog(self):
@ -79,6 +77,7 @@ class PgCopie:
"""
dialog = AboutDialog(iface)
dialog.exec()
def open_help():
""" Open the online help. """
QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/'))
@ -90,8 +89,7 @@ class PgCopie:
def unload(self):
""" Unload the plugin. """
if self.action_editor:
iface.removePluginMenu('CenRa_Copie',self.copie_editor)
iface.removePluginMenu('CenRa_Copie', self.copie_editor)
if self.provider:
QgsApplication.processingRegistry().removeProvider(self.provider)

View File

@ -3,7 +3,7 @@ import os.path
from pathlib import Path
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QPixmap
# from qgis.PyQt.QtGui import QPixmap
from qgis.PyQt.QtWidgets import QDialog
from .tools.resources import devlog
@ -43,4 +43,4 @@ class AboutDialog(QDialog, ABOUT_FORM_CLASS):
Run some actions when
the user closes the dialog
"""
self.close()
self.close()

View File

@ -4,78 +4,70 @@ from __future__ import absolute_import
# Import the PyQt and QGIS libraries
from builtins import next
from builtins import str
from builtins import object
import qgis
# from builtins import object
# import qgis
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtWidgets import QAction, QMenu, QDialog
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import QDialog, QMessageBox
from qgis.PyQt import QtGui
from qgis.core import *
from qgis.core import QgsDataSourceUri
import os
from qgis.core import QgsDataSourceUri, QgsSettings, QgsWkbTypes
try:
from .tools.PythonSQL import login_base
except:
except ValueError:
print('Pas de fichier PythonSQL')
from .tools.SQLRequet import *
from .tools.resources import (
load_ui,
resources_path,
send_issues,
# send_issues,
)
from .issues import CenRa_Issues
# from .issues import CenRa_Issues
from qgis.utils import iface
import os.path
import webbrowser, os
import psycopg2
import psycopg2.extras
import base64
# import os
# import os.path
# import webbrowser
# import psycopg2
# import psycopg2.extras
# import base64
EDITOR_CLASS = load_ui('CenRa_Copie_base.ui')
class Copie_Editor(QDialog, EDITOR_CLASS):
class Copie_Editor(QDialog, EDITOR_CLASS):
def __init__(self, parent=None):
_ = parent
super().__init__()
self.setupUi(self)
self.settings = QgsSettings()
self.s = QSettings()
self.setWindowIcon(QtGui.QIcon(resources_path('icons','icon.png')))
self.setWindowIcon(QtGui.QIcon(resources_path('icons', 'icon.png')))
self.iface = iface
def raise_(self):
"""Run method that performs all the real work"""
layer = self.iface.activeLayer()
if layer == None :
#self.iface.messageBar().pushMessage(u"Vous devez sélectionner une table !", level=QgsMessageBar.WARNING, duration=5)
self.iface.messageBar().pushMessage("Ooops", u"Vous devez sélectionner une table !", level=Qgis.Warning, duration=5)
if layer is None:
# self.iface.messageBar().pushMessage(u"Vous devez sélectionner une table !", level=QgsMessageBar.WARNING, duration=5)
self.iface.messageBar().pushMessage("Ooops", u"Vous devez sélectionner une table !", level=1, duration=5)
else :
else:
# Récupération des sources de la couche active
list_sources = layer.source().split(" ")
# dbname
# dbname
source_db = [s for s in list_sources if "dbname" in s][0].split("'")[1]
# schema
# schema
source_schema = [s for s in list_sources if "table" in s][0].split('"')[1]
# tablename
# tablename
source_tablename = [s for s in list_sources if "table" in s][0].split('"')[3]
account = login_base("account")
sigdb = account[5]
if source_db != sigdb:
#self.iface.messageBar().pushMessage(u"Un référentiel ne peut être copié, utilisez les filtres !", level=QgsMessageBar.CRITICAL, duration=10)
self.iface.messageBar().pushMessage("Ooops", u"Vous ne pouvez copier des couches que dans sigXX", level=Qgis.Critical, duration=5)
# self.iface.messageBar().pushMessage(u"Un référentiel ne peut être copié, utilisez les filtres !", level=QgsMessageBar.CRITICAL, duration=10)
self.iface.messageBar().pushMessage("Ooops", u"Vous ne pouvez copier des couches que dans sigXX", level=2, duration=5)
else:
user = account[0]
mdp = account[1]
@ -85,7 +77,7 @@ class Copie_Editor(QDialog, EDITOR_CLASS):
cur = account[7]
con = account[8]
# Creation de la liste des schemas de la base de donnees
# Creation de la liste des schemas de la base de donnees
SQL = """WITH list_schema AS (
SELECT catalog_name, schema_name
FROM information_schema.schemata
@ -102,26 +94,25 @@ class Copie_Editor(QDialog, EDITOR_CLASS):
list_brut = str(next(cur))
list = list_brut [2:-3]
list = list_brut[2:-3]
listItems = list.split(",")
con.close()
self.schema.clear()
self.schema.addItems(listItems)
self.schema.setCurrentIndex(-1) # Pour ne pas commencer la liste au premier schema
# Pour ne pas commencer la liste au premier schema
self.schema.setCurrentIndex(-1)
self.table_source.setText(source_schema + "." + source_tablename) # Affiche le nom de la table source
# Affiche le nom de la table source
self.table_source.setText(source_schema + "." + source_tablename)
# show the dialog
self.show()
# Run the dialog event loop
result = self.exec()
# See if OK was pressed
if result:
#******************************debut script*********************************
# ******************************debut script*********************************
account = login_base("account")
user = account[0]
mdp = account[1]
@ -136,45 +127,45 @@ class Copie_Editor(QDialog, EDITOR_CLASS):
# Récupération des sources de la couche active
list_sources = layer.source().split(" ")
# dbname
# dbname
source_db = [s for s in list_sources if "dbname" in s][0].split("'")[1]
# schema
# schema
source_schema = [s for s in list_sources if "table" in s][0].split('"')[1]
# tablename
# tablename
source_tablename = [s for s in list_sources if "table" in s][0].split('"')[3]
if self.schema.currentIndex() == -1 :
if self.schema.currentIndex() == - 1:
QMessageBox.warning(None, "Oups :", "Veuillez choisir un dossier de destination.")
return
return
schema = self.schema.currentText()
if self.table_destination.text() == '' :
if self.table_destination.text() == '':
QMessageBox.warning(None, "Oups :", "Veuillez choisir un nom de destination.")
return
if self.annee.text() == 'aaaa' or self.annee.text() == '':
return
if self.annee.text() == 'aaaa' or self.annee.text() == '':
tablename = schema + "_" + self.table_destination.text().lower()
else :
else:
tablename = schema + "_" + self.table_destination.text().lower() + "_" + self.annee.text()
tablename_qgis = tablename[1:] # Permet d'enlever le "_", ajouter a la premiere etape, dans qgis
if self.table_vide.isChecked() == 1 :
if self.table_vide.isChecked() == 1:
SQL_table = "CREATE TABLE " + schema + "." + tablename + " AS SELECT * FROM " + source_schema + "." + source_tablename + " LIMIT 0;"
else :
else:
SQL_table = "CREATE TABLE " + schema + "." + tablename + " AS SELECT * FROM " + source_schema + "." + source_tablename
SQL_pkey = "ALTER TABLE " + schema + "." + tablename + " ADD CONSTRAINT " + tablename + "_pkey" + " PRIMARY KEY (gid)"
SQL_sequence_01 = "CREATE SEQUENCE " + schema + "." + tablename + "_gid_seq" + " INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1;"
SQL_sequence_02 = "ALTER TABLE " + schema + "." + tablename + " ALTER COLUMN gid SET DEFAULT nextval(\'" + schema + "." + tablename + "_gid_seq\'::regclass);"
SQL_sequence_02 = "ALTER TABLE " + schema + "." + tablename + " ALTER COLUMN gid SET DEFAULT nextval(\'" + schema + "." + tablename + "_gid_seq\'::regclass);"
SQL_sequence_03 = "SELECT setval(\'" + schema + "." + tablename + "_gid_seq\'::regclass, (SELECT max(gid) AS max_gid FROM " + schema + "." + tablename + "));"
SQL_sequence_04 = "ALTER SEQUENCE " + schema + "." + tablename + "_gid_seq" + " OWNED BY " + schema + "." + tablename + ".gid;"
SQL_trigger_area_m2 = "CREATE TRIGGER area_m2" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_m2();"
SQL_trigger_area_ha = "CREATE TRIGGER area_ha" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_ha();"
SQL_trigger_area_ha = "CREATE TRIGGER area_ha" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.area_ha();"
SQL_trigger_length_m = "CREATE TRIGGER length_m" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.length_m();"
SQL_trigger_length_km = "CREATE TRIGGER length_km" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.length_km();"
SQL_trigger_length_km = "CREATE TRIGGER length_km" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.length_km();"
SQL_trigger_coordonnees = "CREATE TRIGGER coordonnees" + tablename + " BEFORE INSERT OR UPDATE ON " + schema + "." + tablename + " FOR EACH ROW EXECUTE PROCEDURE ref.coordonnees();"
cur.execute(SQL_table)
@ -184,38 +175,38 @@ class Copie_Editor(QDialog, EDITOR_CLASS):
cur.execute(SQL_sequence_03)
cur.execute(SQL_sequence_04)
RETURNE = "SELECT pg_get_serial_sequence('"+schema + "."+ tablename+"','gid')"
RETURNE = "SELECT pg_get_serial_sequence('" + schema + "." + tablename + "','gid')"
cur.execute(RETURNE)
sequence_name = cur.fetchone()[0]
print(sequence_name)
SQL_GRANT_TABLE="GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON "+schema+"."+tablename+" TO grp_sig;GRANT ALL ON SEQUENCE "+sequence_name+" TO grp_qgis;"
SQL_GRANT_TABLE = "GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON " + schema + "." + tablename + " TO grp_qgis;GRANT DELETE, INSERT, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON " + schema + "." + tablename + " TO grp_sig;GRANT ALL ON SEQUENCE " + sequence_name + " TO grp_qgis;"
cur.execute(SQL_GRANT_TABLE)
if layer.wkbType() == QgsWkbTypes.PointGeometry :
if layer.wkbType() == QgsWkbTypes.PointGeometry:
cur.execute(SQL_trigger_coordonnees)
if layer.wkbType() == QgsWkbTypes.LineGeometry :
if layer.wkbType() == QgsWkbTypes.LineGeometry:
cur.execute(SQL_trigger_length_m)
cur.execute(SQL_trigger_length_km)
cur.execute(SQL_trigger_length_km)
if layer.wkbType() == QgsWkbTypes.PolygonGeometry :
if layer.wkbType() == QgsWkbTypes.PolygonGeometry:
cur.execute(SQL_trigger_area_m2)
cur.execute(SQL_trigger_area_ha)
con.commit()
### Affichage de la table
con.commit()
# Affichage de la table
uri = QgsDataSourceUri()
# set host name, port, database name, username and password
uri.setConnection(host ,port ,dbname ,user ,mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename, geom)
# set host name, port, database name, username and password
uri.setConnection(host, port, dbname, user, mdp)
# set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(schema, tablename, "geom")
layer = self.iface.addVectorLayer(uri.uri(), tablename_qgis, "postgres")
con.commit()
con.close()
#self.iface.messageBar().pushMessage("Table \"" + source_schema + "." + source_tablename + u"\" copiée dans \"" + schema + "." + tablename + "\"." , level=QgsMessageBar.INFO, duration=10)
self.iface.messageBar().pushMessage("Bravo!", "Table \"" + source_schema + "." + source_tablename + u"\" copiée dans \"" + schema + "." + tablename + "\".", level=Qgis.Success, duration=5)
# self.iface.messageBar().pushMessage("Table \"" + source_schema + "." + source_tablename + u"\" copiée dans \"" + schema + "." + tablename + "\"." , level=QgsMessageBar.INFO, duration=10)
self.iface.messageBar().pushMessage("Bravo!", "Table \"" + source_schema + "." + source_tablename + u"\" copiée dans \"" + schema + "." + tablename + "\".", level=3, duration=5)
pass

View File

@ -1,141 +0,0 @@
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_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_viergePolygone = """(gid serial NOT NULL, commentaire text, surface_m2 double precision, surface_ha double precision, geom geometry(MultiPolygon,2154))"""
champ_viergeLigne = """(gid serial NOT NULL, commentaire text, longueur_m double precision, longueur_km double precision, geom geometry(MultiLineString,2154))"""
champ_viergePoint = """(gid serial NOT NULL, commentaire text, x_wgs84 double precision, y_wgs84 double precision, geom geometry(Point,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_vegethab_point = """(
gid serial NOT NULL ,
cd_eu_01 character varying(254) COLLATE pg_catalog."default",
lb_eu_01 character varying(254) COLLATE pg_catalog."default",
occupati_1 bigint,
cd_eu_02 character varying(254) COLLATE pg_catalog."default",
lb_eu_02 character varying(254) COLLATE pg_catalog."default",
occupati_2 bigint,
cd_eu_03 character varying(254) COLLATE pg_catalog."default",
lb_eu_03 character varying(254) COLLATE pg_catalog."default",
occupati_3 bigint,
milieu_cod character varying(254) COLLATE pg_catalog."default",
milieu_lib character varying(254) COLLATE pg_catalog."default",
surface_m2 numeric,
surface_ha numeric,
commentair character varying(254) COLLATE pg_catalog."default",
date_creat date,
date_maj date,
num_phyto character varying(254) COLLATE pg_catalog."default",
type_unite character varying(254) COLLATE pg_catalog."default",
dynamique character varying(254) COLLATE pg_catalog."default",
gestio_obs character varying(254) COLLATE pg_catalog."default",
degrad_obs character varying(254) COLLATE pg_catalog."default",
eta_conser character varying(254) COLLATE pg_catalog."default",
clas_phyto character varying(254) COLLATE pg_catalog."default",
alli_phyto character varying(254) COLLATE pg_catalog."default",
syntaxon character varying(254) COLLATE pg_catalog."default",
n2000 character varying(254) COLLATE pg_catalog."default",
lrr_aura character varying(254) COLLATE pg_catalog."default",
lrr_cbna character varying(254) COLLATE pg_catalog."default",
lrr_cbnmc character varying(254) COLLATE pg_catalog."default",
vege_enjeu character varying(254) COLLATE pg_catalog."default",
num_photo character varying(254) COLLATE pg_catalog."default",
nature_obs character varying(254) COLLATE pg_catalog."default",
date_sais date,
s_al_phyto character varying(254) COLLATE pg_catalog."default",
alli_name character varying(254) COLLATE pg_catalog."default",
salli_name character varying(254) COLLATE pg_catalog."default",
class_name character varying(254) COLLATE pg_catalog."default",
geom geometry(Point,2154)
)
"""
champ_vegethab_multilinestring = """(
gid serial NOT NULL ,
cd_eu_01 character varying(254) COLLATE pg_catalog."default",
lb_eu_01 character varying(254) COLLATE pg_catalog."default",
occupati_1 bigint,
cd_eu_02 character varying(254) COLLATE pg_catalog."default",
lb_eu_02 character varying(254) COLLATE pg_catalog."default",
occupati_2 bigint,
cd_eu_03 character varying(254) COLLATE pg_catalog."default",
lb_eu_03 character varying(254) COLLATE pg_catalog."default",
occupati_3 bigint,
milieu_cod character varying(254) COLLATE pg_catalog."default",
milieu_lib character varying(254) COLLATE pg_catalog."default",
surface_m2 numeric,
surface_ha numeric,
commentair character varying(254) COLLATE pg_catalog."default",
date_creat date,
date_maj date,
num_phyto character varying(254) COLLATE pg_catalog."default",
type_unite character varying(254) COLLATE pg_catalog."default",
dynamique character varying(254) COLLATE pg_catalog."default",
gestio_obs character varying(254) COLLATE pg_catalog."default",
degrad_obs character varying(254) COLLATE pg_catalog."default",
eta_conser character varying(254) COLLATE pg_catalog."default",
clas_phyto character varying(254) COLLATE pg_catalog."default",
alli_phyto character varying(254) COLLATE pg_catalog."default",
syntaxon character varying(254) COLLATE pg_catalog."default",
n2000 character varying(254) COLLATE pg_catalog."default",
lrr_aura character varying(254) COLLATE pg_catalog."default",
lrr_cbna character varying(254) COLLATE pg_catalog."default",
lrr_cbnmc character varying(254) COLLATE pg_catalog."default",
vege_enjeu character varying(254) COLLATE pg_catalog."default",
num_photo character varying(254) COLLATE pg_catalog."default",
nature_obs character varying(254) COLLATE pg_catalog."default",
date_sais date,
s_al_phyto character varying(254) COLLATE pg_catalog."default",
alli_name character varying(254) COLLATE pg_catalog."default",
salli_name character varying(254) COLLATE pg_catalog."default",
class_name character varying(254) COLLATE pg_catalog."default",
geom geometry(MultiLineString,2154)
)
"""
champ_vegethab_multipolygon = """(
gid serial NOT NULL ,
cd_eu_01 character varying(254) COLLATE pg_catalog."default",
lb_eu_01 character varying(254) COLLATE pg_catalog."default",
occupati_1 bigint,
cd_eu_02 character varying(254) COLLATE pg_catalog."default",
lb_eu_02 character varying(254) COLLATE pg_catalog."default",
occupati_2 bigint,
cd_eu_03 character varying(254) COLLATE pg_catalog."default",
lb_eu_03 character varying(254) COLLATE pg_catalog."default",
occupati_3 bigint,
milieu_cod character varying(254) COLLATE pg_catalog."default",
milieu_lib character varying(254) COLLATE pg_catalog."default",
surface_m2 numeric,
surface_ha numeric,
commentair character varying(254) COLLATE pg_catalog."default",
date_creat date,
date_maj date,
num_phyto character varying(254) COLLATE pg_catalog."default",
type_unite character varying(254) COLLATE pg_catalog."default",
dynamique character varying(254) COLLATE pg_catalog."default",
gestio_obs character varying(254) COLLATE pg_catalog."default",
degrad_obs character varying(254) COLLATE pg_catalog."default",
eta_conser character varying(254) COLLATE pg_catalog."default",
clas_phyto character varying(254) COLLATE pg_catalog."default",
alli_phyto character varying(254) COLLATE pg_catalog."default",
syntaxon character varying(254) COLLATE pg_catalog."default",
n2000 character varying(254) COLLATE pg_catalog."default",
lrr_aura character varying(254) COLLATE pg_catalog."default",
lrr_cbna character varying(254) COLLATE pg_catalog."default",
lrr_cbnmc character varying(254) COLLATE pg_catalog."default",
vege_enjeu character varying(254) COLLATE pg_catalog."default",
num_photo character varying(254) COLLATE pg_catalog."default",
nature_obs character varying(254) COLLATE pg_catalog."default",
date_sais date,
s_al_phyto character varying(254) COLLATE pg_catalog."default",
alli_name character varying(254) COLLATE pg_catalog."default",
salli_name character varying(254) COLLATE pg_catalog."default",
class_name character varying(254) COLLATE pg_catalog."default",
geom geometry(MultiPolygon,2154)
)
"""

View File

@ -3,9 +3,9 @@
import configparser
import shutil
import tempfile
import base64
import psycopg2
import psycopg2.extras
# import base64
# import psycopg2
# import psycopg2.extras
import os
from os.path import abspath, join, pardir, dirname
@ -108,71 +108,77 @@ def load_ui(*args):
return ui_class
def pyperclip():
dst = dirname(dirname(__file__))+"\\tools\\"
if os.access('N:/',os.R_OK):
dst = dirname(dirname(__file__)) + "\\tools\\"
if os.access('N:/', os.R_OK):
src = 'N:/SI_Systeme d information/Z_QGIS/PLUGIN/PythonSQL.py'
try:
shutil.copy(src, dst)
except:
except FileNotFoundError:
print('404')
except UnboundLocalError:
print('404')
def send_issues(url,titre,body,labels):
def send_issues(url, titre, body, labels):
import requests
import urllib.request
import json
import os
import qgis
# import os
# import qgis
usr = os.environ['USERNAME']
# usr = os.environ['USERNAME']
token = '9d0a4e0bea561710e0728f161f7edf4e5201e112'
url=url+'?token='+token
headers = {'Authorization': 'token ' + token,'accept': 'application/json','Content-Type': 'application/json'}
url = url + '?token=' + token
headers = {'Authorization': 'token ' + token, 'accept': 'application/json', 'Content-Type': 'application/json'}
payload = {'title': titre, 'body': body, 'labels': labels}
try:
urllib.request.urlopen('https://google.com')
binar = True
except:
except ValueError:
binar = False
r = ''
if binar:
r = requests.post(url, data=json.dumps(payload), headers=headers)
return r
def maj_verif(NAME):
import qgis
import urllib.request
iface = qgis.utils.iface
from qgis.core import Qgis
url = qgis.utils.pluginMetadata(NAME,'repository')
#URL = url+'/raw/branch/main/plugins.xml'
# url = qgis.utils.pluginMetadata(NAME, 'repository')
# URL = url+'/raw/branch/main/plugins.xml'
URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml'
# print(URL)
version = qgis.utils.pluginMetadata(NAME,'version')
# print(URL)
version = qgis.utils.pluginMetadata(NAME, 'version')
len_version = len(version)
try:
urllib.request.urlopen('https://google.com')
binar = True
except:
except urllib.error.URLError:
binar = False
if binar:
try:
version_web = str(urllib.request.urlopen(URL).read())
plugin_num = version_web.find(NAME)
valeur_version_web = version_web.find('<version>',plugin_num)+9
version_plugin = version_web[valeur_version_web:valeur_version_web+len_version]
valeur_version_web = version_web.find('<version>', plugin_num) + 9
version_plugin = version_web[valeur_version_web:valeur_version_web + len_version]
if version_plugin != version:
iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30)
except:
except urllib.error.URLError:
print("error gitea version ssl")
else:
iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30)
def devlog(NAME):
import qgis
devmaj = '<head><style>* {margin:0; padding:0; }</style></head>'
devmaj = devmaj+qgis.utils.pluginMetadata(NAME,'changelog')
return devmaj
devmaj = devmaj + qgis.utils.pluginMetadata(NAME, 'changelog')
return devmaj

View File

@ -1,35 +1,13 @@
import os
from qgis.gui import *
# from qgis.gui import *
from qgis.core import (
NULL,
QgsApplication,
QgsDataSourceUri,
QgsProject,
QgsProviderConnectionException,
QgsProviderRegistry,
QgsRasterLayer,
QgsSettings,
QgsVectorLayer,
QgsGeometry,
)
from qgis.PyQt.QtWidgets import (
QDialog,
QAction,
QDockWidget,
QFileDialog,
QInputDialog,
QMenu,
QToolButton,
QTableWidget,
QTableWidgetItem,
)
from qgis.core import QgsSettings
from qgis.PyQt.QtWidgets import QDialog
from qgis.utils import iface
from .tools.resources import (
load_ui,
# resources_path,
send_issues,
)
plugin_dir = os.path.dirname(__file__)
@ -82,11 +60,11 @@ class CenRa_Issues(QDialog, EDITOR_CLASS):
else:
code = 423
if code == 201:
iface.messageBar().pushMessage("Envoyer :", "Votre messages à bien été envoyer.", level=Qgis.Success, duration=20)
iface.messageBar().pushMessage("Envoyer :", "Votre messages à bien été envoyer.", level=0, duration=20)
self.close()
elif code == 422:
iface.messageBar().pushMessage("Erreur :", "Erreur dans le contenu du messages.", level=Qgis.Critical, duration=20)
iface.messageBar().pushMessage("Erreur :", "Erreur dans le contenu du messages.", level=2, duration=20)
elif code == 423:
iface.messageBar().pushMessage("Erreur :", "Pas de sujet sélectionné.", level=Qgis.Critical, duration=20)
iface.messageBar().pushMessage("Erreur :", "Pas de sujet sélectionné.", level=2, duration=20)
elif code == 404:
iface.messageBar().pushMessage("Missing :", "Le serveur de messagerie est injoignable.", level=Qgis.Warning, duration=20)
iface.messageBar().pushMessage("Missing :", "Le serveur de messagerie est injoignable.", level=1, duration=20)

View File

@ -4,14 +4,13 @@ __email__ = "info@3liz.org"
from qgis.core import QgsApplication
from qgis.PyQt.QtCore import QCoreApplication, Qt, QTranslator, QUrl
from qgis.PyQt.QtCore import Qt, QUrl, QSettings
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
import qgis
#include <QSettings>
# include <QSettings>
'''
from pg_metadata.connection_manager import (
store_connections,
@ -24,8 +23,9 @@ from pg_metadata.processing.provider import PgMetadataProvider
from pg_metadata.qgis_plugin_tools.tools.custom_logging import setup_logger
'''
import os
from .about_form import MetabaseAboutDialog
from .tools.resources import (
plugin_path,
# plugin_path,
pyperclip,
resources_path,
maj_verif,
@ -33,10 +33,8 @@ from .tools.resources import (
pyperclip()
from .dock import CenRa_Metabase
from .editor import Metabase_Editor
from .about_form import MetabaseAboutDialog
#from CenRa_Metabase.issues import CenRa_Issues
from qgis.PyQt.QtCore import *
# from CenRa_Metabase.issues import CenRa_Issues
class PgMetadata:
@ -50,42 +48,42 @@ class PgMetadata:
self.dock_action = None
self.help_action = None
plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\')+1
end_find = plugin_dir.rfind('\\') + 1
global NAME
NAME = plugin_dir[end_find:]
maj_verif(NAME)
# Display About window on first use
version = qgis.utils.pluginMetadata('CenRa_METABASE','version')
version = qgis.utils.pluginMetadata('CenRa_METABASE', 'version')
s = QSettings()
versionUse = s.value("metadata/version", 1, type=str)
if str(versionUse) != str(version) :
if str(versionUse) != str(version):
s.setValue("metadata/version", str(version))
print(versionUse,version)
print(versionUse, version)
self.open_about_dialog()
# setup_logger('pg_metadata')
#locale, file_path = setup_translation(
# locale, file_path = setup_translation(
# folder=plugin_path("i18n"), file_pattern="CenRa_Metabase_{}.qm")
#if file_path:
# if file_path:
# self.translator = QTranslator()
# self.translator.load(file_path)
# noinspection PyCallByClass,PyArgumentList
# QCoreApplication.installTranslator(self.translator)
# noinspection PyPep8Naming
#def initProcessing(self):
#""" Add the QGIS Processing provider. """
#if not self.provider:
#self.provider = PgMetadataProvider()
#QgsApplication.processingRegistry().addProvider(self.provider)
# def initProcessing(self):
# """ Add the QGIS Processing provider. """
# if not self.provider:
# self.provider = PgMetadataProvider()
# QgsApplication.processingRegistry().addProvider(self.provider)
# noinspection PyPep8Naming
def initGui(self):
""" Build the plugin GUI. """
#self.initProcessing()
# self.initProcessing()
#self.check_invalid_connection_names()
# self.check_invalid_connection_names()
self.toolBar = iface.addToolBar("CenRa_Metabase")
self.toolBar.setObjectName("CenRa_Metabase")
@ -100,8 +98,7 @@ class PgMetadata:
if not self.editor:
self.editor = Metabase_Editor()
self.editor_action = QAction(icon2, 'CenRa_Metabase',None)
self.editor_action = QAction(icon2, 'CenRa_Metabase', None)
self.toolBar.addAction(self.editor_action)
self.editor_action.triggered.connect(self.open_editor)
@ -159,6 +156,7 @@ class PgMetadata:
"""
dialog = MetabaseAboutDialog(iface)
dialog.exec()
def open_help():
""" Open the online help. """
QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/'))
@ -178,9 +176,9 @@ class PgMetadata:
def unload(self):
""" Unload the plugin. """
#if self.editor:
#iface.removePluginMenu('CenRa_Metabase',self.editor_action)
#self.editor.removeToolBarIcon(self.editor_action)
# if self.editor:
# iface.removePluginMenu('CenRa_Metabase',self.editor_action)
# self.editor.removeToolBarIcon(self.editor_action)
if self.dock:
iface.removeDockWidget(self.dock)
@ -202,7 +200,6 @@ class PgMetadata:
iface.pluginMenu().removeAction(self.dock_action)
del self.dock_action
@staticmethod
def run_tests(pattern='test_*.py', package=None):
"""Run the test inside QGIS."""

View File

@ -3,7 +3,7 @@ import os.path
from pathlib import Path
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QPixmap
# from qgis.PyQt.QtGui import QPixmap
from qgis.PyQt.QtWidgets import QDialog
from .tools.resources import devlog
@ -16,6 +16,7 @@ ABOUT_FORM_CLASS, _ = uic.loadUiType(
)
)
class MetabaseAboutDialog(QDialog, ABOUT_FORM_CLASS):
""" About - Let the user display the about dialog. """
@ -42,4 +43,4 @@ class MetabaseAboutDialog(QDialog, ABOUT_FORM_CLASS):
Run some actions when
the user closes the dialog
"""
self.close()
self.close()

View File

@ -14,48 +14,31 @@ from pathlib import Path
from xml.dom.minidom import parseString
from qgis.core import (
NULL,
QgsApplication,
QgsDataSourceUri,
QgsProject,
QgsProviderConnectionException,
QgsProviderRegistry,
QgsRasterLayer,
QgsSettings,
QgsVectorLayer,
)
from qgis.PyQt.QtCore import QLocale, QUrl
from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtPrintSupport import QPrinter
#from qgis.PyQt.QtWebKitWidgets import QWebPage
# from qgis.PyQt.QtWebKitWidgets import QWebPage
from qgis.PyQt.QtWidgets import (
QDialog,
QAction,
QDockWidget,
QFileDialog,
QInputDialog,
QMenu,
QToolButton,
)
from qgis.gui import *
from qgis.utils import iface
import qgis
'''
from pg_metadata.connection_manager import (
check_pgmetadata_is_installed,
connections_list,
settings_connections_names,
)
'''
try:
from .tools.PythonSQL import login_base
except:
print('Pas de fichier PythonSQL')
from .tools.resources import (
load_ui,
resources_path,
)
try:
from .tools.PythonSQL import login_base
except ValueError:
print('Pas de fichier PythonSQL')
DOCK_CLASS = load_ui('CenRa_Metabase_dockwidget_base.ui')
LOGGER = logging.getLogger('CenRa_Metabase')
@ -84,8 +67,8 @@ class CenRa_Metabase(QDockWidget, DOCK_CLASS):
self.current_datasource_uri = None
self.current_connection = None
#self.viewer.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
#self.viewer.page().linkClicked.connect(self.open_link)
# self.viewer.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
# self.viewer.page().linkClicked.connect(self.open_link)
# Help button
self.external_help.setText('')
@ -94,13 +77,13 @@ class CenRa_Metabase(QDockWidget, DOCK_CLASS):
# Flat table button
self.flatten_dataset_table.setText('')
#self.flatten_dataset_table.setToolTip(tr("Add the catalog table"))
# self.flatten_dataset_table.setToolTip(tr("Add the catalog table"))
self.flatten_dataset_table.setIcon(QgsApplication.getThemeIcon("/mActionAddHtml.svg"))
#self.flatten_dataset_table.clicked.connect(self.add_flatten_dataset_table)
# self.flatten_dataset_table.clicked.connect(self.add_flatten_dataset_table)
# Settings menu
self.config.setAutoRaise(True)
#self.config.setToolTip(tr("Settings"))
# self.config.setToolTip(tr("Settings"))
self.config.setPopupMode(QToolButton.ToolButtonPopupMode(2))
self.config.setIcon(QgsApplication.getThemeIcon("/mActionOptions.svg"))
@ -118,7 +101,7 @@ class CenRa_Metabase(QDockWidget, DOCK_CLASS):
# Setting PDF/HTML menu
self.save_button.setAutoRaise(True)
#self.save_button.setToolTip(tr("Save metadata"))
# self.save_button.setToolTip(tr("Save metadata"))
self.save_button.setPopupMode(QToolButton.ToolButtonPopupMode(2))
self.save_button.setIcon(QIcon(QgsApplication.iconPath('mActionFileSave.svg')))
@ -146,21 +129,21 @@ class CenRa_Metabase(QDockWidget, DOCK_CLASS):
self.metadata = QgsProviderRegistry.instance().providerMetadata('postgres')
# Display message in the dock
#if not settings_connections_names():
#self.default_html_content_not_installed()
#else:
# if not settings_connections_names():
# self.default_html_content_not_installed()
# else:
self.default_html_content_not_pg_layer()
iface.layerTreeView().currentLayerChanged.connect(self.layer_changed)
try:
login_base()
iface.layerTreeView().currentLayerChanged.connect(self.layer_changed)
except:
#qgis.utils.plugins['CenRa_METABASE'].initGui()
except ValueError:
# qgis.utils.plugins['CenRa_METABASE'].initGui()
qgis.utils.plugins['CenRa_METABASE'].unload()
#self.default_html_content_not_pg_layer()
# self.default_html_content_not_pg_layer()
if iface.activeLayer():
layer=iface.activeLayer()
layer = iface.activeLayer()
iface.layerTreeView().setCurrentLayer(None)
iface.layerTreeView().setCurrentLayer(layer)
@ -192,7 +175,7 @@ class CenRa_Metabase(QDockWidget, DOCK_CLASS):
if output_format == OutputFormats.PDF:
printer = QPrinter()
printer.setOutputFormat(QPrinter.OutputFormat(1))
#printer.setPageMargins(20,20,20,20,QPrinter.Unit(0))
# printer.setPageMargins(20,20,20,20,QPrinter.Unit(0))
printer.setOutputFileName(output_file_path)
self.viewer.print(printer)
iface.messageBar().pushSuccess(
@ -202,7 +185,7 @@ class CenRa_Metabase(QDockWidget, DOCK_CLASS):
"<a href=\"{}\">{}</a>").format(parent_folder, output_file_path)
)
elif output_format in [OutputFormats.HTML,OutputFormats.DCAT]:
elif output_format in [OutputFormats.HTML, OutputFormats.DCAT]:
if output_format == OutputFormats.HTML:
data_str = self.viewer.page().currentFrame().toHtml()
else:
@ -215,7 +198,7 @@ class CenRa_Metabase(QDockWidget, DOCK_CLASS):
xml_template = xml_file.read()
xml = parseString(xml_template.format(language=data[0][0], content=data[0][1]))
data_str = xml.toprettyxml()
with open(output_file[0], "w", encoding='utf8') as file_writer:
@ -231,43 +214,15 @@ class CenRa_Metabase(QDockWidget, DOCK_CLASS):
def save_auto_open_dock(self):
""" Save settings about the dock. """
self.settings.setValue("pgmetadata/auto_open_dock", self.auto_open_dock_action.isChecked())
def sql_to_xml(self,dataall):
distribution=''
def sql_to_xml(self, dataall):
distribution = ''
for y in dataall[1]:
distribution = distribution + (
'<dcat:distribution>'+
'<dcat:Distribution>'+
'<dct:title>{data}</dct:title>'.format(data=y[0])+
'<dcat:downloadURL>{data}</dcat:downloadURL>'.format(data=y[1])+
'<dcat:mediaType>{data}</dcat:mediaType>'.format(data=y[2])+
'<dct:format>{data}</dct:format>'.format(data=y[3])+
'<dct:bytesize>{data}</dct:bytesize>'.format(data=y[4])+
'</dcat:Distribution>'+
'</dcat:distribution>')
publisher=''
distribution = distribution + ('<dcat:distribution>' + '<dcat:Distribution>' + '<dct:title>{data}</dct:title>'.format(data=y[0]) + '<dcat:downloadURL>{data}</dcat:downloadURL>'.format(data=y[1]) + '<dcat:mediaType>{data}</dcat:mediaType>'.format(data=y[2]) + '<dct:format>{data}</dct:format>'.format(data=y[3]) + '<dct:bytesize>{data}</dct:bytesize>'.format(data=y[4]) + '</dcat:Distribution>' + '</dcat:distribution>')
publisher = ''
for z in dataall[2]:
publisher = publisher + (
'<dct:publisher>'+
'<foaf:Organization>'+
'<foaf:name>{data}</foaf:name>'.format(data=z[1])+
'<foaf:mbox>{data}</foaf:mbox>'.format(data=z[3])+
'</foaf:Organization>'+
'</dct:publisher>')
data_str = [[dataall[0][26],
'<dct:identifier>{data}</dct:identifier>'.format(data=dataall[0][1])+
'<dct:title>{data}</dct:title>'.format(data=dataall[0][4])+
'<dct:description>{data}</dct:description>'.format(data=dataall[0][5])+
'<dct:language>{data}</dct:language>'.format(data=dataall[0][26])+
'<dct:spatial>{data}</dct:spatial>'.format(data=dataall[0][28])+
'<dct:created rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">{data}</dct:created>'.format(data=dataall[0][20])+
'<dct:issued rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">{data}</dct:issued>'.format(data=dataall[0][11])+
'<dct:modified rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">{data}</dct:modified>'.format(data=dataall[0][21])+
'<dct:license>{data}</dct:license>'.format(data=dataall[0][13])+
distribution+
publisher+
'<dcat:theme>{data}</dcat:theme>'.format(data=", ".join(str(x) for x in dataall[0][24]))+
'<dcat:keyword>{data}</dcat:keyword>'.format(data=", ".join(str(x) for x in dataall[0][6]))+
'<dct:accrualPeriodicity>{data}</dct:accrualPeriodicity>'.format(data=dataall[0][12])]]
publisher = publisher + ('<dct:publisher>' + '<foaf:Organization>' + '<foaf:name>{data}</foaf:name>'.format(data=z[1]) + '<foaf:mbox>{data}</foaf:mbox>'.format(data=z[3]) + '</foaf:Organization>' + '</dct:publisher>')
data_str = [[dataall[0][26], '<dct:identifier>{data}</dct:identifier>'.format(data=dataall[0][1]) + '<dct:title>{data}</dct:title>'.format(data=dataall[0][4]) + '<dct:description>{data}</dct:description>'.format(data=dataall[0][5]) + '<dct:language>{data}</dct:language>'.format(data=dataall[0][26]) + '<dct:spatial>{data}</dct:spatial>'.format(data=dataall[0][28]) + '<dct:created rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">{data}</dct:created>'.format(data=dataall[0][20]) + '<dct:issued rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">{data}</dct:issued>'.format(data=dataall[0][11]) + '<dct:modified rdf:datatype="http://www.w3.org/2001/XMLSchema#dateTime">{data}</dct:modified>'.format(data=dataall[0][21]) + '<dct:license>{data}</dct:license>'.format(data=dataall[0][13]) + distribution + publisher + '<dcat:theme>{data}</dcat:theme>'.format(data=", ".join(str(x) for x in dataall[0][24])) + '<dcat:keyword>{data}</dcat:keyword>'.format(data=", ".join(str(x) for x in dataall[0][6])) + '<dct:accrualPeriodicity>{data}</dct:accrualPeriodicity>'.format(data=dataall[0][12])]]
return data_str
@ -277,7 +232,7 @@ publisher+
locale = QgsSettings().value("locale/userLocale", QLocale().name())
locale = locale.split('_')[0].lower()
if output_format == [OutputFormats.HTML,OutputFormats.DCAT]:
if output_format == [OutputFormats.HTML, OutputFormats.DCAT]:
sql = (
"SELECT pgmetadata.get_dataset_item_html_content('{schema}', '{table}', '{locale}');"
).format(schema=uri.schema(), table=uri.table(), locale=locale)
@ -292,7 +247,6 @@ publisher+
self.current_connection = None
self.ce_trouve_dans_psql(layer)
def add_flatten_dataset_table(self):
""" Add a flatten dataset table with all links and contacts. """
'''
@ -337,17 +291,17 @@ publisher+
def set_html_content(self, title=None, body=None):
""" Set the content in the dock. """
#link_logo=resources_path('icons', 'CEN_RA.png')
# ink_logo=resources_path('icons', 'CEN_RA.png')
css_file = resources_path('css', 'dock.css')
with open(css_file, 'r', encoding='utf8') as f:
css = f.read()
html = '<html><head>'
#html += '<script src="http://ignf.github.io/geoportal-sdk/latest/dist/2d/GpSDK2D.js" defer ></script>'
# html += '<script src="http://ignf.github.io/geoportal-sdk/latest/dist/2d/GpSDK2D.js" defer ></script>'
html += '<style>{css}</style></head><body>'.format(css=css)
#html += '<link rel="stylesheet" href="http://ignf.github.io/geoportal-sdk/latest/dist/2d/GpSDK2D.css" >'
#html += '<script src="file:///C:/Users/tlaveille/Desktop/maps.js" defer></script>'
#html += '<noscript>Your browser does not support JavaScript!</noscript>'
# html += '<link rel="stylesheet" href="http://ignf.github.io/geoportal-sdk/latest/dist/2d/GpSDK2D.css" >'
# html += '<script src="file:///C:/Users/tlaveille/Desktop/maps.js" defer></script>'
# html += '<noscript>Your browser does not support JavaScript!</noscript>'
if title:
html += '<h2>{title} <img class=logo src=https://i2.wp.com/www.cen-rhonealpes.fr/wp-content/uploads/2013/04/cen-rhonealpes-couleurs1.jpg?w=340&ssl=1></h2>'.format(title=title)
if body:
@ -356,16 +310,16 @@ publisher+
html += '</body></html>'
# It must be a file, even if it does not exist on the file system.
base_url = QUrl.fromLocalFile(resources_path('images', 'must_be_a_file.png'))
self.viewer.setHtml(html)#, base_url)
# base_url = QUrl.fromLocalFile(resources_path('images', 'must_be_a_file.png'))
self.viewer.setHtml(html)
def ce_trouve_dans_psql(self,layer):
def ce_trouve_dans_psql(self, layer):
try:
uri = layer.dataProvider().uri()
except:
except AttributeError:
self.default_html_content_not_pg_layer()
self.save_button.setEnabled(False)
uri=''
uri = ''
if uri != '':
if not uri.table():
layertype = layer.providerType().lower()
@ -376,23 +330,23 @@ publisher+
self.save_button.setEnabled(False)
else:
data_count = self.sql_check(uri)
#print(data_count)
# print(data_count)
if data_count == 0:
self.default_html_content_not_metadata()
self.save_button.setEnabled(False)
else:
self.build_html_content(layer,uri)
self.build_html_content(layer, uri)
self.save_button.setEnabled(True)
def build_html_content(self,layer,uri):
def build_html_content(self, layer, uri):
body = ''
dataall=self.sql_info(uri)
data=dataall[0]
data_url=dataall[1]
data_contact=dataall[2]
#print(len(data_url))
data_collonne=[field.name() for field in layer.dataProvider().fields()]
dataall = self.sql_info(uri)
data = dataall[0]
data_url = dataall[1]
data_contact = dataall[2]
# print(len(data_url))
# data_collonne = [field.name() for field in layer.dataProvider().fields()]
body += '<div><h3>Identification</h3><table class="table table-condensed">'
body += '<tr><th>Titre</th><td>{data[4]}</td></tr>'.format(data=data)
@ -415,7 +369,7 @@ publisher+
body += '<tr><th>Emprise</th><td>{data[28]}</td></tr>'.format(data=data)
body += '</table></div>'
#body += '<div id="map"></div>'
# body += '<div id="map"></div>'
body += '<div><h3>Publication</h3><table class="table table-condensed">'
body += '<tr><th>Date</th><td>{data[11]}</td></tr>'.format(data=data)
@ -454,45 +408,46 @@ publisher+
self.set_html_content(
layer.name(), body)
def set_html_to_wms(self,layer):
def set_html_to_wms(self, layer):
self.set_html_content(
'CenRa Metadata',(layer.htmlMetadata()))
'CenRa Metadata', (layer.htmlMetadata()))
def default_html_content_not_pg_layer(self):
""" When it's not a PostgreSQL layer. """
self.set_html_content(
'CenRa Metadata', ('Vous devez cliquer sur une couche dans la légende qui est stockée dans PostgreSQL.'))
def default_html_content_not_metadata(self):
self.set_html_content(
'CenRa Metadata', ('La couche ne contien pas de métadonnée.'))
def sql_check(self,uri):
cur=login_base()
def sql_check(self, uri):
cur = login_base()
table = uri.table()
schema = uri.schema()
sql_count = """SELECT count(uid) FROM metadata.dataset
WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
WHERE schema_name LIKE '""" + schema + """' AND table_name LIKE '""" + table + """';"""
cur.execute(sql_count)
data_count = cur.fetchall()
cur.close()
return data_count[0][0]
def sql_info(self,uri):
cur=login_base()
def sql_info(self, uri):
cur = login_base()
table = uri.table()
schema = uri.schema()
#[s for s in iface.activeLayer().source().split(" ") if "dbname" in s][0].split("'")[1]
# [s for s in iface.activeLayer().source().split(" ") if "dbname" in s][0].split("'")[1]
sql_find = """SELECT *,right(left(st_astext(geom,2),-2),-9) FROM metadata.dataset
WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
WHERE schema_name LIKE '""" + schema + """' AND table_name LIKE '""" + table + """';"""
cur.execute(sql_find)
data_general = cur.fetchall()
sql_findurl = """SELECT type,url,mime,format,taille FROM metadata.dataurl WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
sql_findurl = """SELECT type,url,mime,format,taille FROM metadata.dataurl WHERE schema_name LIKE '""" + schema + """' AND table_name LIKE '""" + table + """';"""
cur.execute(sql_findurl)
data_url = cur.fetchall()
sql_findcontact = """SELECT role,nom,organisation,email,telephone FROM metadata.datacontact WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
sql_findcontact = """SELECT role,nom,organisation,email,telephone FROM metadata.datacontact WHERE schema_name LIKE '""" + schema + """' AND table_name LIKE '""" + table + """';"""
cur.execute(sql_findcontact)
data_contact = cur.fetchall()
cur.close()
return data_general[0],data_url,data_contact
return data_general[0], data_url, data_contact

View File

@ -1,66 +1,53 @@
import logging
import os
from collections import namedtuple
from enum import Enum
from functools import partial
from pathlib import Path
from xml.dom.minidom import parseString
from qgis.gui import *
# from collections import namedtuple
# from enum import Enum
# from functools import partial
# from pathlib import Path
# from xml.dom.minidom import parseString
# from qgis.gui import *
from qgis.core import (
NULL,
QgsApplication,
QgsDataSourceUri,
QgsProject,
QgsProviderConnectionException,
QgsProviderRegistry,
QgsRasterLayer,
QgsSettings,
QgsVectorLayer,
QgsGeometry,
QgsWkbTypes,
)
from qgis.PyQt import QtGui
from qgis.PyQt.QtCore import QLocale, QUrl, QDateTime
from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtPrintSupport import QPrinter
#from qgis.PyQt.QtWebKitWidgets import QWebPage
from qgis.PyQt import QtGui, QtCore
from qgis.PyQt.QtGui import QIcon
# from qgis.PyQt.QtPrintSupport import QPrinter
# from qgis.PyQt.QtWebKitWidgets import QWebPage
import psycopg2
from qgis.PyQt.QtWidgets import (
QDialog,
QAction,
QDockWidget,
QFileDialog,
QInputDialog,
QMenu,
QToolButton,
QTableWidget,
QTableWidgetItem,
)
from qgis.utils import iface
try:
from .tools.PythonSQL import login_base
except:
except ValueError:
print('Pas de fichier PythonSQL')
from .tools.resources import (
load_ui,
resources_path,
send_issues,
# send_issues,
)
from .issues import CenRa_Issues
# from .issues import CenRa_Issues
EDITOR_CLASS = load_ui('CenRa_Metabase_editorwidget_base.ui')
LOGGER = logging.getLogger('CenRa_Metabase')
LOGGEr = logging.getLogger('CenRa_Metabase')
class Metabase_Editor(QDialog, EDITOR_CLASS):
def __init__(self, parent=None):
_ = parent
super().__init__()
self.setupUi(self)
self.settings = QgsSettings()
self.setWindowIcon(QtGui.QIcon(resources_path('icons','icon.png')))
self.setWindowIcon(QtGui.QIcon(resources_path('icons', 'icon.png')))
self.import_xml.setAutoRaise(True)
self.import_xml.setText('')
self.import_xml.setIcon(QIcon(QgsApplication.iconPath('mActionAddHtml.svg')))
@ -68,13 +55,13 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
self.issues_app.setAutoRaise(True)
self.issues_app.setText('')
self.issues_app.setIcon(QIcon(QgsApplication.iconPath('mIconInfo.svg')))
self.auto_adding.setIcon(QtGui.QIcon(resources_path('icons','auto_add.png')))
self.auto_adding.setIcon(QtGui.QIcon(resources_path('icons', 'auto_add.png')))
self.auto_adding.hide()
if os.getlogin() == 'tlaveille' or 'lpoulin' or 'rclement':
self.auto_adding.show()
self.auto_adding.clicked.connect(self.auto_run)
self.issues_app.clicked.connect(self.issues_open)
# self.issues_app.clicked.connect(self.issues_open)
self.categories_select_view.itemDoubleClicked.connect(self.add_categories_view)
self.categories_view.itemDoubleClicked.connect(self.deleter_categories_view)
self.themes_select_view.itemDoubleClicked.connect(self.add_themes_view)
@ -102,6 +89,7 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
self.format_box.setCurrentIndex(0)
self.taille_line.setText('45')
self.add_lien()
def add_metadata(self):
table_name = layer.dataProvider().uri().table()
schema_name = layer.dataProvider().uri().schema()
@ -117,19 +105,19 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
array_categories = '{'
while row_count_categories >= row:
if row_count_categories != row:
array_categories += (self.categories_view.item(row-1,0).text())+','
array_categories += (self.categories_view.item(row - 1, 0).text()) + ', '
else:
array_categories += (self.categories_view.item(row-1,0).text())
row = row+1
array_categories += (self.categories_view.item(row - 1, 0).text())
row = row + 1
array_categories += '}'
row = 1
array_themes = '{'
while row_count_themes >= row:
if row_count_themes != row:
array_themes += (self.themes_view.item(row-1,0).text())+','
array_themes += (self.themes_view.item(row - 1, 0).text()) + ', '
else:
array_themes += (self.themes_view.item(row-1,0).text())
row = row+1
array_themes += (self.themes_view.item(row - 1, 0).text())
row = row + 1
array_themes += '}'
text_date_creation = str(self.date_creation_date.date().toPyDate())
@ -162,65 +150,65 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
array_link = ''
while row_count_link >= row:
if row_count_link != row:
array_link += "('"+ table_name +"','"+ schema_name +"','"+ (self.table_lien.item(row-1,1).text()) +"','"+ (self.table_lien.item(row-1,2).text()) +"','"+ (self.table_lien.item(row-1,3).text()) +"','"+ (self.table_lien.item(row-1,4).text()) +"','"+ (self.table_lien.item(row-1,5).text()) +"')"+','
array_link += "('" + table_name + "', '" + schema_name + "', '" + (self.table_lien.item(row - 1,1).text()) + "', '" + (self.table_lien.item(row - 1,2).text()) + "', '" + (self.table_lien.item(row - 1,3).text()) + "', '" + (self.table_lien.item(row - 1,4).text()) + "', '" + (self.table_lien.item(row - 1,5).text()) + "')" + ', '
else:
array_link += "('"+ table_name +"','"+ schema_name +"','"+ (self.table_lien.item(row-1,1).text()) +"','"+ (self.table_lien.item(row-1,2).text()) +"','"+ (self.table_lien.item(row-1,3).text()) +"','"+ (self.table_lien.item(row-1,4).text()) +"','"+ (self.table_lien.item(row-1,5).text()) +"')"
row = row+1
array_link += "('" + table_name + "', '" + schema_name + "', '" + (self.table_lien.item(row - 1,1).text()) + "', '" + (self.table_lien.item(row - 1,2).text()) + "', '" + (self.table_lien.item(row - 1,3).text()) + "', '" + (self.table_lien.item(row - 1,4).text()) + "', '" + (self.table_lien.item(row - 1,5).text()) + "')"
row = row + 1
row_count_contact = self.table_contact.rowCount()
row = 1
array_contact = ''
while row_count_contact >= row:
if row_count_contact != row:
array_contact += "('"+ table_name +"','"+ schema_name +"','"+ (self.table_contact.item(row-1,1).text()) +"','"+ (self.table_contact.item(row-1,2).text()) +"','"+ (self.table_contact.item(row-1,3).text()) +"','"+ (self.table_contact.item(row-1,4).text()) +"','"+ (self.table_contact.item(row-1,5).text()) +"')"+','
array_contact += "('" + table_name + "', '" + schema_name + "', '" + (self.table_contact.item(row - 1,1).text()) + "', '" + (self.table_contact.item(row - 1,2).text()) + "', '" + (self.table_contact.item(row - 1,3).text()) + "', '" + (self.table_contact.item(row - 1,4).text()) + "', '" + (self.table_contact.item(row - 1,5).text()) + "')" + ', '
else:
array_contact += "('"+ table_name +"','"+ schema_name +"','"+ (self.table_contact.item(row-1,1).text()) +"','"+ (self.table_contact.item(row-1,2).text()) +"','"+ (self.table_contact.item(row-1,3).text()) +"','"+ (self.table_contact.item(row-1,4).text()) +"','"+ (self.table_contact.item(row-1,5).text()) +"')"
row = row+1
array_contact += "('" + table_name + "', '" + schema_name + "', '" + (self.table_contact.item(row - 1,1).text()) + "', '" + (self.table_contact.item(row - 1,2).text()) + "', '" + (self.table_contact.item(row - 1,3).text()) + "', '" + (self.table_contact.item(row - 1,4).text()) + "', '" + (self.table_contact.item(row - 1,5).text()) + "')"
row = row + 1
'''
exist=self.status_metadata(layer)
cur_con=login_base(take=True)
cur=cur_con[0]
con=cur_con[1]
exist = self.status_metadata(layer)
cur_con = login_base(take=True)
cur = cur_con[0]
con = cur_con[1]
list_champs_sql = ''
values_sql_add = ''
if exist:
SQL_uid = """SELECT uid from metadata.dataset where table_name like '"""+table_name+"""' and schema_name like '"""+schema_name+"""';"""
SQL_uid = """SELECT uid from metadata.dataset where table_name like '""" + table_name + """' and schema_name like '""" + schema_name + """';"""
cur.execute(SQL_uid)
text_uid = (cur.fetchall())[0][0]
SQL_delete = """DELETE from metadata.dataset where table_name like '"""+table_name+"""' and schema_name like '"""+schema_name+"""';"""
SQL_delete = """DELETE from metadata.dataset where table_name like '""" + table_name + """' and schema_name like '""" + schema_name + """';"""
cur.execute(SQL_delete)
values_sql_add += "'"+text_uid+"',"
values_sql_add += "'" + text_uid + "',"
list_champs_sql+='uid,'
global uid_delete_list_link,uid_delete_list_contact
list_champs_sql += 'uid,'
global uid_delete_list_link, uid_delete_list_contact
if len(uid_delete_list_link) >= 35:
SQL_delete_link = """DELETE FROM metadata.dataurl WHERE uid IN ("""+ uid_delete_list_link[:-1] +""");"""
SQL_delete_link = """DELETE FROM metadata.dataurl WHERE uid IN (""" + uid_delete_list_link[:- 1] + """);"""
cur.execute(SQL_delete_link)
uid_delete_list_link = ''
if len(uid_delete_list_contact) >= 35:
SQL_delete_contact = """DELETE FROM metadata.datacontact WHERE uid IN ("""+ uid_delete_list_contact[:-1] +""");"""
SQL_delete_contact = """DELETE FROM metadata.datacontact WHERE uid IN (""" + uid_delete_list_contact[:- 1] + """);"""
cur.execute(SQL_delete_contact)
uid_delete_list_contact=''
uid_delete_list_contact = ''
list_champs_sql += 'table_name,schema_name,title,abstract,keywords,data_last_update,langue,categories,themes,creation_date,update_date,encode,geom,spatial_extent,feature_count,geometry_type,projection_name,projection_authid,spatial_level,minimum_optimal_scale,maximum_optimal_scale,publication_date,publication_frequency,confidentiality,license,license_attribution'
values_sql_add += "'"+table_name+"','"+schema_name+"','"+text_titre+"','"+text_description+"','"+text_mots_cles+"','"+text_date_maj+"','"+text_langue+"','"+array_categories+"','"+array_themes+"','"+text_date_creation+"','"+text_date_modification+"','"+text_encode+"','"+text_extend+"','"+text_extend+"','"+int_nbr_entites+"','"+text_geomtype+"','"+text_crsname+"','"+text_crscode+"','"+text_niveau+"',"+text_echelle_min+","+text_echelle_max+",'"+text_date_publication+"','"+text_frequence+"','"+text_restriction+"','"+text_licence+"','"+text_licence_attrib+"'"
list_champs_sql += 'table_name, schema_name, title, abstract, keywords, data_last_update, langue, categories, themes, creation_date, update_date, encode, geom, spatial_extent, feature_count, geometry_type, projection_name, projection_authid, spatial_level, minimum_optimal_scale, maximum_optimal_scale, publication_date, publication_frequency, confidentiality, license, license_attribution'
values_sql_add += "'" + table_name + "', '" + schema_name + "', '" + text_titre + "', '" + text_description + "', '" + text_mots_cles + "', '" + text_date_maj + "', '" + text_langue + "', '" + array_categories + "', '" + array_themes + "', '" + text_date_creation + "', '" + text_date_modification + "', '" + text_encode + "', '" + text_extend + "', '" + text_extend + "', '" + int_nbr_entites + "', '" + text_geomtype + "', '" + text_crsname + "', '" + text_crscode + "', '" + text_niveau + "'," + text_echelle_min + "," + text_echelle_max + ",'" + text_date_publication + "', '" + text_frequence + "', '" + text_restriction + "', '" + text_licence + "', '" + text_licence_attrib + "'"
SQL_add = """INSERT INTO metadata.dataset ("""+list_champs_sql+""") VALUES ("""+values_sql_add+""");"""
SQL_add = """INSERT INTO metadata.dataset (""" + list_champs_sql + """) VALUES (""" + values_sql_add + """);"""
cur.execute(SQL_add)
global array_link,array_contact
global array_link, array_contact
if len(array_link) >= 25:
array_link=array_link[:-1]
SQL_add_link = """INSERT INTO metadata.dataurl (table_name,schema_name,type,url,mime,format,taille) VALUES """+array_link+""";"""
array_link = array_link[:- 1]
SQL_add_link = """INSERT INTO metadata.dataurl (table_name, schema_name, type, url, mime, format, taille) VALUES """ + array_link + """;"""
cur.execute(SQL_add_link)
array_link = ''
if len(array_contact) >= 25:
array_contact=array_contact[0:-1]
SQL_add_contact = """INSERT INTO metadata.datacontact (table_name,schema_name,role,nom,organisation,email,telephone) VALUES """+array_contact+""";"""
array_contact = array_contact[0:- 1]
SQL_add_contact = """INSERT INTO metadata.datacontact (table_name, schema_name, role, nom, organisation, email, telephone) VALUES """ + array_contact + """;"""
cur.execute(SQL_add_contact)
array_contact = ''
@ -235,28 +223,28 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
self.activateWindow()
global layer
layer = iface.activeLayer()
global uid_delete_list_link,uid_delete_list_contact,array_link,array_contact
uid_delete_list_link=''
uid_delete_list_contact=''
global uid_delete_list_link, uid_delete_list_contact, array_link, array_contact
uid_delete_list_link = ''
uid_delete_list_contact = ''
array_link = ''
array_contact = ''
is_ok=self.is_in_psql(layer)
is_ok = self.is_in_psql(layer)
if is_ok:
exist=self.status_metadata(layer)
exist = self.status_metadata(layer)
if exist:
self.reload_data(layer)
else:
self.new_data(layer)
else:
self.close()
iface.messageBar().pushMessage("Information :", "Cette couche n'est pas stockée dans PostgreSQL", level=Qgis.Warning, duration=30)
iface.messageBar().pushMessage("Information:", "Cette couche n'est pas stockée dans PostgreSQL", level=1, duration=30)
def is_in_psql(self,layer):
def is_in_psql(self, layer):
try:
uri = layer.dataProvider().uri()
except:
uri=''
except AttributeError:
uri = ''
return False
if uri != '':
if not uri.table():
@ -264,13 +252,13 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
else:
return True
def status_metadata(self,layer):
def status_metadata(self, layer):
uri = layer.dataProvider().uri()
table = uri.table()
schema = uri.schema()
cur=login_base()
count_sql = """ SELECT count(uid) FROM metadata.dataset WHERE table_name LIKE '"""+table+"""' AND schema_name LIKE '"""+schema+"""';"""
cur = login_base()
count_sql = """ SELECT count(uid) FROM metadata.dataset WHERE table_name LIKE '""" + table + """' AND schema_name LIKE '""" + schema + """';"""
cur.execute(count_sql)
data_count = (cur.fetchall())[0][0]
@ -280,17 +268,17 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
return False
cur.close()
def new_data(self,layer):
#print(layer.name(),'is new data')
reloader=False
self.interface_view(layer,reloader)
def new_data(self, layer):
# print(layer.name(),'is new data')
reloader = False
self.interface_view(layer, reloader)
def reload_data(self,layer):
#print(layer.name(),'reload data')
reloader=True
self.interface_view(layer,reloader)
def reload_data(self, layer):
# print(layer.name(),'reload data')
reloader = True
self.interface_view(layer, reloader)
def interface_view(self,layer,reloader):
def interface_view(self, layer, reloader):
self.description_text.setText(None)
self.mots_cles_text.setText(None)
@ -309,27 +297,26 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
self.licence_attrib_box.clear()
self.restriction_box.clear()
all_list=self.fletch_ref()
all_list = self.fletch_ref()
categories_list=all_list[0]
themes_list=all_list[1]
langue_list=all_list[2]
encodage_list=all_list[3]
frequency_list=all_list[4]
confidentiality_list=all_list[5]
license_list=all_list[6]
type_list=all_list[7]
mime_list=all_list[8]
format_list=all_list[9]
role_list=all_list[10]
organisation_list=all_list[11]
categories_list = all_list[0]
themes_list = all_list[1]
langue_list = all_list[2]
encodage_list = all_list[3]
frequency_list = all_list[4]
confidentiality_list = all_list[5]
license_list = all_list[6]
type_list = all_list[7]
mime_list = all_list[8]
format_list = all_list[9]
role_list = all_list[10]
organisation_list = all_list[11]
#langue_box
# langue_box
self.langue_box.clear()
self.langue_box.addItem('')
#self.langue_box.addItem('Fr')
#self.langue_box.addItem('En')
# self.langue_box.addItem('Fr')
# self.langue_box.addItem('En')
for langue_list_data in langue_list:
self.langue_box.addItem(langue_list_data[0])
@ -339,46 +326,46 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
self.table_ligne.setText(layer.dataProvider().uri().table())
self.schema_ligne.setText(layer.dataProvider().uri().schema())
#categories_select_view
# categories_select_view
self.categories_select_view.setColumnCount(1)
self.categories_select_view.setColumnWidth(0, 230)
self.categories_select_view.setHorizontalHeaderLabels(['List des categories'])
#categories_view
# categories_view
self.categories_view.setRowCount(0)
self.categories_view.setColumnCount(1)
self.categories_view.setColumnWidth(0, 230)
self.categories_view.setHorizontalHeaderLabels(['Categories'])
#themes_select_view
# themes_select_view
self.themes_select_view.setColumnCount(1)
self.themes_select_view.setColumnWidth(0, 230)
self.themes_select_view.setHorizontalHeaderLabels(['List des thèmes'])
#themes_view
# themes_view
self.themes_view.setRowCount(0)
self.themes_view.setColumnCount(1)
self.themes_view.setColumnWidth(0, 230)
self.themes_view.setHorizontalHeaderLabels(['Thèmes'])
#lien_view
# lien_view
self.table_lien.setRowCount(0)
self.table_lien.setColumnCount(6)
self.table_lien.setColumnWidth(0, 0)
self.table_lien.setHorizontalHeaderLabels(['','Type','URL','MIME','Format','Taille'])
self.table_lien.setHorizontalHeaderLabels(['', 'Type', 'URL', 'MIME', 'Format', 'Taille'])
#contact_view
# contact_view
self.table_contact.setRowCount(0)
self.table_contact.setColumnCount(6)
self.table_contact.setColumnWidth(0, 0)
self.table_contact.setHorizontalHeaderLabels(['','Rôle','Nom','Organisation','Email','Telephone'])
self.table_contact.setHorizontalHeaderLabels(['', 'Rôle', 'Nom', 'Organisation', 'Email', 'Telephone'])
#print(self.date_maj_date.date().toPyDate())
# print(self.date_maj_date.date().toPyDate())
vector_extend = layer.extent()
polygone_extend = QgsGeometry.fromRect(vector_extend).asWkt()
self.extend_plaintext.setPlainText(str(polygone_extend))
qgstype = str(layer.type())[10:]
if qgstype != 'Raster' :
if qgstype != 'Raster':
count_layers = str(layer.featureCount())
geomtype = QgsWkbTypes.displayString(layer.wkbType())
elif qgstype == 'Raster':
@ -392,7 +379,6 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
crs_code = str(layer.crs().authid())
self.crscode_plaintext.setPlainText(crs_code)
self.frequence_box.addItem('')
self.restriction_box.addItem('')
self.licence_box.addItem('')
@ -428,12 +414,12 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
self.organisation_box.addItem(organisation_list_data[0])
if reloader:
sql_dataload=self.sql_info(layer.dataProvider().uri())
sql_contactlink=self.sql_infoother(layer.dataProvider().uri())
sql_datalink=sql_contactlink[0]
sql_datacontact=sql_contactlink[1]
sql_dataload = self.sql_info(layer.dataProvider().uri())
sql_contactlink = self.sql_infoother(layer.dataProvider().uri())
sql_datalink = sql_contactlink[0]
sql_datacontact = sql_contactlink[1]
#print(sql_dataload)
# print(sql_dataload)
self.titre_line.setText(sql_dataload[4])
self.date_maj_date.setDateTime(sql_dataload[23])
self.date_publication_date.setDateTime(sql_dataload[11])
@ -444,38 +430,38 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
self.uuid_ligne.setText(sql_dataload[1])
self.categories_view.setRowCount(len(sql_dataload[6]))
i=0
i = 0
for categorie_data in sql_dataload[6]:
self.categories_view.setItem(i,0,QTableWidgetItem(categorie_data))
i=i+1
self.categories_view.setItem(i, 0, QTableWidgetItem(categorie_data))
i = i + 1
self.themes_view.setRowCount(len(sql_dataload[24]))
i=0
i = 0
for themes_data in sql_dataload[24]:
self.themes_view.setItem(i,0,QTableWidgetItem(themes_data))
i=i+1
self.themes_view.setItem(i, 0, QTableWidgetItem(themes_data))
i = i + 1
self.categories_select_view.setRowCount(len(categories_list)-len(sql_dataload[6]))
self.themes_select_view.setRowCount(len(themes_list)-len(sql_dataload[24]))
i=0
self.categories_select_view.setRowCount(len(categories_list) - len(sql_dataload[6]))
self.themes_select_view.setRowCount(len(themes_list) - len(sql_dataload[24]))
i = 0
for categorie_select_data in categories_list:
try:
in_index = sql_dataload[6].index(categorie_select_data[0])
in_index=False
except:
in_index=True
in_index = False
except ValueError:
in_index = True
if in_index:
self.categories_select_view.setItem(i,0,QTableWidgetItem(categorie_select_data[0]))
i=i+1
i=0
self.categories_select_view.setItem(i, 0, QTableWidgetItem(categorie_select_data[0]))
i = i + 1
i = 0
for themes_select_data in themes_list:
try:
in_index = sql_dataload[24].index(themes_select_data[0])
in_index=False
except:
in_index=True
in_index = False
except ValueError:
in_index = True
if in_index:
self.themes_select_view.setItem(i,0,QTableWidgetItem(themes_select_data[0]))
i=i+1
self.themes_select_view.setItem(i, 0, QTableWidgetItem(themes_select_data[0]))
i = i + 1
array_encodage_box = [self.encodage_box.itemText(i) for i in range(self.encodage_box.count())]
self.encodage_box.setCurrentIndex(array_encodage_box.index(sql_dataload[27]))
@ -504,35 +490,35 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
array_licence_attrib_box = [self.licence_attrib_box.itemText(i) for i in range(self.licence_attrib_box.count())]
self.licence_attrib_box.setCurrentIndex(array_licence_attrib_box.index(sql_dataload[25]))
c=0
#self.table_lien.setRowCount(len(sql_datalink))
c = 0
# self.table_lien.setRowCount(len(sql_datalink))
for lien_data in sql_datalink:
self.table_lien.insertRow(c)
self.table_lien.setItem(c,0,QTableWidgetItem(lien_data[1]))
self.table_lien.setItem(c,1,QTableWidgetItem(lien_data[4]))
self.table_lien.setItem(c,2,QTableWidgetItem(lien_data[5]))
self.table_lien.setItem(c,3,QTableWidgetItem(lien_data[6]))
self.table_lien.setItem(c,4,QTableWidgetItem(lien_data[7]))
self.table_lien.setItem(c,5,QTableWidgetItem(lien_data[8]))
c=c+1
c=0
#self.table_contact.setRowCount(len(sql_datacontact))
self.table_lien.setItem(c, 0, QTableWidgetItem(lien_data[1]))
self.table_lien.setItem(c, 1, QTableWidgetItem(lien_data[4]))
self.table_lien.setItem(c, 2, QTableWidgetItem(lien_data[5]))
self.table_lien.setItem(c, 3, QTableWidgetItem(lien_data[6]))
self.table_lien.setItem(c, 4, QTableWidgetItem(lien_data[7]))
self.table_lien.setItem(c, 5, QTableWidgetItem(lien_data[8]))
c = c + 1
c = 0
# self.table_contact.setRowCount(len(sql_datacontact))
for contact_data in sql_datacontact:
self.table_contact.insertRow(c)
self.table_contact.setItem(c,0,QTableWidgetItem(contact_data[1]))
self.table_contact.setItem(c,1,QTableWidgetItem(contact_data[4]))
self.table_contact.setItem(c,2,QTableWidgetItem(contact_data[5]))
self.table_contact.setItem(c,3,QTableWidgetItem(contact_data[6]))
self.table_contact.setItem(c,4,QTableWidgetItem(contact_data[7]))
self.table_contact.setItem(c,5,QTableWidgetItem(contact_data[8]))
c=c+1
self.table_contact.setItem(c, 0, QTableWidgetItem(contact_data[1]))
self.table_contact.setItem(c, 1, QTableWidgetItem(contact_data[4]))
self.table_contact.setItem(c, 2, QTableWidgetItem(contact_data[5]))
self.table_contact.setItem(c, 3, QTableWidgetItem(contact_data[6]))
self.table_contact.setItem(c, 4, QTableWidgetItem(contact_data[7]))
self.table_contact.setItem(c, 5, QTableWidgetItem(contact_data[8]))
c = c + 1
else:
#titre_line
# titre_line
self.titre_line.setText(layer.name())
self.langue_box.setCurrentIndex(1)
#date_maj_date
# date_maj_date
now = QtCore.QDateTime.currentDateTime()
self.date_maj_date.setDateTime(now)
self.date_creation_date.setDateTime(now)
@ -540,87 +526,89 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
self.date_publication_date.setDateTime(now)
self.categories_select_view.setRowCount(len(categories_list))
self.themes_select_view.setRowCount(len(themes_list))
i=0
i = 0
for categorie_select_data in categories_list:
self.categories_select_view.setItem(i,0,QTableWidgetItem(categorie_select_data[0]))
i=i+1
i=0
self.categories_select_view.setItem(i, 0, QTableWidgetItem(categorie_select_data[0]))
i = i + 1
i = 0
for themes_select_data in themes_list:
self.themes_select_view.setItem(i,0,QTableWidgetItem(themes_select_data[0]))
i=i+1
self.themes_select_view.setItem(i, 0, QTableWidgetItem(themes_select_data[0]))
i = i + 1
#print(self.langue_box.currentText())
# print(self.langue_box.currentText())
def sql_info(self,uri):
cur=login_base()
def sql_info(self, uri):
cur = login_base()
table = uri.table()
schema = uri.schema()
#[s for s in iface.activeLayer().source().split(" ") if "dbname" in s][0].split("'")[1]
sql_find = """SELECT *,right(left(st_astext(geom,2),-2),-9) FROM metadata.dataset
WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
# [s for s in iface.activeLayer().source().split(" ") if "dbname" in s][0].split("'")[1]
sql_find = """SELECT *, right(left(st_astext(geom,2),-2),-9) FROM metadata.dataset
WHERE schema_name LIKE '""" + schema + """' AND table_name LIKE '""" + table + """';"""
cur.execute(sql_find)
data_general = cur.fetchall()
cur.close()
return data_general[0]
def sql_infoother(self,uri):
cur=login_base()
def sql_infoother(self, uri):
cur = login_base()
table = uri.table()
schema = uri.schema()
sql_findlink = """SELECT * FROM metadata.dataurl
WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
WHERE schema_name LIKE '""" + schema + """' AND table_name LIKE '""" + table + """';"""
cur.execute(sql_findlink)
data_link = cur.fetchall()
sql_findcontact = """SELECT * FROM metadata.datacontact
WHERE schema_name LIKE '"""+schema+"""' AND table_name LIKE '"""+table+"""';"""
WHERE schema_name LIKE '""" + schema + """' AND table_name LIKE '""" + table + """';"""
cur.execute(sql_findcontact)
data_contact = cur.fetchall()
cur.close()
return data_link,data_contact
return data_link, data_contact
def add_categories_view(self):
values_add_categories = self.categories_select_view.selectedItems()[0].text()
self.categories_select_view.removeRow(self.categories_select_view.currentRow())
self.categories_view.insertRow(0)
self.categories_view.setItem(0,0,QTableWidgetItem(values_add_categories))
self.categories_view.setItem(0, 0, QTableWidgetItem(values_add_categories))
def deleter_categories_view(self):
values_deleter_categories = self.categories_view.selectedItems()[0].text()
self.categories_view.removeRow(self.categories_view.currentRow())
self.categories_select_view.insertRow(0)
self.categories_select_view.setItem(0,0,QTableWidgetItem(values_deleter_categories))
self.categories_select_view.setItem(0, 0, QTableWidgetItem(values_deleter_categories))
def add_themes_view(self):
values_add_themes = self.themes_select_view.selectedItems()[0].text()
self.themes_select_view.removeRow(self.themes_select_view.currentRow())
self.themes_view.insertRow(0)
self.themes_view.setItem(0,0,QTableWidgetItem(values_add_themes))
self.themes_view.setItem(0, 0, QTableWidgetItem(values_add_themes))
def deleter_themes_view(self):
values_deleter_themes = self.themes_view.selectedItems()[0].text()
self.themes_view.removeRow(self.themes_view.currentRow())
self.themes_select_view.insertRow(0)
self.themes_select_view.setItem(0,0,QTableWidgetItem(values_deleter_themes))
self.themes_select_view.setItem(0, 0, QTableWidgetItem(values_deleter_themes))
def add_lien(self):
cur=login_base()
maxrow=self.table_lien.rowCount()
cur = login_base()
maxrow = self.table_lien.rowCount()
self.table_lien.insertRow(maxrow)
table = layer.dataProvider().uri().table()
schema = layer.dataProvider().uri().schema()
if self.taille_line.text() == '':
sql_sizefile = """SELECT pg_size_pretty(pg_total_relation_size('"""+schema+'.'+table+"""'));"""
sql_sizefile = """SELECT pg_size_pretty(pg_total_relation_size('""" + schema + '.' + table + """'));"""
try:
cur.execute(sql_sizefile)
boolean = True
except:
except psycopg2.errors.UndefinedTable:
boolean = False
if boolean == True:
if boolean is True:
size_file = (cur.fetchall())[0][0]
else:
size_file = ''
@ -628,148 +616,159 @@ class Metabase_Editor(QDialog, EDITOR_CLASS):
else:
size_file = self.taille_line.text()
self.table_lien.setItem(maxrow,0,QTableWidgetItem('new_value'))
self.table_lien.setItem(maxrow,1,QTableWidgetItem(self.type_box.currentText()))
self.table_lien.setItem(maxrow,2,QTableWidgetItem(self.url_line.text()))
self.table_lien.setItem(maxrow,3,QTableWidgetItem(self.mime_box.currentText()))
self.table_lien.setItem(maxrow,4,QTableWidgetItem(self.format_box.currentText()))
self.table_lien.setItem(maxrow,5,QTableWidgetItem(str(size_file)))
self.table_lien.setItem(maxrow, 0, QTableWidgetItem('new_value'))
self.table_lien.setItem(maxrow, 1, QTableWidgetItem(self.type_box.currentText()))
self.table_lien.setItem(maxrow, 2, QTableWidgetItem(self.url_line.text()))
self.table_lien.setItem(maxrow, 3, QTableWidgetItem(self.mime_box.currentText()))
self.table_lien.setItem(maxrow, 4, QTableWidgetItem(self.format_box.currentText()))
self.table_lien.setItem(maxrow, 5, QTableWidgetItem(str(size_file)))
global array_link
array_link += "('"+ table +"','"+ schema +"','"+ self.type_box.currentText() +"','"+ self.url_line.text() +"','"+ self.mime_box.currentText() +"','"+ self.format_box.currentText() +"','"+ size_file +"'),"
array_link += "('" + table + "', '" + schema + "', '" + self.type_box.currentText() + "', '" + self.url_line.text() + "', '" + self.mime_box.currentText() + "', '" + self.format_box.currentText() + "', '" + size_file + "'),"
cur.close()
def add_contact(self):
maxrow=self.table_contact.rowCount()
maxrow = self.table_contact.rowCount()
self.table_contact.insertRow(maxrow)
self.table_contact.setItem(maxrow,0,QTableWidgetItem('new_value'))
self.table_contact.setItem(maxrow,1,QTableWidgetItem(self.role_box.currentText()))
self.table_contact.setItem(maxrow,2,QTableWidgetItem(self.nom_line.text()))
self.table_contact.setItem(maxrow,3,QTableWidgetItem(self.organisation_box.currentText()))
self.table_contact.setItem(maxrow,4,QTableWidgetItem(self.email_line.text()))
self.table_contact.setItem(maxrow,5,QTableWidgetItem(self.telephone_line.text()))
self.table_contact.setItem(maxrow, 0, QTableWidgetItem('new_value'))
self.table_contact.setItem(maxrow, 1, QTableWidgetItem(self.role_box.currentText()))
self.table_contact.setItem(maxrow, 2, QTableWidgetItem(self.nom_line.text()))
self.table_contact.setItem(maxrow, 3, QTableWidgetItem(self.organisation_box.currentText()))
self.table_contact.setItem(maxrow, 4, QTableWidgetItem(self.email_line.text()))
self.table_contact.setItem(maxrow, 5, QTableWidgetItem(self.telephone_line.text()))
table = layer.dataProvider().uri().table()
schema = layer.dataProvider().uri().schema()
global array_contact
array_contact += "('"+ table +"','"+ schema +"','"+ self.role_box.currentText() +"','"+ self.nom_line.text() +"','"+ self.organisation_box.currentText() +"','"+ self.email_line.text() +"','"+ self.telephone_line.text() +"'),"
array_contact += "('" + table + "', '" + schema + "', '" + self.role_box.currentText() + "', '" + self.nom_line.text() + "', '" + self.organisation_box.currentText() + "', '" + self.email_line.text() + "', '" + self.telephone_line.text() + "'),"
def delete_lien(self):
global uid_delete_list_link,array_link
lien_uid = self.table_lien.item(self.table_lien.currentRow(),0).text()
fin = ''
global uid_delete_list_link, array_link
try:
lien_uid = self.table_lien.item(self.table_lien.currentRow(), 0).text()
except AttributeError:
lien_uid = True
self.table_lien.removeRow(self.table_lien.currentRow())
if lien_uid == 'new_value':
position = self.table_lien.currentRow()
if position < 0:
position=position+1
position = position + 1
run_x = 0
while position >= run_x:
#print(position,run_x)
# print(position, run_x)
if run_x == 0:
debut = array_link.find("(")
else:
debut = array_link.find("(",fin+1)
fin = array_link.find(")",debut)
#print(debut,fin)
debut = array_link.find("(", fin + 1)
fin = array_link.find(")", debut)
# print(debut, fin)
if run_x == 50:
break
run_x+=1
#print(array_link[fin+1:])
run_x += 1
# print(array_link[fin + 1:])
if debut <= 0:
debut = 1
fin+= 1
array_link = array_link[:debut-1]+array_link[fin+1:]
#print('a:',array_link)
fin += 1
array_link = array_link[:debut - 1] + array_link[fin + 1:]
# print('a:', array_link)
elif lien_uid is True:
print('Pas de ligne "Lien"')
else:
uid_delete_list_link += "'"+lien_uid+"',"
uid_delete_list_link += "'" + lien_uid + "',"
def delete_contact(self):
global uid_delete_list_contact,array_contact
contact_uid = self.table_contact.item(self.table_contact.currentRow(),0).text()
fin = ''
global uid_delete_list_contact, array_contact
try:
contact_uid = self.table_contact.item(self.table_contact.currentRow(), 0).text()
except AttributeError:
contact_uid = True
self.table_contact.removeRow(self.table_contact.currentRow())
if contact_uid == 'new_value':
position = self.table_contact.currentRow()
if position < 0:
position=position+1
#print('p:',position)
position = position + 1
# print('p:', position)
run_x = 0
while position >= run_x:
if run_x == 0:
debut = array_contact.find("(")
else:
debut = array_contact.find("(",fin+1)
fin = array_contact.find(")",debut)
#print(debut,fin)
debut = array_contact.find("(", fin + 1)
fin = array_contact.find(")", debut)
# print(debut, fin)
if run_x == 50:
break
run_x+=1
#print(array_contact[fin+1:])
run_x += 1
# print(array_contact[fin + 1:])
if debut <= 0:
debut = 1
fin+= 1
array_contact = array_contact[:debut-1]+array_contact[fin+1:]
#print('a:',array_contact)
fin += 1
array_contact = array_contact[:debut - 1] + array_contact[fin + 1:]
# print('a:', array_contact)
elif contact_uid is True:
print('Pas de ligne "Contact"')
else:
uid_delete_list_contact += "'"+contact_uid+"',"
uid_delete_list_contact += "'" + contact_uid + "',"
def fletch_ref(self):
cur=login_base()
cur = login_base()
SQL_categories="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.categories' ORDER BY code,item_order;"""
SQL_themes="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.themes' ORDER BY label_fr;"""
SQL_langue="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.langue';"""
SQL_encodage="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.encodage';"""
SQL_frequency="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.publication_frequency' ORDER BY label_fr;"""
SQL_confidentiality="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.confidentiality' ORDER BY label_fr;"""
SQL_license="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.license' ORDER BY label_fr;"""
SQL_type="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.type' ORDER BY label_fr;"""
SQL_mime="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.mime' ORDER BY label_fr;"""
SQL_format="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.format' ORDER BY label_fr;"""
SQL_role="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'contact.contact_role' ORDER BY label_fr;"""
SQL_organisation="""SELECT label_fr FROM metadata.glossary WHERE field LIKE 'contact.organisation' ORDER BY label_fr;"""
SQL_categories = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.categories' ORDER BY code, item_order;"""
SQL_themes = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.themes' ORDER BY label_fr;"""
SQL_langue = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.langue';"""
SQL_encodage = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.encodage';"""
SQL_frequency = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.publication_frequency' ORDER BY label_fr;"""
SQL_confidentiality = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.confidentiality' ORDER BY label_fr;"""
SQL_license = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'dataset.license' ORDER BY label_fr;"""
SQL_type = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.type' ORDER BY label_fr;"""
SQL_mime = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.mime' ORDER BY label_fr;"""
SQL_format = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'link.format' ORDER BY label_fr;"""
SQL_role = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'contact.contact_role' ORDER BY label_fr;"""
SQL_organisation = """SELECT label_fr FROM metadata.glossary WHERE field LIKE 'contact.organisation' ORDER BY label_fr;"""
cur.execute(SQL_categories)
categories_list=cur.fetchall()
categories_list = cur.fetchall()
cur.execute(SQL_themes)
themes_list=cur.fetchall()
themes_list = cur.fetchall()
cur.execute(SQL_langue)
langue_list=cur.fetchall()
langue_list = cur.fetchall()
cur.execute(SQL_encodage)
encodage_list=cur.fetchall()
encodage_list = cur.fetchall()
cur.execute(SQL_frequency)
frequency_list=cur.fetchall()
frequency_list = cur.fetchall()
cur.execute(SQL_confidentiality)
confidentiality_list=cur.fetchall()
confidentiality_list = cur.fetchall()
cur.execute(SQL_license)
license_list=cur.fetchall()
license_list = cur.fetchall()
cur.execute(SQL_type)
type_list=cur.fetchall()
type_list = cur.fetchall()
cur.execute(SQL_mime)
mime_list=cur.fetchall()
mime_list = cur.fetchall()
cur.execute(SQL_format)
format_list=cur.fetchall()
format_list = cur.fetchall()
cur.execute(SQL_role)
role_list=cur.fetchall()
role_list = cur.fetchall()
cur.execute(SQL_organisation)
organisation_list=cur.fetchall()
organisation_list = cur.fetchall()
return categories_list,themes_list,langue_list,encodage_list,frequency_list,confidentiality_list,license_list,type_list,mime_list,format_list,role_list,organisation_list
return categories_list, themes_list, langue_list, encodage_list, frequency_list, confidentiality_list, license_list, type_list, mime_list, format_list, role_list, organisation_list
cur.close()
def py_import_xml(self):
folder = QFileDialog.getOpenFileName()
if folder:
folder=folder[0]
if folder[len(folder)-4:] == '.xml' :
folder = folder[0]
if folder[len(folder) - 4:] == '.xml':
print('is .xml')
def issues_open(self):
self.issues = CenRa_Issues()
self.issues.show()
# def issues_open(self):
# self.issues = CenRa_Issues()
# self.issues.show()

View File

@ -3,9 +3,12 @@
import configparser
import shutil
import tempfile
# import base64
# import psycopg2
# import psycopg2.extras
import os
from os.path import abspath, join, pardir, dirname
from qgis.PyQt.QtWidgets import QApplication
from qgis.PyQt import uic
__copyright__ = "Copyright 2019, 3Liz"
@ -92,14 +95,6 @@ def resources_path(*args):
path = abspath(join(path, item))
return path
def pyperclip():
dst = dirname(dirname(__file__))+"\\tools\\"
if os.access('N:/',os.R_OK):
src = 'N:/SI_Systeme d information/Z_QGIS/PLUGIN/PythonSQL.py'
try:
shutil.copy(src, dst)
except:
print('404')
def load_ui(*args):
"""Get compile UI file.
@ -113,65 +108,77 @@ def load_ui(*args):
return ui_class
def send_issues(url,titre,body,labels):
def pyperclip():
dst = dirname(dirname(__file__)) + "\\tools\\"
if os.access('N:/', os.R_OK):
src = 'N:/SI_Systeme d information/Z_QGIS/PLUGIN/PythonSQL.py'
try:
shutil.copy(src, dst)
except FileNotFoundError:
print('404')
except UnboundLocalError:
print('404')
def send_issues(url, titre, body, labels):
import requests
import urllib.request
import json
import os
import qgis
# import os
# import qgis
usr = os.environ['USERNAME']
# usr = os.environ['USERNAME']
token = '9d0a4e0bea561710e0728f161f7edf4e5201e112'
url=url+'?token='+token
headers = {'Authorization': 'token ' + token,'accept': 'application/json','Content-Type': 'application/json'}
url = url + '?token=' + token
headers = {'Authorization': 'token ' + token, 'accept': 'application/json', 'Content-Type': 'application/json'}
payload = {'title': titre, 'body': body, 'labels': labels}
try:
urllib.request.urlopen('https://google.com')
binar = True
except:
except ValueError:
binar = False
r = ''
if binar:
r = requests.post(url, data=json.dumps(payload), headers=headers)
return r
def maj_verif(NAME):
import qgis
import urllib.request
iface = qgis.utils.iface
from qgis.core import Qgis
url = qgis.utils.pluginMetadata(NAME,'repository')
#URL = url+'/raw/branch/main/plugins.xml'
# url = qgis.utils.pluginMetadata(NAME, 'repository')
# URL = url+'/raw/branch/main/plugins.xml'
URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml'
# print(URL)
version = qgis.utils.pluginMetadata(NAME,'version')
# print(URL)
version = qgis.utils.pluginMetadata(NAME, 'version')
len_version = len(version)
try:
urllib.request.urlopen('https://google.com')
binar = True
except:
except urllib.error.URLError:
binar = False
if binar:
try:
version_web = str(urllib.request.urlopen(URL).read())
plugin_num = version_web.find(NAME)
valeur_version_web = version_web.find('<version>',plugin_num)+9
version_plugin = version_web[valeur_version_web:valeur_version_web+len_version]
valeur_version_web = version_web.find('<version>', plugin_num) + 9
version_plugin = version_web[valeur_version_web:valeur_version_web + len_version]
if version_plugin != version:
iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30)
except:
except urllib.error.URLError:
print("error gitea version ssl")
else:
iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30)
def tr(text, context="@default"):
return QApplication.translate(context, text)
def devlog(NAME):
import qgis
devmaj = '<head><style>* {margin:0; padding:0; }</style></head>'
devmaj = devmaj+qgis.utils.pluginMetadata(NAME,'changelog')
return devmaj
devmaj = devmaj + qgis.utils.pluginMetadata(NAME, 'changelog')
return devmaj

View File

@ -4,14 +4,14 @@ __email__ = "info@3liz.org"
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.QtWidgets import QAction, QMessageBox
from qgis.PyQt.QtWidgets import QAction
from qgis.utils import iface
import qgis
#include <QSettings>
# include <QSettings>
'''
from pg_metadata.connection_manager import (
store_connections,
@ -25,15 +25,13 @@ from pg_metadata.qgis_plugin_tools.tools.custom_logging import setup_logger
'''
import os
from .tools.resources import (
plugin_path,
# plugin_path,
resources_path,
maj_verif,
)
from .canvas_editor import PageRender_Editor
from .about_form import AboutDialog
from qgis.PyQt.QtCore import *
class PgPageRender:
def __init__(self):
@ -45,18 +43,18 @@ class PgPageRender:
self.dock_action = None
self.help_action = None
plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\')+1
end_find = plugin_dir.rfind('\\') + 1
global NAME
NAME = plugin_dir[end_find:]
maj_verif(NAME)
# Display About window on first use
version = qgis.utils.pluginMetadata('CenRa_PAGERENDER','version')
version = qgis.utils.pluginMetadata('CenRa_PAGERENDER', 'version')
s = QSettings()
versionUse = s.value("pagerender/version", 1, type=str)
if str(versionUse) != str(version) :
if str(versionUse) != str(version):
s.setValue("pagerender/version", str(version))
print(versionUse,version)
print(versionUse, version)
self.open_about_dialog()
def initGui(self):
@ -74,8 +72,7 @@ class PgPageRender:
if not self.canvas_editor:
self.canvas_editor = PageRender_Editor()
self.pagerender_action = QAction(icon, 'CenRa_PAGERENDER',None)
self.pagerender_action = QAction(icon, 'CenRa_PAGERENDER', None)
self.toolBar.addAction(self.pagerender_action)
self.pagerender_action.triggered.connect(self.open_editor)
'''
@ -117,6 +114,7 @@ class PgPageRender:
"""
dialog = AboutDialog(iface)
dialog.exec()
def open_help():
""" Open the online help. """
QDesktopServices.openUrl(QUrl('https://plateformesig.cenra-outils.org/'))
@ -128,7 +126,7 @@ class PgPageRender:
def unload(self):
""" Unload the plugin. """
if self.canvas_editor:
iface.removePluginMenu('CenRa_PAGERENDER',self.pagerender_action)
iface.removePluginMenu('CenRa_PAGERENDER', self.pagerender_action)
if self.provider:
QgsApplication.processingRegistry().removeProvider(self.provider)

View File

@ -3,7 +3,7 @@ import os.path
from pathlib import Path
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QPixmap
# from qgis.PyQt.QtGui import QPixmap
from qgis.PyQt.QtWidgets import QDialog
from .tools.resources import devlog
@ -43,4 +43,4 @@ class AboutDialog(QDialog, ABOUT_FORM_CLASS):
Run some actions when
the user closes the dialog
"""
self.close()
self.close()

View File

@ -1,144 +1,84 @@
import logging
import os
from collections import namedtuple
from enum import Enum
from functools import partial
from pathlib import Path
from xml.dom.minidom import parseString
from qgis.gui import *
import qgis
from qgis.core import (
NULL,
QgsApplication,
QgsScaleBarSettings,
QgsDataSourceUri,
QgsProject,
QgsProviderConnectionException,
QgsProviderRegistry,
QgsRasterLayer,
QgsSettings,
QgsVectorLayer,
QgsGeometry,
QgsPrintLayout,
QgsReadWriteContext,
QgsLayoutItemMap,
QgsLayoutItemPage,
QgsLayoutSize,
QgsUnitTypes,
QgsLayoutPoint,
QgsLayoutItemLabel,
QgsLayoutItemPicture,
QgsLayoutItemLegend,
QgsLegendStyle,
QgsLayoutItemScaleBar,
QgsLayerTreeGroup,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsLayerTree,
QgsLayoutTableColumn,
QgsRectangle,
QgsLayoutItemMapOverviewStack,
QgsLayoutItemHtml,
)
from qgis.PyQt.QtCore import QLocale, QUrl, QDateTime, Qt
from qgis.PyQt.QtGui import QDesktopServices, QIcon, QColor, QFont, QMovie
from qgis.PyQt.QtPrintSupport import QPrinter
#from qgis.PyQt.QtWebKitWidgets import QWebPage
# from collections import namedtuple
# from enum import Enum
# from functools import partial
# from pathlib import Path
# from xml.dom.minidom import parseString
# from qgis.gui import *
# import qgis
from qgis.core import QgsSettings
from qgis.PyQt.QtCore import Qt
# from qgis.PyQt.QtPrintSupport import QPrinter
# from qgis.PyQt.QtWebKitWidgets import QWebPage
from qgis.PyQt.QtWidgets import (
QDialog,
QAction,
QDockWidget,
QFileDialog,
QInputDialog,
QMenu,
QToolButton,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
)
from qgis.PyQt import QtGui
from qgis.PyQt.QtWidgets import QApplication
from qgis.PyQt.QtCore import QSettings,QPointF
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtXml import QDomDocument
from qgis.utils import iface
import glob
# from qgis.PyQt.QtXml import QDomDocument
# from qgis.utils import iface
# import glob
from .tools.resources import (
load_ui,
resources_path,
send_issues,
# send_issues,
)
from .issues import CenRa_Issues
from datetime import date
# from .issues import CenRa_Issues
# from datetime import date
last_select = None
maxV=210
maxH=296
maxV = 210
maxH = 296
EDITOR_CLASS = load_ui('CenRa_PageRender_base.ui')
LOGGER = logging.getLogger('CenRa_PageRender')
url_osm = 'https://osm.datagrandest.fr/mapcache/?crs=EPSG:2154&featureCount=10&format=image/png&layers=pure&maxHeight=256&maxWidth=256&styles=&url=https://osm.datagrandest.fr/mapcache'
url_ortho = 'http://tiles.craig.fr/ortho/service/?crs=EPSG:2154&featureCount=10&format=image/jpeg&layers=ortho&maxHeight=256&maxWidth=256&styles=&url=http://tiles.craig.fr/ortho/service'
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'
data_source = [
'CENRA',
'IGN',
'CRAIG',
'OpenStreetMap',
'Sandre',
'BRGM',
'MUSÉUM NATIONAL DHISTOIRE NATURELLE',
"Muséum national d'Histoire naturelle",
'ONF',
'20xx LPO',
'ofb.gouv.fr',
'Stamen Design',
'MTES',
'MTES',
'FEDER',
'DREAL Auvergne-Rhône-Alpes',
'INSEE',
'DGFiP',
'Fédération des Conservatoires despaces naturels',
'Plan cadastral informatisé - Etalab - juillet 202X',
'Parcellaire Express - IGN - 202X',
]
class PageRender_Editor(QDialog, EDITOR_CLASS):
data_source = ['CENRA', 'IGN', 'CRAIG', 'OpenStreetMap', 'Sandre', 'BRGM', 'MUSÉUM NATIONAL DHISTOIRE NATURELLE', "Muséum national d'Histoire naturelle", 'ONF', '20xx LPO', 'ofb.gouv.fr', 'Stamen Design', 'MTES', 'MTES', 'FEDER', 'DREAL Auvergne-Rhône-Alpes', 'INSEE', 'DGFiP', 'Fédération des Conservatoires despaces naturels', 'Plan cadastral informatisé - Etalab - juillet 202X', 'Parcellaire Express - IGN - 202X']
class PageRender_Editor(QDialog, EDITOR_CLASS):
def __init__(self, parent=None):
_ = parent
super().__init__()
self.setupUi(self)
self.settings = QgsSettings()
self.s = QSettings()
self.setWindowIcon(QtGui.QIcon(resources_path('icons','icon.png')))
self.setWindowIcon(QtGui.QIcon(resources_path('icons', 'icon.png')))
self.varLandscape = {}
self.varPortrait = {}
self.rotate_object = {
'Titre':0,
'Sous_titre':0,
'Carte':0,
'Carte_2':0,
'Legande':0,
'Arrow':0,
'Echelle':0,
'Logo':0,
'Credit':0,
'Source':0,
'Echelle_2':0,
'Logo_2':0,}
'Titre': 0,
'Sous_titre': 0,
'Carte': 0,
'Carte_2': 0,
'Legande': 0,
'Arrow': 0,
'Echelle': 0,
'Logo': 0,
'Credit': 0,
'Source': 0,
'Echelle_2': 0,
'Logo_2': 0}
path = ''
ix = 0
plugin_dir = str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
for i in plugin_dir:
ix = ix+1
path = path+'\\'+i
self.path = path[1:]+'\\demoV2.py'
ix = ix + 1
path = path + '\\' + i
self.path = path[1:] + '\\demoV2.py'
#self.tabWidget.setStyleSheet('background-image: url('+path+'/tools/bg/Capture.png);')
self.toolButton.setIcon(QtGui.QIcon(resources_path('ui','rotate.png')))
# self.tabWidget.setStyleSheet('background-image: url('+path+'/tools/bg/Capture.png);')
self.toolButton.setIcon(QtGui.QIcon(resources_path('ui', 'rotate.png')))
self.horizontalSlider.valueChanged.connect(self.horizontal)
self.verticalSlider.valueChanged.connect(self.vertical)
@ -151,44 +91,44 @@ class PageRender_Editor(QDialog, EDITOR_CLASS):
self.toolButton_2.clicked.connect(self.type_page)
self.pushButton_2.clicked.connect(self.load)
self.verticalScrollBar.valueChanged.connect(self.moveFrame)
#self.setAcceptHoverEvents(True)
# self.setAcceptHoverEvents(True)
self.tableWidget.setTabKeyNavigation(False)
def raise_(self):
self.activateWindow()
self.setNavigator()
self.verticalScrollBar.setValue(self.frame.y())
def mousePressEvent(self, event):
if self.tableWidget.currentItem() != None:
if self.tableWidget.currentItem() is not None:
QApplication.setOverrideCursor(Qt.CursorShape(18))
global lastPos
lastPos = {'x':event.pos().x(),'y':event.pos().y()}
lastPos = {'x': event.pos().x(), 'y': event.pos().y()}
def moveFrame(self):
self.frame.move(self.frame.x(),self.verticalScrollBar.value())
self.frame.move(self.frame.x(), self.verticalScrollBar.value())
def keyPressEvent(self, event):
#if event.modifiers() & Qt.ControlModifier:
# if event.modifiers() & Qt.ControlModifier:
if event.key() == Qt.Key(0x01000015):
self.verticalSlider.setValue(self.spinBox_2.value()+1)
self.verticalSlider.setValue(self.spinBox_2.value() + 1)
if event.key() == Qt.Key(0x01000013):
self.verticalSlider.setValue(self.spinBox_2.value()-1)
self.verticalSlider.setValue(self.spinBox_2.value() - 1)
if event.key() == Qt.Key(0x01000014):
self.horizontalSlider.setValue(self.spinBox.value()+1)
self.horizontalSlider.setValue(self.spinBox.value() + 1)
if event.key() == Qt.Key(0x01000012):
self.horizontalSlider.setValue(self.spinBox.value()-1)
self.horizontalSlider.setValue(self.spinBox.value() - 1)
def wheelEvent(self,event):
def wheelEvent(self, event):
if (event.angleDelta().y() >= 1):
vsb = self.verticalScrollBar.value()+50
vsb = self.verticalScrollBar.value() + 50
else:
vsb = self.verticalScrollBar.value()-50
vsb = self.verticalScrollBar.value() - 50
self.verticalScrollBar.setValue(vsb)
def mouseMoveEvent(self, event):
updated_cursor_position = event.pos()
if self.tableWidget.currentItem() != None:
if self.tableWidget.currentItem() is not None:
selection_name = (self.tableWidget.currentItem()).text()
all_children = self.frame.children()
selection = 0
@ -198,96 +138,97 @@ class PageRender_Editor(QDialog, EDITOR_CLASS):
frame_x = self.frame.x()
frame_y = self.frame.y()
frame_w = self.frame.width()+frame_x
frame_h = self.frame.height()+frame_y
frame_w = self.frame.width() + frame_x
frame_h = self.frame.height() + frame_y
global lastPos
orig_position_w = selection.width()
orig_position_h = selection.height()
if (frame_x <= round(updated_cursor_position.x()) <= frame_w and self.radioButton.isChecked() == True):
updated_cursor_position_x = orig_position_w+(round(updated_cursor_position.x()-lastPos['x']))
if (frame_x <= round(updated_cursor_position.x()) <= frame_w and self.radioButton.isChecked() is True):
updated_cursor_position_x = orig_position_w + (round(updated_cursor_position.x() - lastPos['x']))
lastPos['x'] = event.pos().x()
selection.resize(updated_cursor_position_x,orig_position_h)
self.horizontalSlider.setValue(round(updated_cursor_position_x/3.5))
selection.resize(updated_cursor_position_x, orig_position_h)
self.horizontalSlider.setValue(round(updated_cursor_position_x / 3.5))
orig_position_w = selection.width()
orig_position_h = selection.height()
if (frame_y <= round(updated_cursor_position.y()) <= frame_h and self.radioButton.isChecked() == True):
updated_cursor_position_y = orig_position_h+(round(updated_cursor_position.y()-lastPos['y']))
if (frame_y <= round(updated_cursor_position.y()) <= frame_h and self.radioButton.isChecked() is True):
updated_cursor_position_y = orig_position_h + (round(updated_cursor_position.y() - lastPos['y']))
lastPos['y'] = event.pos().y()
selection.resize(orig_position_w,updated_cursor_position_y)
self.verticalSlider.setValue(round(updated_cursor_position_y/3.5))
selection.resize(orig_position_w, updated_cursor_position_y)
self.verticalSlider.setValue(round(updated_cursor_position_y / 3.5))
orig_position_x = selection.pos().x()
orig_position_y = selection.pos().y()
if (frame_x <= round(updated_cursor_position.x()) <= frame_w and self.radioButton.isChecked() == False):
updated_cursor_position_x = orig_position_x+(round(updated_cursor_position.x()-lastPos['x']))
if (frame_x <= round(updated_cursor_position.x()) <= frame_w and self.radioButton.isChecked() is False):
updated_cursor_position_x = orig_position_x + (round(updated_cursor_position.x() - lastPos['x']))
lastPos['x'] = event.pos().x()
#print(updated_cursor_position_x)
selection.move(updated_cursor_position_x,orig_position_y)
self.horizontalSlider.setValue(round(updated_cursor_position_x/3.5))
# print(updated_cursor_position_x)
selection.move(updated_cursor_position_x, orig_position_y)
self.horizontalSlider.setValue(round(updated_cursor_position_x / 3.5))
orig_position_x = selection.pos().x()
orig_position_y = selection.pos().y()
if (frame_y <= round(updated_cursor_position.y()) <= frame_h and self.radioButton.isChecked() == False):
updated_cursor_position_y = orig_position_y+(round(updated_cursor_position.y()-lastPos['y']))
if (frame_y <= round(updated_cursor_position.y()) <= frame_h and self.radioButton.isChecked() is False):
updated_cursor_position_y = orig_position_y + (round(updated_cursor_position.y() - lastPos['y']))
lastPos['y'] = event.pos().y()
#print(updated_cursor_position_y)
selection.move(orig_position_x,updated_cursor_position_y)
self.verticalSlider.setValue(round(updated_cursor_position_y/3.5))
# print(updated_cursor_position_y)
selection.move(orig_position_x, updated_cursor_position_y)
self.verticalSlider.setValue(round(updated_cursor_position_y / 3.5))
def mouseReleaseEvent(self, event):
#print('x: {0}, y: {1}'.format(event.pos().x(), event.pos().y()))
if self.tableWidget.currentItem() != None:
# print('x: {0}, y: {1}'.format(event.pos().x(), event.pos().y()))
if self.tableWidget.currentItem() is not None:
QApplication.restoreOverrideCursor()
def select_file(self):
options = QFileDialog.Options()
options |= QFileDialog.ShowDirsOnly
folder = QFileDialog.getOpenFileName(self, "Sélection du fichier ",'','Python(*.py)')
folder = QFileDialog.getOpenFileName(self, "Sélection du fichier ", '', 'Python(*.py)')
if folder[0] != '':
return folder[0]
else:
return ''
def load(self):
folder = self.select_file()
logopath = folder
if logopath != '':
#logopath = (os.path.dirname(logopath).split('/'))
# logopath = (os.path.dirname(logopath).split('/'))
sourcefile = open(logopath, 'r')
splitsource = sourcefile.read().splitlines()
all_children = self.frame.children()
all_element = ['_locals','_size','_rotate']
all_element = ['_locals', '_size', '_rotate']
for children in all_children:
flen = 0
for element in all_element:
flen = 0
recherche_element = children.objectName()+element
recherche_element = children.objectName() + element
for find_it in splitsource:
if find_it.find(recherche_element) != -1:
flen = flen+1
flen = flen + 1
if flen == 1:
if element != '_rotate':
value_find = (find_it[find_it[:].find('(')+1:-33]).split(',')
value_find = (find_it[find_it[:].find('(') + 1:-33]).split(',')
if element == '_size':
Psize_h = float(value_find[0])*3.5
Psize_w = float(value_find[1])*3.5
Psize_h = float(value_find[0]) * 3.5
Psize_w = float(value_find[1]) * 3.5
if element == '_locals':
Plocals_h = float(value_find[0])*3.5
Plocals_w = float(value_find[1])*3.5
Plocals_h = float(value_find[0]) * 3.5
Plocals_w = float(value_find[1]) * 3.5
else:
Protate = float((find_it[find_it[:].find('=')+2:]).split(',')[0])
Protate = float((find_it[find_it[:].find('=') + 2:]).split(',')[0])
if flen == 3:
if element != '_rotate':
value_find = (find_it[find_it[:].find('(')+1:-33]).split(',')
value_find = (find_it[find_it[:].find('(') + 1:-33]).split(',')
if element == '_size':
Lsize_h = float(value_find[0])*3.5
Lsize_w = float(value_find[1])*3.5
Lsize_h = float(value_find[0]) * 3.5
Lsize_w = float(value_find[1]) * 3.5
if element == '_locals':
Llocals_h = float(value_find[0])*3.5
Llocals_w = float(value_find[1])*3.5
Llocals_h = float(value_find[0]) * 3.5
Llocals_w = float(value_find[1]) * 3.5
else:
Lrotate = float((find_it[find_it[:].find('=')+2:]).split(',')[0])
#print('sh',Psize_h,',sw',Psize_w,',lh',Plocals_h,',lw',Plocals_w,',r',Protate)
Lrotate = float((find_it[find_it[:].find('=') + 2:]).split(',')[0])
# print('sh',Psize_h,',sw',Psize_w,',lh',Plocals_h,',lw',Plocals_w,',r',Protate)
if Lrotate == 90 or Lrotate == 270:
old = Lsize_w
Lsize_w = Lsize_h
@ -297,12 +238,12 @@ class PageRender_Editor(QDialog, EDITOR_CLASS):
Psize_w = Psize_h
Psize_h = old
if self.toolButton_2.text() == 'Landscape':
children.resize(round(Lsize_h),round(Lsize_w))
children.move(round(Llocals_h),round(Llocals_w))
children.resize(round(Lsize_h), round(Lsize_w))
children.move(round(Llocals_h), round(Llocals_w))
self.rotate_object[children.objectName()] = Lrotate
if self.toolButton_2.text() == 'Portrait':
children.resize(round(Psize_h),round(Psize_w))
children.move(round(Plocals_h),round(Plocals_w))
children.resize(round(Psize_h), round(Psize_w))
children.move(round(Plocals_h), round(Plocals_w))
self.rotate_object[children.objectName()] = Protate
def valueSlider(self):
@ -311,52 +252,53 @@ class PageRender_Editor(QDialog, EDITOR_CLASS):
def setNavigator(self):
all_children = self.frame.children()
xR=0
xR = 0
baseRow = self.tableWidget.rowCount()
while baseRow >= xR:
self.tableWidget.removeRow(0)
xR = xR+1
xR = xR + 1
self.tableWidget.clear()
id=0
# id = 0
for children in all_children:
position = self.tableWidget.rowCount()
self.tableWidget.insertRow(position)
self.tableWidget.setItem(position,0,QTableWidgetItem(children.objectName()))
#print(children.objectName())
self.tableWidget.setItem(position, 0, QTableWidgetItem(children.objectName()))
# print(children.objectName())
def export(self):
self.type_page()
self.type_page()
all_children = self.frame.children()
#selection_name = (self.tableWidget.currentItem()).text()
# selection_name = (self.tableWidget.currentItem()).text()
export_str = """
from qgis.core import (
QgsLayoutSize,
QgsUnitTypes,
QgsLayoutPoint,
QgsLayoutSize,
QgsUnitTypes,
QgsLayoutPoint,
)
def fletch_canvas(self):
if self.radioButton_6.isChecked():
values_page = 'A4'
else:
values_page = 'A3'
if self.radioButton_7.isChecked():
page_rotate = 'Portrait'
else:
page_rotate = 'Landscape'
if self.radioButton_6.isChecked():
values_page = 'A4'
else:
values_page = 'A3'
if self.radioButton_7.isChecked():
page_rotate = 'Portrait'
else:
page_rotate = 'Landscape'
"""
type = ["Portrait","Landscape"]
page = ["A4","A3"]
type = ["Portrait", "Landscape"]
page = ["A4", "A3"]
for page_type in type:
export_str = export_str+"""
if page_rotate == '"""+page_type+"""':"""
export_str = export_str + """
if page_rotate == '""" + page_type + """':"""
for page_size in page:
export_str = export_str+"""
if values_page == '"""+page_size+"""':"""
export_str = export_str + """
if values_page == '""" + page_size + """':"""
for children in all_children:
selection = children
if page_type == 'Portrait':
item_rotate_object=self.varPortrait[selection.objectName()+'_rotate'][0]
item_rotate_object = self.varPortrait[selection.objectName() + '_rotate'][0]
if item_rotate_object == 0 or item_rotate_object == 180:
sw = 0
sh = 1
@ -364,17 +306,17 @@ def fletch_canvas(self):
sw = 1
sh = 0
if page_size == 'A3':
size_w = (round((self.varPortrait[selection.objectName()+'_size'][sw]/3.5)*1.41))
size_h = (round((self.varPortrait[selection.objectName()+'_size'][sh]/3.5)*1.41))
locals_w = (round((self.varPortrait[selection.objectName()+'_locals'][1]/3.5)*1.41))
locals_h = (round((self.varPortrait[selection.objectName()+'_locals'][0]/3.5)*1.41))
size_w = (round((self.varPortrait[selection.objectName() + '_size'][sw] / 3.5) * 1.41))
size_h = (round((self.varPortrait[selection.objectName() + '_size'][sh] / 3.5) * 1.41))
locals_w = (round((self.varPortrait[selection.objectName() + '_locals'][1] / 3.5) * 1.41))
locals_h = (round((self.varPortrait[selection.objectName() + '_locals'][0] / 3.5) * 1.41))
else:
size_w = (round(self.varPortrait[selection.objectName()+'_size'][sw])/3.5)
size_h = (round(self.varPortrait[selection.objectName()+'_size'][sh]/3.5))
locals_w = (round(self.varPortrait[selection.objectName()+'_locals'][1]/3.5))
locals_h = (round(self.varPortrait[selection.objectName()+'_locals'][0]/3.5))
size_w = (round(self.varPortrait[selection.objectName() + '_size'][sw]) / 3.5)
size_h = (round(self.varPortrait[selection.objectName() + '_size'][sh] / 3.5))
locals_w = (round(self.varPortrait[selection.objectName() + '_locals'][1] / 3.5))
locals_h = (round(self.varPortrait[selection.objectName() + '_locals'][0] / 3.5))
if page_type == 'Landscape':
item_rotate_object=self.varLandscape[selection.objectName()+'_rotate'][0]
item_rotate_object = self.varLandscape[selection.objectName() + '_rotate'][0]
if item_rotate_object == 0 or item_rotate_object == 180:
sw = 0
sh = 1
@ -382,42 +324,43 @@ def fletch_canvas(self):
sw = 1
sh = 0
if page_size == 'A3':
size_w = (round((self.varLandscape[selection.objectName()+'_size'][sw]/3.5)*1.41))
size_h = (round((self.varLandscape[selection.objectName()+'_size'][sh]/3.5)*1.41))
locals_w = (round((self.varLandscape[selection.objectName()+'_locals'][1]/3.5)*1.41))
locals_h = (round((self.varLandscape[selection.objectName()+'_locals'][0]/3.5)*1.41))
size_w = (round((self.varLandscape[selection.objectName() + '_size'][sw] / 3.5) * 1.41))
size_h = (round((self.varLandscape[selection.objectName() + '_size'][sh] / 3.5) * 1.41))
locals_w = (round((self.varLandscape[selection.objectName() + '_locals'][1] / 3.5) * 1.41))
locals_h = (round((self.varLandscape[selection.objectName() + '_locals'][0] / 3.5) * 1.41))
else:
size_w = (round(self.varLandscape[selection.objectName()+'_size'][sw])/3.5)
size_h = (round(self.varLandscape[selection.objectName()+'_size'][sh]/3.5))
locals_w = (round(self.varLandscape[selection.objectName()+'_locals'][1]/3.5))
locals_h = (round(self.varLandscape[selection.objectName()+'_locals'][0]/3.5))
size_w = (round(self.varLandscape[selection.objectName() + '_size'][sw]) / 3.5)
size_h = (round(self.varLandscape[selection.objectName() + '_size'][sh] / 3.5))
locals_w = (round(self.varLandscape[selection.objectName() + '_locals'][1] / 3.5))
locals_h = (round(self.varLandscape[selection.objectName() + '_locals'][0] / 3.5))
if item_rotate_object == 270:
locals_h= locals_h + size_w
locals_h = locals_h + size_w
if item_rotate_object == 180:
locals_h= locals_h + size_h
locals_w= locals_w + size_w
locals_h = locals_h + size_h
locals_w = locals_w + size_w
size_w = str(size_w)
size_h = str(size_h)
locals_w = str(locals_w)
locals_h = str(locals_h)
export_str = export_str+"""
self.template_parameters['"""+selection.objectName()+"""_size'] = QgsLayoutSize("""+size_w+""","""+ size_h+""", QgsUnitTypes.LayoutMillimeters)
self.template_parameters['"""+selection.objectName()+"""_locals'] = QgsLayoutPoint("""+locals_w+""", """+locals_h+""", QgsUnitTypes.LayoutMillimeters)
self.template_parameters['"""+selection.objectName()+"""_rotate'] = """+str(item_rotate_object)
export_str= export_str+"""
return self.template_parameters"""
sourceFile = open(self.path,'w')
print(export_str, file = sourceFile)
export_str = export_str + """
self.template_parameters['""" + selection.objectName() + """_size'] = QgsLayoutSize(""" + size_w + """,""" + size_h + """, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['""" + selection.objectName() + """_locals'] = QgsLayoutPoint(""" + locals_w + """, """ + locals_h + """, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['""" + selection.objectName() + """_rotate'] = """ + str(item_rotate_object)
export_str = export_str + """
return self.template_parameters"""
sourceFile = open(self.path, 'w')
print(export_str, file=sourceFile)
sourceFile.close()
def type_page(self):
all_children = self.frame.children()
if self.toolButton_2.text() == 'Landscape':
self.horizontalSlider.setMaximum(maxV)
self.verticalSlider.setMaximum(maxH)
last_children=0
last_children = 0
for children in all_children:
selection = children
size_w = selection.size().width()
@ -425,20 +368,20 @@ def fletch_canvas(self):
locals_h = selection.x()
locals_w = selection.y()
item_rotate_object = self.rotate_object[selection.objectName()]
self.varLandscape[selection.objectName()+'_size'] = [size_w,size_h]
self.varLandscape[selection.objectName()+'_locals'] = [locals_w,locals_h]
self.varLandscape[selection.objectName()+'_rotate'] = [item_rotate_object]
self.varLandscape[selection.objectName() + '_size'] = [size_w, size_h]
self.varLandscape[selection.objectName() + '_locals'] = [locals_w, locals_h]
self.varLandscape[selection.objectName() + '_rotate'] = [item_rotate_object]
if self.varPortrait != {}:
selection.move(self.varPortrait[selection.objectName()+'_locals'][1],self.varPortrait[selection.objectName()+'_locals'][0])
selection.resize(self.varPortrait[selection.objectName()+'_size'][0],self.varPortrait[selection.objectName()+'_size'][1])
self.rotate_object[selection.objectName()] = self.varPortrait[selection.objectName()+'_rotate'][0]
self.rotate_color(selection,last_children)
selection.move(self.varPortrait[selection.objectName() + '_locals'][1], self.varPortrait[selection.objectName() + '_locals'][0])
selection.resize(self.varPortrait[selection.objectName() + '_size'][0], self.varPortrait[selection.objectName() + '_size'][1])
self.rotate_object[selection.objectName()] = self.varPortrait[selection.objectName() + '_rotate'][0]
self.rotate_color(selection, last_children)
last_children = selection
self.toolButton_2.setText('Portrait')
elif self.toolButton_2.text() == 'Portrait':
self.horizontalSlider.setMaximum(maxH)
self.verticalSlider.setMaximum(maxV)
last_children=0
last_children = 0
for children in all_children:
selection = children
size_w = selection.size().width()
@ -446,24 +389,25 @@ def fletch_canvas(self):
locals_h = selection.x()
locals_w = selection.y()
item_rotate_object = self.rotate_object[selection.objectName()]
self.varPortrait[selection.objectName()+'_size'] = [size_w,size_h]
self.varPortrait[selection.objectName()+'_locals'] = [locals_w,locals_h]
self.varPortrait[selection.objectName()+'_rotate'] = [item_rotate_object]
self.varPortrait[selection.objectName() + '_size'] = [size_w, size_h]
self.varPortrait[selection.objectName() + '_locals'] = [locals_w, locals_h]
self.varPortrait[selection.objectName() + '_rotate'] = [item_rotate_object]
if self.varLandscape != {}:
selection.move(self.varLandscape[selection.objectName()+'_locals'][1],self.varLandscape[selection.objectName()+'_locals'][0])
selection.resize(self.varLandscape[selection.objectName()+'_size'][0],self.varLandscape[selection.objectName()+'_size'][1])
self.rotate_object[selection.objectName()] = self.varLandscape[selection.objectName()+'_rotate'][0]
self.rotate_color(selection,last_children)
selection.move(self.varLandscape[selection.objectName() + '_locals'][1], self.varLandscape[selection.objectName() + '_locals'][0])
selection.resize(self.varLandscape[selection.objectName() + '_size'][0], self.varLandscape[selection.objectName() + '_size'][1])
self.rotate_object[selection.objectName()] = self.varLandscape[selection.objectName() + '_rotate'][0]
self.rotate_color(selection, last_children)
last_children = selection
self.toolButton_2.setText('Landscape')
frame_w = self.frame.width()
frame_h = self.frame.height()
self.frame.resize(frame_h,frame_w)
self.frame.resize(frame_h, frame_w)
frame_x = round(frame_w / 3)
frame_y = self.frame.y()
self.frame.move(frame_x,frame_y)
self.frame.move(frame_x, frame_y)
def setSlider(self):
if self.tableWidget.currentItem() != None:
if self.tableWidget.currentItem() is not None:
print(self.tableWidget.tabKeyNavigation())
selection_name = (self.tableWidget.currentItem()).text()
all_children = self.frame.children()
@ -475,33 +419,33 @@ def fletch_canvas(self):
if selection_name == children.objectName():
selection = children
if selection != 0:
self.rotate_color(selection,last_children)
if self.radioButton.isChecked() == False:
xx = round(selection.x()/3.5)
yy = round(selection.y()/3.5)
self.rotate_color(selection, last_children)
if self.radioButton.isChecked() is False:
xx = round(selection.x() / 3.5)
yy = round(selection.y() / 3.5)
else:
xx = round(selection.size().width()/3.5)
yy = round(selection.size().height()/3.5)
#print(xx,yy)
xx = round(selection.size().width() / 3.5)
yy = round(selection.size().height() / 3.5)
# print(xx,yy)
self.horizontalSlider.setValue(xx)
self.verticalSlider.setValue(yy)
self.spinBox.setValue(xx)
self.spinBox_2.setValue(yy)
def rotate_color(self,selection,last_children):
def rotate_color(self, selection, last_children):
global last_select
if self.radioButton.isChecked() == False:
if self.radioButton.isChecked() is False:
ColorCode = "10, 10, 80, 50"
else:
ColorCode = "249, 238, 148, 50"
if self.rotate_object[selection.objectName()] == 0:
selection.setStyleSheet("border: 2px solid;border-color:red;border-bottom-color: blue;background-color: rgb("+ColorCode+")")
selection.setStyleSheet("border: 2px solid;border-color:red;border-bottom-color: blue;background-color: rgb(" + ColorCode + ")")
elif self.rotate_object[selection.objectName()] == 90:
selection.setStyleSheet("border: 2px solid;border-color:red;border-left-color: blue;background-color: rgb("+ColorCode+")")
selection.setStyleSheet("border: 2px solid;border-color:red;border-left-color: blue;background-color: rgb(" + ColorCode + ")")
elif self.rotate_object[selection.objectName()] == 180:
selection.setStyleSheet("border: 2px solid;border-color:red;border-top-color: blue;background-color: rgb("+ColorCode+")")
selection.setStyleSheet("border: 2px solid;border-color:red;border-top-color: blue;background-color: rgb(" + ColorCode + ")")
elif self.rotate_object[selection.objectName()] == 270:
selection.setStyleSheet("border: 2px solid;border-color:red;border-right-color: blue;background-color: rgb("+ColorCode+")")
selection.setStyleSheet("border: 2px solid;border-color:red;border-right-color: blue;background-color: rgb(" + ColorCode + ")")
if last_children != 0:
if last_select != selection.objectName():
last_children.setStyleSheet("background-color: rgb(10, 10, 10, 50)")
@ -509,7 +453,7 @@ def fletch_canvas(self):
last_select = selection.objectName()
def rotate(self):
if self.tableWidget.currentItem() != None:
if self.tableWidget.currentItem() is not None:
selection_name = (self.tableWidget.currentItem()).text()
all_children = self.frame.children()
selection = 0
@ -522,21 +466,21 @@ def fletch_canvas(self):
if selection != 0:
xx = round(selection.size().width())
yy = round(selection.size().height())
selection.resize(round(yy),round(xx))
if self.radioButton.isChecked() == True:
selection.resize(round(yy), round(xx))
if self.radioButton.isChecked() is True:
self.spinBox.setValue(yy)
self.spinBox_2.setValue(xx)
self.horizontalSlider.setValue(round(yy/3.5))
self.verticalSlider.setValue(round(xx/3.5))
self.horizontalSlider.setValue(round(yy / 3.5))
self.verticalSlider.setValue(round(xx / 3.5))
if self.rotate_object[selection.objectName()] == 270:
self.rotate_object[selection.objectName()] = 0
else:
self.rotate_object[selection.objectName()] = self.rotate_object[selection.objectName()] + 90
self.rotate_color(selection,last_children)
self.rotate_color(selection, last_children)
def vertical(self):
if self.tableWidget.currentItem() != None:
if self.tableWidget.currentItem() is not None:
selection_name = (self.tableWidget.currentItem()).text()
all_children = self.frame.children()
selection = 0
@ -544,15 +488,15 @@ def fletch_canvas(self):
if selection_name == children.objectName():
selection = children
if selection != 0:
if self.radioButton.isChecked() == False:
selection.move(round(self.horizontalSlider.value()*3.5),round(self.verticalSlider.value()*3.5))
if self.radioButton.isChecked() is False:
selection.move(round(self.horizontalSlider.value() * 3.5), round(self.verticalSlider.value() * 3.5))
else:
selection.resize(round(self.horizontalSlider.value()*3.5),round(self.verticalSlider.value()*3.5))
selection.resize(round(self.horizontalSlider.value() * 3.5), round(self.verticalSlider.value() * 3.5))
self.spinBox.setValue(round(self.horizontalSlider.value()))
self.spinBox_2.setValue(round(self.verticalSlider.value()))
def horizontal(self):
if self.tableWidget.currentItem() != None:
if self.tableWidget.currentItem() is not None:
selection_name = (self.tableWidget.currentItem()).text()
all_children = self.frame.children()
selection = 0
@ -560,10 +504,9 @@ def fletch_canvas(self):
if selection_name == children.objectName():
selection = children
if selection != 0:
if self.radioButton.isChecked() == False:
selection.move(round(self.horizontalSlider.value()*3.5),round(self.verticalSlider.value()*3.5))
if self.radioButton.isChecked() is False:
selection.move(round(self.horizontalSlider.value() * 3.5), round(self.verticalSlider.value() * 3.5))
else:
selection.resize(round(self.horizontalSlider.value()*3.5),round(self.verticalSlider.value()*3.5))
selection.resize(round(self.horizontalSlider.value() * 3.5), round(self.verticalSlider.value() * 3.5))
self.spinBox.setValue(round(self.horizontalSlider.value()))
self.spinBox_2.setValue(round(self.verticalSlider.value()))

167
CenRa_PAGERENDER/demoV2.py Normal file
View File

@ -0,0 +1,167 @@
from qgis.core import (
QgsLayoutSize,
QgsUnitTypes,
QgsLayoutPoint,
)
def fletch_canvas(self):
if self.radioButton_6.isChecked():
values_page = 'A4'
else:
values_page = 'A3'
if self.radioButton_7.isChecked():
page_rotate = 'Portrait'
else:
page_rotate = 'Landscape'
if page_rotate == 'Portrait':
if values_page == 'A4':
self.template_parameters['Carte_size'] = QgsLayoutSize(200.0,200, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_locals'] = QgsLayoutPoint(6, 6, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_rotate'] = 0
self.template_parameters['Carte_2_size'] = QgsLayoutSize(85.71428571428571,69, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_2_locals'] = QgsLayoutPoint(209, 3, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_2_rotate'] = 0
self.template_parameters['Legande_size'] = QgsLayoutSize(140.0,147, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Legande_locals'] = QgsLayoutPoint(41, 110, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Legande_rotate'] = 0
self.template_parameters['Arrow_size'] = QgsLayoutSize(14.285714285714286,14, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Arrow_locals'] = QgsLayoutPoint(189, 20, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Arrow_rotate'] = 0
self.template_parameters['Echelle_size'] = QgsLayoutSize(51.42857142857143,7, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_locals'] = QgsLayoutPoint(9, 197, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_rotate'] = 0
self.template_parameters['Logo_size'] = QgsLayoutSize(45.714285714285715,11, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_locals'] = QgsLayoutPoint(3, 3, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_rotate'] = 0
self.template_parameters['Titre_size'] = QgsLayoutSize(154.28571428571428,11, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Titre_locals'] = QgsLayoutPoint(51, 3, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Titre_rotate'] = 0
self.template_parameters['Credit_size'] = QgsLayoutSize(51.42857142857143,6, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Credit_locals'] = QgsLayoutPoint(151, 197, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Credit_rotate'] = 0
self.template_parameters['Source_size'] = QgsLayoutSize(51.42857142857143,6, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Source_locals'] = QgsLayoutPoint(229, 197, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Source_rotate'] = 0
self.template_parameters['Sous_titre_size'] = QgsLayoutSize(125.71428571428571,14, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Sous_titre_locals'] = QgsLayoutPoint(60, 20, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Sous_titre_rotate'] = 0
self.template_parameters['Echelle_2_size'] = QgsLayoutSize(51.42857142857143,13, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_2_locals'] = QgsLayoutPoint(9, 184, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_2_rotate'] = 0
self.template_parameters['Logo_2_size'] = QgsLayoutSize(28.571428571428573,29, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_2_locals'] = QgsLayoutPoint(9, 151, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_2_rotate'] = 0
if values_page == 'A3':
self.template_parameters['Carte_size'] = QgsLayoutSize(282,282, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_locals'] = QgsLayoutPoint(8, 8, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_rotate'] = 0
self.template_parameters['Carte_2_size'] = QgsLayoutSize(121,97, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_2_locals'] = QgsLayoutPoint(294, 4, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_2_rotate'] = 0
self.template_parameters['Legande_size'] = QgsLayoutSize(197,207, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Legande_locals'] = QgsLayoutPoint(58, 156, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Legande_rotate'] = 0
self.template_parameters['Arrow_size'] = QgsLayoutSize(20,20, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Arrow_locals'] = QgsLayoutPoint(266, 28, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Arrow_rotate'] = 0
self.template_parameters['Echelle_size'] = QgsLayoutSize(73,10, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_locals'] = QgsLayoutPoint(12, 278, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_rotate'] = 0
self.template_parameters['Logo_size'] = QgsLayoutSize(64,16, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_locals'] = QgsLayoutPoint(4, 4, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_rotate'] = 0
self.template_parameters['Titre_size'] = QgsLayoutSize(218,16, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Titre_locals'] = QgsLayoutPoint(73, 4, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Titre_rotate'] = 0
self.template_parameters['Credit_size'] = QgsLayoutSize(73,8, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Credit_locals'] = QgsLayoutPoint(214, 278, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Credit_rotate'] = 0
self.template_parameters['Source_size'] = QgsLayoutSize(73,8, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Source_locals'] = QgsLayoutPoint(322, 278, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Source_rotate'] = 0
self.template_parameters['Sous_titre_size'] = QgsLayoutSize(177,20, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Sous_titre_locals'] = QgsLayoutPoint(85, 28, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Sous_titre_rotate'] = 0
self.template_parameters['Echelle_2_size'] = QgsLayoutSize(73,18, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_2_locals'] = QgsLayoutPoint(12, 260, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_2_rotate'] = 0
self.template_parameters['Logo_2_size'] = QgsLayoutSize(40,40, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_2_locals'] = QgsLayoutPoint(12, 214, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_2_rotate'] = 0
if page_rotate == 'Landscape':
if values_page == 'A4':
self.template_parameters['Carte_size'] = QgsLayoutSize(200.0,200, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_locals'] = QgsLayoutPoint(6, 6, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_rotate'] = 0
self.template_parameters['Carte_2_size'] = QgsLayoutSize(85.71428571428571,69, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_2_locals'] = QgsLayoutPoint(209, 3, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_2_rotate'] = 0
self.template_parameters['Legande_size'] = QgsLayoutSize(140.0,147, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Legande_locals'] = QgsLayoutPoint(49, 15, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Legande_rotate'] = 0
self.template_parameters['Arrow_size'] = QgsLayoutSize(14.285714285714286,14, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Arrow_locals'] = QgsLayoutPoint(189, 20, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Arrow_rotate'] = 0
self.template_parameters['Echelle_size'] = QgsLayoutSize(51.42857142857143,7, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_locals'] = QgsLayoutPoint(9, 197, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_rotate'] = 0
self.template_parameters['Logo_size'] = QgsLayoutSize(45.714285714285715,11, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_locals'] = QgsLayoutPoint(3, 3, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_rotate'] = 0
self.template_parameters['Titre_size'] = QgsLayoutSize(154.28571428571428,11, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Titre_locals'] = QgsLayoutPoint(51, 3, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Titre_rotate'] = 0
self.template_parameters['Credit_size'] = QgsLayoutSize(51.42857142857143,6, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Credit_locals'] = QgsLayoutPoint(151, 197, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Credit_rotate'] = 0
self.template_parameters['Source_size'] = QgsLayoutSize(51.42857142857143,6, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Source_locals'] = QgsLayoutPoint(229, 197, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Source_rotate'] = 0
self.template_parameters['Sous_titre_size'] = QgsLayoutSize(125.71428571428571,14, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Sous_titre_locals'] = QgsLayoutPoint(60, 20, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Sous_titre_rotate'] = 0
self.template_parameters['Echelle_2_size'] = QgsLayoutSize(51.42857142857143,13, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_2_locals'] = QgsLayoutPoint(9, 184, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_2_rotate'] = 0
self.template_parameters['Logo_2_size'] = QgsLayoutSize(28.571428571428573,29, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_2_locals'] = QgsLayoutPoint(9, 151, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_2_rotate'] = 0
if values_page == 'A3':
self.template_parameters['Carte_size'] = QgsLayoutSize(282,282, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_locals'] = QgsLayoutPoint(8, 8, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_rotate'] = 0
self.template_parameters['Carte_2_size'] = QgsLayoutSize(121,97, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_2_locals'] = QgsLayoutPoint(294, 4, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Carte_2_rotate'] = 0
self.template_parameters['Legande_size'] = QgsLayoutSize(197,207, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Legande_locals'] = QgsLayoutPoint(69, 21, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Legande_rotate'] = 0
self.template_parameters['Arrow_size'] = QgsLayoutSize(20,20, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Arrow_locals'] = QgsLayoutPoint(266, 28, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Arrow_rotate'] = 0
self.template_parameters['Echelle_size'] = QgsLayoutSize(73,10, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_locals'] = QgsLayoutPoint(12, 278, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_rotate'] = 0
self.template_parameters['Logo_size'] = QgsLayoutSize(64,16, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_locals'] = QgsLayoutPoint(4, 4, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_rotate'] = 0
self.template_parameters['Titre_size'] = QgsLayoutSize(218,16, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Titre_locals'] = QgsLayoutPoint(73, 4, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Titre_rotate'] = 0
self.template_parameters['Credit_size'] = QgsLayoutSize(73,8, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Credit_locals'] = QgsLayoutPoint(214, 278, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Credit_rotate'] = 0
self.template_parameters['Source_size'] = QgsLayoutSize(73,8, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Source_locals'] = QgsLayoutPoint(322, 278, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Source_rotate'] = 0
self.template_parameters['Sous_titre_size'] = QgsLayoutSize(177,20, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Sous_titre_locals'] = QgsLayoutPoint(85, 28, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Sous_titre_rotate'] = 0
self.template_parameters['Echelle_2_size'] = QgsLayoutSize(73,18, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_2_locals'] = QgsLayoutPoint(12, 260, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Echelle_2_rotate'] = 0
self.template_parameters['Logo_2_size'] = QgsLayoutSize(40,40, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_2_locals'] = QgsLayoutPoint(12, 214, QgsUnitTypes.LayoutMillimeters)
self.template_parameters['Logo_2_rotate'] = 0
return self.template_parameters

View File

@ -3,9 +3,9 @@
import configparser
import shutil
import tempfile
import base64
import psycopg2
import psycopg2.extras
# import base64
# import psycopg2
# import psycopg2.extras
from os.path import abspath, join, pardir, dirname
from qgis.PyQt.QtWidgets import QApplication
from qgis.PyQt import uic
@ -107,65 +107,68 @@ def load_ui(*args):
return ui_class
def send_issues(url,titre,body,labels):
def send_issues(url, titre, body, labels):
import requests
import urllib.request
import json
import os
import qgis
# import os
usr = os.environ['USERNAME']
# usr = os.environ['USERNAME']
token = '9d0a4e0bea561710e0728f161f7edf4e5201e112'
url=url+'?token='+token
headers = {'Authorization': 'token ' + token,'accept': 'application/json','Content-Type': 'application/json'}
url = url + '?token=' + token
headers = {'Authorization': 'token ' + token, 'accept': 'application/json', 'Content-Type': 'application/json'}
payload = {'title': titre, 'body': body, 'labels': labels}
try:
urllib.request.urlopen('https://google.com')
binar = True
except:
except urllib.requests.URLError:
binar = False
r = ''
if binar:
r = requests.post(url, data=json.dumps(payload), headers=headers)
return r
def maj_verif(NAME):
import qgis
import urllib.request
iface = qgis.utils.iface
from qgis.core import Qgis
url = qgis.utils.pluginMetadata(NAME,'repository')
#URL = url+'/raw/branch/main/plugins.xml'
# url = qgis.utils.pluginMetadata(NAME, 'repository')
# URL = url+'/raw/branch/main/plugins.xml'
URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml'
# print(URL)
version = qgis.utils.pluginMetadata(NAME,'version')
version = qgis.utils.pluginMetadata(NAME, 'version')
len_version = len(version)
try:
urllib.request.urlopen('https://google.com')
binar = True
except:
except urllib.requests.URLError:
binar = False
if binar:
try:
version_web = str(urllib.request.urlopen(URL).read())
plugin_num = version_web.find(NAME)
valeur_version_web = version_web.find('<version>',plugin_num)+9
version_plugin = version_web[valeur_version_web:valeur_version_web+len_version]
valeur_version_web = version_web.find('<version>', plugin_num) + 9
version_plugin = version_web[valeur_version_web:valeur_version_web + len_version]
if version_plugin != version:
iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30)
except:
except urllib.requests.URLError:
print("error gitea version ssl")
else:
iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30)
def tr(text, context="@default"):
return QApplication.translate(context, text)
def devlog(NAME):
import qgis
devmaj = '<head><style>* {margin:0; padding:0; }</style></head>'
devmaj = devmaj+qgis.utils.pluginMetadata(NAME,'changelog')
return devmaj
devmaj = devmaj + qgis.utils.pluginMetadata(NAME, 'changelog')
return devmaj

View File

@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
SICEN
A QGIS plugin
Filtre sur données SICEN
-------------------
SICEN
A QGIS plugin
Filtre sur données SICEN
-------------------
begin : 2014-10-17
copyright : (C) 2014 by Guillaume COSTES
email : guillaume.costes@espaces-naturels.fr
@ -18,10 +18,11 @@
* (at your option) any later version. *
* *
***************************************************************************/
This script initializes the plugin, making it known to QGIS.
This script initializes the plugin, making it known to QGIS.
"""
from __future__ import absolute_import
def classFactory(iface):
# load SICEN class from file SICEN
from .sicen import SICEN

View File

@ -5,10 +5,9 @@
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.2)
#
# WARNING! All changes made in this file will be lost!
try:
from PyQt5 import QtCore
except:
from PyQt6 import QtCore
from qgis.PyQt import QtCore
qt_resource_data = b"\
\x00\x00\x0d\x89\
\x89\
@ -558,10 +557,13 @@ else:
rcc_version = 2
qt_resource_struct = qt_resource_struct_v2
def qInitResources():
QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
SICENDialog
A QGIS plugin
Filtre sur données SICEN
-------------------
SICENDialog
A QGIS plugin
Filtre sur données SICEN
-------------------
begin : 2014-10-17
copyright : (C) 2014 by Guillaume COSTES
email : guillaume.costes@espaces-naturels.fr
@ -20,8 +20,8 @@
***************************************************************************/
"""
from qgis.PyQt import QtCore, QtGui
from qgis.PyQt.QtWidgets import QAction, QDialog
# from qgis.PyQt import QtCore, QtGui
from qgis.PyQt.QtWidgets import QDialog
from .ui_sicen import Ui_SICEN
# create the dialog for zoom to point

View File

@ -3,10 +3,10 @@
import configparser
import shutil
import tempfile
# import base64
# import psycopg2
# import psycopg2.extras
import os
import base64
import psycopg2
import psycopg2.extras
from os.path import abspath, join, pardir, dirname
from qgis.PyQt import uic
@ -90,7 +90,7 @@ def resources_path(*args):
:return: Absolute path to the resources folder.
:rtype: str
"""
path = abspath(abspath(join(plugin_path(), "CenRa_SICEN\\tools")))
path = abspath(abspath(join(plugin_path(), "CenRa_COPIE\\tools")))
for item in args:
path = abspath(join(path, item))
return path
@ -108,72 +108,77 @@ def load_ui(*args):
return ui_class
def pyperclip():
dst = dirname(dirname(__file__))+"\\tools\\"
if os.access('N:/',os.R_OK):
dst = dirname(dirname(__file__)) + "\\tools\\"
if os.access('N:/', os.R_OK):
src = 'N:/SI_Systeme d information/Z_QGIS/PLUGIN/PythonSQL.py'
try:
shutil.copy(src, dst)
except:
except FileNotFoundError:
print('404')
except UnboundLocalError:
print('404')
def send_issues(url,titre,body,labels):
def send_issues(url, titre, body, labels):
import requests
import urllib.request
import json
import os
import qgis
# import os
# import qgis
usr = os.environ['USERNAME']
# usr = os.environ['USERNAME']
token = '9d0a4e0bea561710e0728f161f7edf4e5201e112'
url=url+'?token='+token
headers = {'Authorization': 'token ' + token,'accept': 'application/json','Content-Type': 'application/json'}
url = url + '?token=' + token
headers = {'Authorization': 'token ' + token, 'accept': 'application/json', 'Content-Type': 'application/json'}
payload = {'title': titre, 'body': body, 'labels': labels}
try:
urllib.request.urlopen('https://google.com')
binar = True
except:
except ValueError:
binar = False
r = ''
if binar:
r = requests.post(url, data=json.dumps(payload), headers=headers)
return r
def maj_verif(NAME):
import qgis
import urllib.request
iface = qgis.utils.iface
from qgis.core import Qgis
url = qgis.utils.pluginMetadata(NAME,'repository')
#URL = url+'/raw/branch/main/plugins.xml'
# url = qgis.utils.pluginMetadata(NAME, 'repository')
# URL = url+'/raw/branch/main/plugins.xml'
URL = 'https://gitea.cenra-outils.org/CEN-RA/Plugin_QGIS/releases/download/latest/plugins.xml'
# print(URL)
version = qgis.utils.pluginMetadata(NAME,'version')
# print(URL)
version = qgis.utils.pluginMetadata(NAME, 'version')
len_version = len(version)
try:
urllib.request.urlopen('https://google.com')
binar = True
except:
except urllib.error.URLError:
binar = False
if binar:
try:
version_web = str(urllib.request.urlopen(URL).read())
plugin_num = version_web.find(NAME)
valeur_version_web = version_web.find('<version>',plugin_num)+9
version_plugin = version_web[valeur_version_web:valeur_version_web+len_version]
valeur_version_web = version_web.find('<version>', plugin_num) + 9
version_plugin = version_web[valeur_version_web:valeur_version_web + len_version]
if version_plugin != version:
iface.messageBar().pushMessage("MAJ :", "Des mise à jour de plugin sont disponibles.", level=Qgis.Info, duration=30)
except:
except urllib.error.URLError:
print("error gitea version ssl")
else:
iface.messageBar().pushMessage("WiFi :", "Pas de connection à internet.", level=Qgis.Warning, duration=30)
#return version_plugin
def devlog(NAME):
import qgis
devmaj = '<head><style>* {margin:0; padding:0; }</style></head>'
devmaj = devmaj+qgis.utils.pluginMetadata(NAME,'changelog')
return devmaj
devmaj = devmaj + qgis.utils.pluginMetadata(NAME, 'changelog')
return devmaj

View File

@ -8,9 +8,10 @@
# WARNING! All changes made in this file will be lost!
from builtins import object
from qgis.PyQt import QtCore, QtGui
from qgis.PyQt import QtCore
from qgis.PyQt.QtGui import QFont
from qgis.PyQt.QtWidgets import QAction, QDialog, QDialogButtonBox, QLabel, QApplication, QTabWidget, QWidget, QGroupBox, QGridLayout, QComboBox, QCheckBox, QCalendarWidget, QToolBox, QFrame, QLineEdit, QSizePolicy #Modifié
# Modifié
from qgis.PyQt.QtWidgets import QDialogButtonBox, QLabel, QApplication, QTabWidget, QWidget, QGroupBox, QGridLayout, QComboBox, QCheckBox, QCalendarWidget, QToolBox, QFrame, QLineEdit, QSizePolicy
try:
@ -21,20 +22,22 @@ except AttributeError:
try:
_encoding = QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QApplication.translate(context, text, disambig)
class Ui_SICEN(object):
def setupUi(self, SICEN):
SICEN.setObjectName(_fromUtf8("SICEN"))
SICEN.resize(592, 556)
self.buttonBox = QDialogButtonBox(SICEN)
self.buttonBox.setGeometry(QtCore.QRect(390, 520, 161, 32))
#self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.StandardButton(0x00400000)|QDialogButtonBox.StandardButton(0x00000400))
# self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.StandardButton(0x00400000) | QDialogButtonBox.StandardButton(0x00000400))
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.Titre = QLabel(SICEN)
self.Titre.setGeometry(QtCore.QRect(110, 10, 331, 31))
@ -529,7 +532,7 @@ class Ui_SICEN(object):
font.setBold(True)
font.setWeight(75)
self.groupBox_6.setFont(font)
self.groupBox_6.setAlignment(QtCore.Qt.AlignmentFlag(0x0001)|QtCore.Qt.AlignmentFlag(0x0001)|QtCore.Qt.AlignmentFlag(0x0080))
self.groupBox_6.setAlignment(QtCore.Qt.AlignmentFlag(0x0001) | QtCore.Qt.AlignmentFlag(0x0001) | QtCore.Qt.AlignmentFlag(0x0080))
self.groupBox_6.setObjectName(_fromUtf8("groupBox_6"))
self.gridLayoutWidget_7 = QWidget(self.groupBox_6)
self.gridLayoutWidget_7.setGeometry(QtCore.QRect(10, 20, 491, 21))
@ -680,8 +683,9 @@ class Ui_SICEN(object):
self.retranslateUi(SICEN)
self.Emprise.setCurrentIndex(0)
self.protections.setCurrentIndex(0)
self.buttonBox.accepted.connect(SICEN.accept)
self.buttonBox.rejected.connect(SICEN.reject) #Modifié
self.buttonBox.accepted.connect(SICEN.accept)
# Modifié
self.buttonBox.rejected.connect(SICEN.reject)
QtCore.QMetaObject.connectSlotsByName(SICEN)
def retranslateUi(self, SICEN):
@ -753,4 +757,3 @@ class Ui_SICEN(object):
self.label_11.setText(_translate("SICEN", "4.", None))
self.Emprise.setTabText(self.Emprise.indexOf(self.tab_4), _translate("SICEN", "Filtre par Emprise", None))
self.centroide.setText(_translate("SICEN", "Utiliser les centroïdes pour les observations autres que ponctuelles", None))