mocodoeditor 0.2.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ """MocodoEditor : éditeur Mocodo simple, code à gauche et MCD en direct à droite."""
2
+ from .version import __version__
@@ -0,0 +1,3 @@
1
+ from .app import main
2
+
3
+ main()
mocodoeditor/app.py ADDED
@@ -0,0 +1,66 @@
1
+ """Application : QApplication (ouverture depuis le Finder) et fonction main()."""
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from PyQt6.QtCore import QEvent
6
+ from PyQt6.QtGui import QFont
7
+ from PyQt6.QtWidgets import QApplication
8
+
9
+ from .constants import APP_NAME
10
+ from .main_window import MainWindow
11
+ from .version import __version__
12
+
13
+
14
+ def set_macos_app_name(name):
15
+ """Sous macOS, le menu de l'application s'appelle « Python » (nom du bundle de
16
+ l'interpréteur) ; on le renomme avant la création de QApplication.
17
+ Nécessite pyobjc (optionnel) : sans lui, le nom reste inchangé."""
18
+ if sys.platform != "darwin":
19
+ return
20
+ try:
21
+ from Foundation import NSBundle
22
+ except ImportError:
23
+ return
24
+ info = NSBundle.mainBundle().infoDictionary()
25
+ info["CFBundleName"] = name
26
+
27
+
28
+ class MocodoApplication(QApplication):
29
+ """Gère l'ouverture d'un fichier par Finder (double-clic, « Ouvrir avec »)."""
30
+ window: "MainWindow | None" = None
31
+ pending: str | None = None
32
+
33
+ def event(self, e):
34
+ if e.type() == QEvent.Type.FileOpen:
35
+ if self.window:
36
+ self.window.open_recent(e.file())
37
+ else: # l'événement peut arriver avant la création de la fenêtre
38
+ self.pending = e.file()
39
+ return True
40
+ return super().event(e)
41
+
42
+
43
+ def main():
44
+ if "--version" in sys.argv[1:]:
45
+ print(f"{APP_NAME} {__version__}")
46
+ sys.exit(0)
47
+ set_macos_app_name(APP_NAME)
48
+ app = MocodoApplication(sys.argv)
49
+ # les SVG produits demandent parfois « sans-serif », absente de macOS : évite une recherche coûteuse
50
+ if sys.platform == "darwin":
51
+ QFont.insertSubstitution("Sans-serif", "Helvetica Neue")
52
+ QFont.insertSubstitution("sans-serif", "Helvetica Neue")
53
+ else: # hors macOS, Fusion suit l'apparence clair/sombre demandée (Qt ≥ 6.8)
54
+ app.setStyle("Fusion")
55
+ app.setApplicationName(APP_NAME)
56
+ app.setApplicationVersion(__version__)
57
+ win = MainWindow()
58
+ app.window = win
59
+ win.show()
60
+ # fichier passé en argument ou reçu de Finder au démarrage
61
+ start = app.pending or next((a for a in sys.argv[1:] if Path(a).is_file()), None)
62
+ if start:
63
+ win.load_path(Path(start))
64
+ else: # sinon, le dernier fichier ouvert ; à défaut, le nouveau document par défaut
65
+ win.open_last_recent()
66
+ sys.exit(app.exec())
@@ -0,0 +1,139 @@
1
+ """Ce que Mocodo sait faire, sous forme de tables : retouches, sorties, palettes, formes, exemples.
2
+
3
+ Chaque retouche ou sortie est une liste d'arguments pour `mocodo -t` (voir `mocodo --help`)."""
4
+
5
+ # Retouches du texte (menu Retouches, comme l'onglet du même nom de mocodo.net) :
6
+ # (menu, [(libellé, arguments de -t)]). Un séparateur est noté (None, None).
7
+ ARRANGE_TIMEOUT = "timeout=20" # le Branch & Bound sans limite peut durer très longtemps
8
+ RETOUCHES = [
9
+ ("Réarranger", [
10
+ ("Sans contraintes", ["arrange:" + ARRANGE_TIMEOUT]),
11
+ ("En privilégiant la largeur", ["arrange:wide," + ARRANGE_TIMEOUT]),
12
+ ("Sur la grille actuelle", ["arrange:current," + ARRANGE_TIMEOUT]),
13
+ ("Sur la plus petite grille équilibrée", ["arrange:balanced=0," + ARRANGE_TIMEOUT]),
14
+ ("Sur la seconde plus petite grille équilibrée", ["arrange:balanced=1," + ARRANGE_TIMEOUT]),
15
+ ("Avec l'algorithme génétique", ["arrange:algo=ga"]),
16
+ ]),
17
+ ("Inverser", [
18
+ ("Horizontalement", ["flip:h"]),
19
+ ("Verticalement", ["flip:v"]),
20
+ ("Selon la première diagonale", ["flip:vhd"]),
21
+ ("Selon la seconde diagonale", ["flip:d"]),
22
+ ]),
23
+ ("Éditer", [
24
+ ("Libellés en camelCase", ["camel:labels"]),
25
+ ("Libellés en PascalCase", ["pascal:labels"]),
26
+ ("Libellés en snake_case", ["snake:labels"]),
27
+ ("Libellés en ASCII", ["ascii:labels"]),
28
+ (None, None),
29
+ ("Attributs en minuscules", ["lower:attrs"]),
30
+ ("Noms des entités et des associations en majuscules", ["upper:boxes"]),
31
+ ("Corriger les fautes de frappe dans les cardinalités", ["fix:cards"]),
32
+ ("Tout normaliser (ASCII, minuscules, majuscules, cardinalités)",
33
+ ["ascii:labels", "lower:attrs", "upper:boxes", "fix:cards"]),
34
+ ]),
35
+ ("Révéler", [
36
+ ("Mettre des DF partout où c'est possible", ["create:dfs"]),
37
+ ("Ajouter des flèches aux DF", ["add:df_arrows"]),
38
+ ("Ajouter les CIF correspondant aux agrégats", ["add:cifs"]),
39
+ ("Mettre comme rôles le nom des associations", ["add:roles"]),
40
+ (None, None),
41
+ ("Mettre en évidence les types à remplir", ["create:types=TODO"]),
42
+ ("Deviner les types à partir du nom des attributs", ["guess:types"]),
43
+ ("Supprimer les types", ["delete:types"]),
44
+ (None, None),
45
+ ("Réparer l'oubli d'entités référencées dans des associations", ["create:entities"]),
46
+ ]),
47
+ ("Masquer", [
48
+ ("Remplacer les libellés par des libellés génériques numérotés", ["drown"]),
49
+ ("Masquer les attributs et les cardinalités", ["empty"]),
50
+ ("Remplir les types au hasard", ["randomize:types"]),
51
+ ("Masquer avec du faux texte", ["obfuscate"]),
52
+ (None, None),
53
+ ("Créer un MCD d'entraînement à la conversion en relationnel",
54
+ ["grow:n=9,from_scratch,ent_attrs=3", "obfuscate:labels=en4", "create:roles", "lower:roles",
55
+ "arrange:" + ARRANGE_TIMEOUT]),
56
+ ("Créer un MCD aléatoire avec des libellés génériques numérotés",
57
+ ["grow:from_scratch", "drown", "arrange:" + ARRANGE_TIMEOUT]),
58
+ ]),
59
+ ("Décomposer", [
60
+ ("Drainer les DF porteuses d'attributs", ["drain"]),
61
+ ("Décomposer les DF ternaires et plus", ["split", "arrange:" + ARRANGE_TIMEOUT]),
62
+ ("Décomposer les non-DF ternaires et plus", ["explode", "arrange:" + ARRANGE_TIMEOUT]),
63
+ ("Décomposer les non-DF binaires porteuses d'attributs",
64
+ ["explode:arity=2.5", "arrange:" + ARRANGE_TIMEOUT]),
65
+ ("Décomposer toutes les non-DF binaires", ["explode:arity=2", "arrange:" + ARRANGE_TIMEOUT]),
66
+ ]),
67
+ ]
68
+
69
+ # Sorties textuelles (onglet « Autres sorties ») : (groupe, [(libellé, arguments de -t, extension)])
70
+ OUTPUTS = [
71
+ ("Schéma relationnel", [
72
+ ("Markdown", ["markdown"], ".md"), ("Texte", ["text"], ".txt"),
73
+ ("LaTeX", ["latex"], ".tex"), ("HTML", ["html"], ".html"),
74
+ ]),
75
+ ("Script SQL", [
76
+ ("MySQL / MariaDB", ["mysql"], ".sql"), ("PostgreSQL", ["postgresql"], ".sql"),
77
+ ("SQLite", ["sqlite"], ".sql"), ("SQL Server", ["sqlserver"], ".sql"), ("Oracle", ["oracle"], ".sql"),
78
+ ]),
79
+ ("Dessin", [
80
+ ("Dessin du MCD (SVG)", [], ".svg"),
81
+ ]),
82
+ ("Autres notations", [
83
+ ("Dictionnaire des données", ["data_dict"], ".md"),
84
+ ("Diagramme de classes UML (PlantUML)", ["uml"], ".puml"),
85
+ ("Pattes de corbeau (Mermaid)", ["crow:mmd"], ".mmd"),
86
+ ("Pattes de corbeau (Graphviz)", ["crow"], ".gv"),
87
+ ("Notation de Chen avec attributs (Graphviz)", ["chen:attrs"], ".gv"),
88
+ ]),
89
+ ("Partage", [
90
+ ("Lien vers Mocodo en ligne", ["share"], ".url"),
91
+ ("Prompt pour une IA (avec cardinalités et types)", ["prompt:cards,types"], ".txt"),
92
+ ]),
93
+ ]
94
+
95
+ # Fichiers que Mocodo écrit toujours et qui ne sont pas le résultat d'une conversion.
96
+ SIDE_FILES = {"mcd.mcd", "mcd.svg", "mcd_geo.json", "mcd_static.svg", "params.json"}
97
+
98
+ PALETTES = ["bw", "wb", "gray", "blank", "ocean", "pond", "desert", "keepsake", "mondrian", "xinnian",
99
+ "dark", "dark-ocean", "dark-pond", "dark-desert"] + [f"brewer{s}{n}" for s in "+-" for n in range(1, 10)]
100
+ # Police non connue de Mocodo : le dessin est calculé avec les proportions d'Arial (voir `options.py`).
101
+ ATKINSON = "Atkinson Hyperlegible Next"
102
+ ATKINSON_MONO = "Atkinson Hyperlegible Mono"
103
+ # polices à chasse fixe proposées pour l'éditeur et les textes calculés (les absentes du Mac sont ignorées)
104
+ EDITOR_FONTS = [ATKINSON_MONO, "SF Mono", "Menlo", "Monaco", "Courier New"]
105
+ SHAPES = [ATKINSON, "copperplate", "arial", "georgia", "sans", "serif", "times", "trebuchet", "verdana", "mondrian", "xinnian"]
106
+
107
+ CARD_FORMATS = ["{min_card},{max_card}", "({min_card},{max_card})", "{min_card}..{max_card}", "{min_card}-{max_card}"]
108
+ FK_FORMATS = ["#{label}", "{label}#", "{label}"]
109
+
110
+ EXAMPLES = [
111
+ ("Clients et commandes", """CLIENT: réf. client, nom, prénom, ville
112
+ PASSER, 0N CLIENT, 11 COMMANDE
113
+ COMMANDE: num. commande, date, montant
114
+ CONTENIR, 1N COMMANDE, 0N PRODUIT: quantité
115
+ PRODUIT: réf. produit, libellé, prix unitaire
116
+ """),
117
+ ("Bibliothèque", """ADHÉRENT: num. adhérent, nom, prénom
118
+ EMPRUNTER, 0N ADHÉRENT, 0N EXEMPLAIRE: date emprunt, date retour
119
+ EXEMPLAIRE: num. exemplaire, état
120
+ CORRESPONDRE, 11 EXEMPLAIRE, 0N LIVRE
121
+ LIVRE: ISBN, titre, année
122
+ ÉCRIRE, 1N LIVRE, 0N AUTEUR
123
+ AUTEUR: num. auteur, nom
124
+ """),
125
+ ("Employés et projets (tutoriel Mocodo)", """DÉPARTEMENT: num. département, nom département
126
+ EMPLOYER, 11 EMPLOYÉ, 1N DÉPARTEMENT
127
+ EMPLOYÉ: matricule, nom employé
128
+ TRAVAILLER, 0N EMPLOYÉ, 1N PROJET
129
+ PROJET: num. projet, nom projet
130
+ DIRIGER, 0N [responsable] EMPLOYÉ, 01 PROJET
131
+ """),
132
+ ("Association réflexive", """PIÈCE: réf. pièce, libellé pièce
133
+ COMPOSER, 0N [composée] PIÈCE, 0N [composante] PIÈCE: quantité
134
+ """),
135
+ ("Entité faible et dépendance fonctionnelle", """CHAMBRE: num. chambre, étage
136
+ DF, _11 CHAMBRE, 0N HÔTEL
137
+ HÔTEL: num. hôtel, nom, adresse
138
+ """),
139
+ ]
@@ -0,0 +1,104 @@
1
+ """Éditeur de code avec numéros de ligne et ligne courante mise en valeur."""
2
+ from PyQt6.QtCore import QRect, QSize, Qt
3
+ from PyQt6.QtGui import QColor, QFont, QPainter, QPalette, QTextFormat
4
+ from PyQt6.QtWidgets import QFrame, QPlainTextEdit, QTextEdit, QWidget
5
+
6
+
7
+ class LineNumberArea(QWidget):
8
+ def __init__(self, editor):
9
+ super().__init__(editor)
10
+ self.editor = editor
11
+
12
+ def sizeHint(self):
13
+ return QSize(self.editor.number_area_width(), 0)
14
+
15
+ def paintEvent(self, event):
16
+ self.editor.paint_numbers(event)
17
+
18
+
19
+ class CodeEditor(QPlainTextEdit):
20
+ """QPlainTextEdit avec une marge de numéros de ligne, sans cadre, à fond uni."""
21
+
22
+ def __init__(self):
23
+ super().__init__()
24
+ self.setFrameShape(QFrame.Shape.NoFrame)
25
+ self.setCursorWidth(2)
26
+ self.document().setDocumentMargin(10)
27
+ self.number_area = LineNumberArea(self)
28
+ self.gutter_bg = QColor("#ffffff")
29
+ self.gutter_fg, self.gutter_fg_current = QColor("#a1a1a6"), QColor("#5a5a5f")
30
+ self.current_line_color = QColor("#f4f6fa")
31
+ self.blockCountChanged.connect(self.update_margin)
32
+ self.updateRequest.connect(self.update_numbers)
33
+ self.cursorPositionChanged.connect(self.highlight_current_line)
34
+ self.update_margin()
35
+ self.highlight_current_line()
36
+
37
+ def gutter_font(self):
38
+ font = QFont(self.font())
39
+ font.setPointSizeF(max(self.font().pointSizeF() - 2, 8))
40
+ return font
41
+
42
+ def number_area_width(self):
43
+ digits = max(2, len(str(max(1, self.blockCount()))))
44
+ return 22 + self.fontMetrics().horizontalAdvance("9") * digits
45
+
46
+ def setFont(self, font):
47
+ super().setFont(font)
48
+ self.update_margin()
49
+
50
+ def update_margin(self):
51
+ self.setViewportMargins(self.number_area_width(), 0, 0, 0)
52
+
53
+ def update_numbers(self, rect, dy):
54
+ if dy:
55
+ self.number_area.scroll(0, dy)
56
+ else:
57
+ self.number_area.update(0, rect.y(), self.number_area.width(), rect.height())
58
+ if rect.contains(self.viewport().rect()):
59
+ self.update_margin()
60
+
61
+ def resizeEvent(self, event):
62
+ super().resizeEvent(event)
63
+ cr = self.contentsRect()
64
+ self.number_area.setGeometry(QRect(cr.left(), cr.top(), self.number_area_width(), cr.height()))
65
+
66
+ def set_colors(self, theme):
67
+ """Applique les couleurs du thème : fond et texte via la palette, le reste en direct."""
68
+ palette = self.palette()
69
+ palette.setColor(QPalette.ColorRole.Base, QColor(theme["editor_bg"]))
70
+ palette.setColor(QPalette.ColorRole.Text, QColor(theme["editor_fg"]))
71
+ self.setPalette(palette)
72
+ self.gutter_bg = QColor(theme["editor_bg"])
73
+ self.gutter_fg = QColor(theme["gutter_fg"])
74
+ self.gutter_fg_current = QColor(theme["gutter_fg_current"])
75
+ self.current_line_color = QColor(theme["current_line"])
76
+ self.highlight_current_line()
77
+ self.number_area.update()
78
+
79
+ def highlight_current_line(self):
80
+ selection = QTextEdit.ExtraSelection()
81
+ selection.format.setBackground(self.current_line_color)
82
+ selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True)
83
+ selection.cursor = self.textCursor()
84
+ selection.cursor.clearSelection()
85
+ self.setExtraSelections([] if self.textCursor().hasSelection() else [selection])
86
+ self.number_area.update()
87
+
88
+ def paint_numbers(self, event):
89
+ painter = QPainter(self.number_area)
90
+ painter.fillRect(event.rect(), self.gutter_bg)
91
+ painter.setFont(self.gutter_font())
92
+ current = self.textCursor().blockNumber()
93
+ block = self.firstVisibleBlock()
94
+ top = round(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
95
+ while block.isValid() and top <= event.rect().bottom():
96
+ height = round(self.blockBoundingRect(block).height())
97
+ if block.isVisible() and top + height >= event.rect().top():
98
+ number = block.blockNumber()
99
+ painter.setPen(self.gutter_fg_current if number == current else self.gutter_fg)
100
+ painter.drawText(0, top, self.number_area.width() - 10, height,
101
+ Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
102
+ str(number + 1))
103
+ block = block.next()
104
+ top += height
@@ -0,0 +1,14 @@
1
+ """Constantes partagées."""
2
+
3
+ TEMPLATE = """% Exemple : un client passe des commandes (les lignes consécutives forment une rangée,
4
+ % une ligne vide commence une nouvelle rangée)
5
+ CLIENT: Réf. client, Nom, Prénom, Ville
6
+ PASSER, 0N CLIENT, 11 COMMANDE
7
+ COMMANDE: Num. commande, Date, Montant
8
+ CONTENIR, 1N COMMANDE, 0N PRODUIT: Quantité
9
+ PRODUIT: Réf. produit, Libellé, Prix unitaire
10
+ """
11
+ APP_NAME = "MocodoEditor"
12
+ BLANK_SVG = b'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'
13
+ MAX_RECENT = 8
14
+ FILTER = "Fichiers Mocodo (*.mcd);;Tous les fichiers (*)"
@@ -0,0 +1,106 @@
1
+ """Impression et exports (PNG, SVG) du dernier diagramme rendu par la fenêtre principale."""
2
+ from pathlib import Path
3
+
4
+ from PyQt6.QtCore import QByteArray, QMarginsF, QRectF, QSizeF, Qt
5
+ from PyQt6.QtGui import QImage, QPageLayout, QPageSize, QPainter, QPdfWriter
6
+ from PyQt6.QtPrintSupport import QPrintDialog, QPrinter
7
+ from PyQt6.QtSvg import QSvgRenderer
8
+ from PyQt6.QtWidgets import QDialog, QFileDialog, QMessageBox
9
+
10
+
11
+
12
+ def print_diagram(win):
13
+ renderer = valid_renderer(win, "Impression impossible")
14
+ if not renderer:
15
+ return
16
+ printer = QPrinter(QPrinter.PrinterMode.HighResolution)
17
+ if QPrintDialog(printer, win).exec() == QDialog.DialogCode.Accepted:
18
+ paint_to_printer(renderer, printer)
19
+
20
+
21
+ def paint_to_printer(renderer, printer):
22
+ """Dessine le SVG en haut de la page, à sa taille réelle (96 px = 1 pouce),
23
+ réduit si nécessaire pour tenir dans la zone imprimable."""
24
+ page = printer.pageRect(QPrinter.Unit.DevicePixel)
25
+ size = renderer.defaultSize()
26
+ scale = printer.resolution() / 96
27
+ scale = min(scale, page.width() / size.width(), page.height() / size.height())
28
+ w, h = size.width() * scale, size.height() * scale
29
+ painter = QPainter(printer)
30
+ renderer.render(painter, QRectF(page.x() + (page.width() - w) / 2, page.y(), w, h))
31
+ painter.end()
32
+
33
+
34
+ def valid_renderer(win, title):
35
+ if not win.last_svg:
36
+ QMessageBox.warning(win, title, "Aucun MCD n'a encore été rendu correctement.")
37
+ return None
38
+ renderer = QSvgRenderer(QByteArray(win.last_svg))
39
+ size = renderer.defaultSize()
40
+ if not renderer.isValid() or not size.isValid() or size.isEmpty():
41
+ QMessageBox.warning(win, title, "Le MCD rendu est invalide ou sans dimensions.")
42
+ return None
43
+ return renderer
44
+
45
+
46
+ def export_png(win):
47
+ renderer = valid_renderer(win, "Export impossible")
48
+ if not renderer:
49
+ return
50
+ size = renderer.defaultSize()
51
+ default = str((win.path or Path("mcd")).with_suffix(".png"))
52
+ name, _ = QFileDialog.getSaveFileName(
53
+ win, "Exporter en PNG", default, "Images PNG (*.png)")
54
+ if not name:
55
+ return
56
+ if not Path(name).suffix:
57
+ name += ".png"
58
+ image = QImage(size, QImage.Format.Format_ARGB32)
59
+ image.fill(Qt.GlobalColor.transparent)
60
+ painter = QPainter(image)
61
+ renderer.render(painter)
62
+ painter.end()
63
+ if image.save(name, "PNG"):
64
+ win.statusBar().showMessage(f"Exporté : {name} ({size.width()}×{size.height()})", 5000)
65
+ else:
66
+ QMessageBox.critical(win, "Erreur", f"Écriture impossible :\n{name}")
67
+
68
+
69
+ def export_svg(win):
70
+ if not win.last_svg:
71
+ QMessageBox.warning(win, "Export impossible", "Aucun MCD n'a encore été rendu correctement.")
72
+ return
73
+ default = str((win.path or Path("mcd")).with_suffix(".svg"))
74
+ name, _ = QFileDialog.getSaveFileName(win, "Exporter en SVG", default, "Images SVG (*.svg)")
75
+ if not name:
76
+ return
77
+ if not Path(name).suffix:
78
+ name += ".svg"
79
+ try:
80
+ Path(name).write_bytes(win.last_svg)
81
+ except OSError as e:
82
+ QMessageBox.critical(win, "Erreur", f"Écriture impossible :\n{e}")
83
+ return
84
+ win.statusBar().showMessage(f"Exporté : {name}", 5000)
85
+
86
+
87
+ def export_pdf(win):
88
+ """PDF vectoriel, à la taille du MCD (une page aux dimensions du dessin, sans marge)."""
89
+ renderer = valid_renderer(win, "Export impossible")
90
+ if not renderer:
91
+ return
92
+ default = str((win.path or Path("mcd")).with_suffix(".pdf"))
93
+ name, _ = QFileDialog.getSaveFileName(win, "Exporter en PDF", default, "Documents PDF (*.pdf)")
94
+ if not name:
95
+ return
96
+ if not Path(name).suffix:
97
+ name += ".pdf"
98
+ size = renderer.defaultSize()
99
+ writer = QPdfWriter(name)
100
+ writer.setResolution(96)
101
+ writer.setPageLayout(QPageLayout(QPageSize(QSizeF(size.width(), size.height()), QPageSize.Unit.Point),
102
+ QPageLayout.Orientation.Portrait, QMarginsF(0, 0, 0, 0)))
103
+ painter = QPainter(writer)
104
+ renderer.render(painter, QRectF(0, 0, writer.width(), writer.height()))
105
+ painter.end()
106
+ win.statusBar().showMessage(f"Exporté : {name}", 5000)
@@ -0,0 +1,33 @@
1
+ """Ouverture d'un résultat dans une autre application de la même famille (PUMLEditor, SVGEditor)."""
2
+ import subprocess
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
+ # extension du résultat → (nom de l'application macOS, libellé du bouton)
7
+ EDITORS = {
8
+ ".puml": ("PUMLEditor", "Ouvrir dans PUMLEditor"),
9
+ ".svg": ("SVGEditor", "Ouvrir dans SVGEditor"),
10
+ }
11
+
12
+
13
+ def open_in_editor(ext: str, content: str | bytes, stem: str = "mcd") -> str | None:
14
+ """Écrit le résultat dans un fichier temporaire (`<stem><ext>`) et l'ouvre avec l'application associée à
15
+ l'extension. Retourne un message d'erreur, ou None si l'ouverture a été demandée."""
16
+ if ext not in EDITORS:
17
+ return f"Aucune application associée à « {ext} »."
18
+ app = EDITORS[ext][0]
19
+ folder = Path(tempfile.gettempdir()) / "MocodoEditor"
20
+ try:
21
+ folder.mkdir(exist_ok=True)
22
+ target = folder / f"{stem}{ext}"
23
+ if isinstance(content, str):
24
+ target.write_text(content, encoding="utf-8")
25
+ else:
26
+ target.write_bytes(content)
27
+ run = subprocess.run(["open", "-a", app, str(target)], capture_output=True, text=True, timeout=20)
28
+ except (OSError, subprocess.TimeoutExpired) as e:
29
+ return f"Ouverture impossible : {e}"
30
+ if run.returncode != 0:
31
+ return (f"{app} est introuvable (l'application doit être installée, par exemple dans /Applications).\n\n"
32
+ f"{run.stderr.strip()}")
33
+ return None
@@ -0,0 +1,157 @@
1
+ """Barre de recherche et de remplacement."""
2
+ from PyQt6.QtCore import Qt, pyqtSignal
3
+ from PyQt6.QtGui import QColor, QPainter, QTextCursor, QTextDocument
4
+ from PyQt6.QtWidgets import QHBoxLayout, QLineEdit, QPushButton, QToolButton, QVBoxLayout, QWidget
5
+
6
+
7
+ class FindBar(QWidget):
8
+ """Barre de recherche sous l'éditeur (Entrée : suivant, Maj+Entrée : précédent)."""
9
+ not_found = pyqtSignal()
10
+ info = pyqtSignal(str)
11
+
12
+ def __init__(self, editor):
13
+ super().__init__()
14
+ self.editor = editor
15
+ self.field = QLineEdit(placeholderText="Rechercher…", clearButtonEnabled=True)
16
+ self.case = QToolButton(text="Aa", checkable=True, autoRaise=True)
17
+ self.case.setToolTip("Respecter la casse")
18
+ prev_btn, next_btn, close_btn = (QToolButton(text=t, autoRaise=True) for t in ("‹", "›", "✕"))
19
+ for b, tip in [(prev_btn, "Précédent"), (next_btn, "Suivant"), (close_btn, "Fermer")]:
20
+ b.setToolTip(tip)
21
+ b.setFixedWidth(28)
22
+
23
+ self.replace_field = QLineEdit(placeholderText="Remplacer par…", clearButtonEnabled=True)
24
+ replace_btn, replace_all_btn = QPushButton("Remplacer"), QPushButton("Tout remplacer")
25
+ self.replace_row = QWidget()
26
+ row = QHBoxLayout(self.replace_row)
27
+ row.setContentsMargins(0, 0, 0, 0)
28
+ for w in (self.replace_field, replace_btn, replace_all_btn):
29
+ row.addWidget(w)
30
+
31
+ layout = QVBoxLayout(self)
32
+ layout.setContentsMargins(10, 8, 10, 8)
33
+ layout.setSpacing(6)
34
+ top = QHBoxLayout()
35
+ for w in (self.field, self.case, prev_btn, next_btn, close_btn):
36
+ top.addWidget(w)
37
+ layout.addLayout(top)
38
+ layout.addWidget(self.replace_row)
39
+
40
+ self.field.returnPressed.connect(self.find_next)
41
+ self.replace_field.returnPressed.connect(self.replace_current)
42
+ next_btn.clicked.connect(self.find_next)
43
+ prev_btn.clicked.connect(self.find_prev)
44
+ close_btn.clicked.connect(self.close_bar)
45
+ replace_btn.clicked.connect(self.replace_current)
46
+ replace_all_btn.clicked.connect(self.replace_all)
47
+ self.field.textChanged.connect(lambda: self.find(backward=False, from_start=True))
48
+ self.hide()
49
+
50
+ def paintEvent(self, event):
51
+ """Fond de barre et filet supérieur, comme une barre secondaire macOS."""
52
+ p = QPainter(self)
53
+ p.fillRect(self.rect(), self.palette().window())
54
+ line = QColor(self.palette().windowText().color())
55
+ line.setAlpha(36)
56
+ p.fillRect(0, 0, self.width(), 1, line)
57
+ p.end()
58
+
59
+ def keyPressEvent(self, event):
60
+ if event.key() == Qt.Key.Key_Escape:
61
+ self.close_bar()
62
+ elif (event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter)
63
+ and event.modifiers() & Qt.KeyboardModifier.ShiftModifier):
64
+ self.find_prev()
65
+ else:
66
+ super().keyPressEvent(event)
67
+
68
+ def open_bar(self, replace=False):
69
+ sel = self.editor.textCursor().selection().toPlainText()
70
+ if sel and "\n" not in sel:
71
+ self.field.setText(sel)
72
+ self.replace_row.setVisible(replace)
73
+ self.show()
74
+ self.field.setFocus()
75
+ self.field.selectAll()
76
+
77
+ def open_replace(self):
78
+ self.open_bar(replace=True)
79
+
80
+ def case_flags(self):
81
+ return (QTextDocument.FindFlag.FindCaseSensitively if self.case.isChecked()
82
+ else QTextDocument.FindFlag(0))
83
+
84
+ def selection_matches(self):
85
+ sel = self.editor.textCursor().selectedText()
86
+ text = self.field.text()
87
+ if not sel:
88
+ return False
89
+ return sel == text if self.case.isChecked() else sel.lower() == text.lower()
90
+
91
+ def replace_current(self):
92
+ """Remplace l'occurrence sélectionnée (la sélectionne d'abord si besoin), puis passe à la suivante."""
93
+ if not self.field.text():
94
+ return
95
+ if not self.selection_matches():
96
+ self.find_next()
97
+ if not self.selection_matches():
98
+ return
99
+ cur = self.editor.textCursor()
100
+ cur.insertText(self.replace_field.text())
101
+ self.editor.setTextCursor(cur)
102
+ self.find_next()
103
+
104
+ def replace_all(self):
105
+ text = self.field.text()
106
+ if not text:
107
+ return
108
+ doc, flags, repl = self.editor.document(), self.case_flags(), self.replace_field.text()
109
+ count, pos = 0, 0
110
+ edit = QTextCursor(doc)
111
+ edit.beginEditBlock() # une seule étape d'annulation pour tout le remplacement
112
+ while True:
113
+ found = doc.find(text, pos, flags)
114
+ if found.isNull():
115
+ break
116
+ found.insertText(repl)
117
+ pos = found.position()
118
+ count += 1
119
+ edit.endEditBlock()
120
+ if count:
121
+ self.info.emit(f"{count} remplacement{'s' if count > 1 else ''}")
122
+ else:
123
+ self.not_found.emit()
124
+
125
+ def close_bar(self):
126
+ self.hide()
127
+ self.editor.setFocus()
128
+
129
+ def find_next(self):
130
+ self.find(backward=False)
131
+
132
+ def find_prev(self):
133
+ self.find(backward=True)
134
+
135
+ def find(self, backward, from_start=False):
136
+ text = self.field.text()
137
+ if not text:
138
+ return
139
+ flags = QTextDocument.FindFlag(0)
140
+ if backward:
141
+ flags |= QTextDocument.FindFlag.FindBackward
142
+ if self.case.isChecked():
143
+ flags |= QTextDocument.FindFlag.FindCaseSensitively
144
+ cur = self.editor.textCursor()
145
+ if from_start: # recherche incrémentale : repartir du début de la sélection courante
146
+ cur.setPosition(cur.selectionStart())
147
+ self.editor.setTextCursor(cur)
148
+ if self.editor.find(text, flags):
149
+ return
150
+ # retour à la ligne : on repart du début (ou de la fin)
151
+ wrap = QTextCursor(self.editor.document())
152
+ wrap.movePosition(QTextCursor.MoveOperation.End if backward
153
+ else QTextCursor.MoveOperation.Start)
154
+ self.editor.setTextCursor(wrap)
155
+ if not self.editor.find(text, flags):
156
+ self.editor.setTextCursor(cur)
157
+ self.not_found.emit()