| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
from xml.dom.minidom import parseString |
| 25 |
from xml.parsers.expat import ExpatError |
| 26 |
import tarfile, os, zipfile, re |
| 27 |
from io import BytesIO |
| 28 |
|
| 29 |
from .filtres import filtre_versions_anterieures |
| 30 |
from ..pylib import print_error, eval_safe, removeend |
| 31 |
from .. import param |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
class FichierGEO(object): |
| 40 |
"""Classe utilisée pour manipuler un fichier .geo. |
| 41 |
|
| 42 |
On peut aussi utiliser le DOM XML, mais les spécifications du format de fichier .geo |
| 43 |
sont plus restreintes, et cette classe offre une surcouche au DOM XML pour un accès plus simple.""" |
| 44 |
|
| 45 |
defaut = {"type": "Fichier WxGeometrie", "version": param.version, "module": '', "nom": '', "repertoire": ''} |
| 46 |
|
| 47 |
def __init__(self, texte = "", encoding = "utf-8", **args): |
| 48 |
self.infos = self.defaut.copy() |
| 49 |
self.infos.update(args) |
| 50 |
self.encoding = encoding |
| 51 |
self.contenu = {} |
| 52 |
|
| 53 |
if texte: self.importer(texte) |
| 54 |
|
| 55 |
|
| 56 |
@property |
| 57 |
def nom(self): return self.infos['nom'] |
| 58 |
@property |
| 59 |
def repertoire(self): return self.infos['repertoire'] |
| 60 |
@property |
| 61 |
def module(self): return self.infos['module'].lower() |
| 62 |
@property |
| 63 |
def type(self): return self.infos['type'] |
| 64 |
@property |
| 65 |
def version(self): return self.infos['version'] |
| 66 |
@property |
| 67 |
def data(self): return self.exporter() |
| 68 |
|
| 69 |
|
| 70 |
def importer(self, texte): |
| 71 |
def contenu_node(node): |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
if not node.childNodes: |
| 78 |
return "" |
| 79 |
|
| 80 |
|
| 81 |
if not "Element" in [subnode.__class__.__name__ for subnode in node.childNodes]: |
| 82 |
return node.childNodes[0].nodeValue.strip("\n").replace("<", "<").replace(">", ">").replace("&", "&") |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
dico = {} |
| 87 |
for elt in node.childNodes: |
| 88 |
if elt.__class__.__name__ == "Element": |
| 89 |
contenu = contenu_node(elt) |
| 90 |
if elt.nodeName in dico: |
| 91 |
dico[elt.nodeName] += [contenu] |
| 92 |
else: |
| 93 |
dico[elt.nodeName] = [contenu] |
| 94 |
return dico |
| 95 |
|
| 96 |
|
| 97 |
xml = parseString(texte) |
| 98 |
self.encoding = xml.encoding |
| 99 |
self.document = xml.childNodes[0] |
| 100 |
self.infos = self.defaut.copy() |
| 101 |
for attribut in self.document._attrs: |
| 102 |
self.infos[attribut] = self.document._attrs[attribut].value |
| 103 |
|
| 104 |
self.contenu = contenu_node(self.document) |
| 105 |
return self |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
def exporter(self): |
| 112 |
def convertir_contenu(dictionnaire): |
| 113 |
texte = "" |
| 114 |
for balise in dictionnaire: |
| 115 |
for elt in dictionnaire[balise]: |
| 116 |
texte += "<%s>\n" %balise |
| 117 |
if isinstance(elt, str): |
| 118 |
texte += elt.replace("&", "&").replace("<", "<").replace(">", ">").strip("\n") + "\n" |
| 119 |
elif isinstance(elt, dict): |
| 120 |
texte += convertir_contenu(elt) |
| 121 |
texte += "</%s>\n" %balise |
| 122 |
|
| 123 |
return texte |
| 124 |
|
| 125 |
texte = "<?xml version='1.0' encoding='%s'?>\n" %self.encoding |
| 126 |
texte += "<Document type='%s' version='%s' module='%s'>\n" %(self.type, self.version, self.module) |
| 127 |
texte += convertir_contenu(self.contenu) |
| 128 |
texte += "</Document>" |
| 129 |
return texte |
| 130 |
|
| 131 |
|
| 132 |
def ajouter(self, nom, racine = None, contenu = None): |
| 133 |
"""Ajoute une ou plusieurs nouvelle(s) node(s) nommée(s) 'nom' à 'racine', leur contenu étant donné par 'contenu'. |
| 134 |
Renvoie le contenu, ou la nouvelle racine crée (si le contenu était vide).""" |
| 135 |
if racine is None: |
| 136 |
racine = self.contenu |
| 137 |
if contenu is None: |
| 138 |
contenu = {} |
| 139 |
|
| 140 |
if nom not in racine: |
| 141 |
racine[nom] = [] |
| 142 |
racine[nom].append(contenu) |
| 143 |
return contenu |
| 144 |
|
| 145 |
|
| 146 |
def ecrire(self, path, compressed=False): |
| 147 |
"""Ecrit dans un fichier dont l'adresse est donnée par 'path'. |
| 148 |
|
| 149 |
L'encodage est fixé par 'self.encoding'. |
| 150 |
Eventuellement, le contenu peut-être compressé au format zip.""" |
| 151 |
|
| 152 |
contenu = self.data |
| 153 |
f = None |
| 154 |
rep = os.path.split(path)[0] |
| 155 |
if not os.path.exists(rep): |
| 156 |
os.makedirs(rep) |
| 157 |
if zip: |
| 158 |
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as f: |
| 159 |
f.writestr("content.geo", contenu) |
| 160 |
else: |
| 161 |
with open(path, "w", encoding=self.encoding) as f: |
| 162 |
f.write(contenu) |
| 163 |
|
| 164 |
|
| 165 |
def ouvrir(self, path, compressed=None): |
| 166 |
"""Retourne un objet FichierGEO à partir du fichier dont l'adresse est donnée par 'path'. |
| 167 |
|
| 168 |
Si l'attribut 'zip' n'est pas fixé, la détection est automatique.""" |
| 169 |
|
| 170 |
if not os.path.exists(path): |
| 171 |
if param.debug: |
| 172 |
print('Incorrect path: ' + repr(path)) |
| 173 |
return None, "Le fichier n'existe pas." |
| 174 |
|
| 175 |
if compressed is None: |
| 176 |
compressed = zipfile.is_zipfile(path) |
| 177 |
|
| 178 |
try: |
| 179 |
if compressed: |
| 180 |
with zipfile.ZipFile(path, "r") as f: |
| 181 |
texte = f.read("content.geo").decode('utf8') |
| 182 |
else: |
| 183 |
with open(path, "r", encoding=self.encoding) as f: |
| 184 |
texte = f.read() |
| 185 |
except IOError: |
| 186 |
print_error() |
| 187 |
return None, "L'accès au fichier a été refusé." |
| 188 |
except UnicodeError: |
| 189 |
print_error() |
| 190 |
return None, "Caractères non reconnus." |
| 191 |
except Exception: |
| 192 |
print_error() |
| 193 |
return None, "Impossible d'ouvrir le fichier." |
| 194 |
|
| 195 |
self.importer(texte) |
| 196 |
|
| 197 |
version = self.version_interne() |
| 198 |
|
| 199 |
s |
| 200 |
print('Test de la version du fichier...') |
| 201 |
if version < self.version_interne(param.version): |
| 202 |
print("Ce fichier a été créé avec une ancienne version du logiciel (%s)." |
| 203 |
" Conversion en cours..." % '.'.join(str(n) for n in version)) |
| 204 |
filtre_versions_anterieures(self, version) |
| 205 |
|
| 206 |
rep, fich = os.path.split(path) |
| 207 |
self.infos['repertoire'] = rep |
| 208 |
self.infos['nom'] = removeend(fich, ".geo", ".geoz") |
| 209 |
|
| 210 |
return self, "Le fichier %s a bien été ouvert." %path |
| 211 |
|
| 212 |
|
| 213 |
def version_interne(self, version = None): |
| 214 |
"""Renvoie le numéro de version sous forme d'une liste, ex: [12, 4, 1] pour la version 12.4.1. |
| 215 |
|
| 216 |
Par défaut, le numéro de version est celui du logiciel ayant servi à créer le fichier. |
| 217 |
""" |
| 218 |
if version is None: |
| 219 |
version = self.version |
| 220 |
version = version.strip().lower() |
| 221 |
version = version.replace("alpha", "a").replace("beta", "b").replace("release candidate", "rc").replace("releasecandidate", "rc") |
| 222 |
version = version.replace("a", " -3 ").replace("b", " -2 ").replace("rc", " -1 ").replace(".", " ") |
| 223 |
return [int(n) for n in re.split("[ ]+", version)] |
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
." |
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
" |
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
th |
| 243 |
|
| 244 |
|
| 245 |
def ouvrir_fichierGEO(path): |
| 246 |
"Alias de 'FichierGEO().ouvrir(path)'." |
| 247 |
return FichierGEO().ouvrir(path) |
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
class FichierSession(object): |
| 252 |
|
| 253 |
def __init__(self, *fichiers, **infos): |
| 254 |
|
| 255 |
self.fichiers = {} |
| 256 |
self.infos = infos |
| 257 |
self.ajouter(*fichiers) |
| 258 |
|
| 259 |
def ajouter(self, *fichiers): |
| 260 |
for fichier in fichiers: |
| 261 |
self._ajouter_fichier(fichier) |
| 262 |
|
| 263 |
def _ajouter_fichier(self, fichier): |
| 264 |
if fichier.module in self.fichiers: |
| 265 |
self.fichiers[fichier.module].append(fichier) |
| 266 |
else: |
| 267 |
self.fichiers[fichier.module] = [fichier] |
| 268 |
|
| 269 |
|
| 270 |
def ecrire(self, path, compresser = True): |
| 271 |
rep = os.path.split(path)[0] |
| 272 |
if not os.path.exists(rep): |
| 273 |
os.makedirs(rep) |
| 274 |
|
| 275 |
def _ajouter(titre, content): |
| 276 |
info = tarfile.TarInfo(titre) |
| 277 |
data = content.encode('utf8') |
| 278 |
info.size = len(data) |
| 279 |
tar.addfile(info, BytesIO(data)) |
| 280 |
|
| 281 |
mode = 'w:' + ('gz' if compresser else '') |
| 282 |
with tarfile.open(path, mode=mode) as tar: |
| 283 |
fichier_info = FichierGEO(type = 'Session WxGeometrie', module = 'main') |
| 284 |
for key, val in self.infos.items(): |
| 285 |
fichier_info.ajouter(key, None, repr(val)) |
| 286 |
_ajouter('session.info', fichier_info.data) |
| 287 |
for module, fichiers in self.fichiers.items(): |
| 288 |
for i, fichier in enumerate(fichiers): |
| 289 |
_ajouter(module + str(i) + '.geo', fichier.data) |
| 290 |
|
| 291 |
|
| 292 |
def ouvrir(self, path): |
| 293 |
self.fichiers = {} |
| 294 |
self.infos = {} |
| 295 |
tar = tarfile.open(path, mode = 'r') |
| 296 |
try: |
| 297 |
for member_info in tar.getmembers(): |
| 298 |
nom = member_info.name |
| 299 |
with tar.extractfile(member_info) as f: |
| 300 |
data = f.read().decode('utf8') |
| 301 |
fichier = FichierGEO().importer(data) |
| 302 |
if nom == 'session.info': |
| 303 |
for key in fichier.contenu: |
| 304 |
self.infos[key] = eval_safe(fichier.contenu[key][0]) |
| 305 |
else: |
| 306 |
self._ajouter_fichier(fichier) |
| 307 |
finally: |
| 308 |
tar.close() |
| 309 |
return self |
| 310 |
|
| 311 |
def __iter__(self): |
| 312 |
def gen_fichiers(): |
| 313 |
for fichiers in self.fichiers.values(): |
| 314 |
for fichier in fichiers: |
| 315 |
yield fichier |
| 316 |
return gen_fichiers() |