xvExos 0.2.0__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.
xvexos/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """xvExos : préparation de feuilles d'exercices LaTeX (classe exercice_pdf)."""
2
+
3
+ __version__ = "0.2.0"
xvexos/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .gui import main
2
+
3
+ main()
xvexos/calendrier.py ADDED
@@ -0,0 +1,63 @@
1
+ """Petit calendrier en français (tkinter/ttk seul)."""
2
+
3
+ import calendar
4
+ import datetime as dt
5
+ import tkinter as tk
6
+ from tkinter import ttk
7
+
8
+ from .core import MOIS
9
+
10
+ JOURS_COURTS = ["Lu", "Ma", "Me", "Je", "Ve", "Sa", "Di"]
11
+
12
+
13
+ def choisir_date(parent, start: dt.date | None = None) -> dt.date | None:
14
+ """Ouvre un calendrier modal ; renvoie la date cliquée, ou None."""
15
+ start = start or dt.date.today()
16
+ win = tk.Toplevel(parent)
17
+ win.title("Calendrier")
18
+ win.transient(parent)
19
+ win.resizable(False, False)
20
+ shown = [start.year, start.month]
21
+ result = []
22
+
23
+ head = ttk.Frame(win, padding=6)
24
+ head.pack(fill="x")
25
+ title = ttk.Label(head, anchor="center", font="TkHeadingFont")
26
+ grid = ttk.Frame(win, padding=(6, 0, 6, 6))
27
+ grid.pack()
28
+
29
+ def change(delta):
30
+ y, m = shown[0], shown[1] + delta
31
+ shown[:] = [y + (m - 1) // 12, (m - 1) % 12 + 1]
32
+ draw()
33
+
34
+ def pick(day):
35
+ result.append(day)
36
+ win.destroy()
37
+
38
+ def draw():
39
+ y, m = shown
40
+ title.config(text=f"{MOIS[m - 1]} {y}")
41
+ for w in grid.winfo_children():
42
+ w.destroy()
43
+ for c, name in enumerate(JOURS_COURTS):
44
+ ttk.Label(grid, text=name, anchor="center").grid(row=0, column=c, sticky="ew")
45
+ for r, week in enumerate(calendar.Calendar(firstweekday=0).monthdatescalendar(y, m), 1):
46
+ for c, day in enumerate(week):
47
+ b = ttk.Button(grid, text=str(day.day), width=3, command=lambda d=day: pick(d))
48
+ if day.month != m:
49
+ b.state(["disabled"])
50
+ if day == start:
51
+ b.state(["pressed"])
52
+ b.grid(row=r, column=c)
53
+
54
+ ttk.Button(head, text="«", width=3, command=lambda: change(-12)).pack(side="left")
55
+ ttk.Button(head, text="‹", width=3, command=lambda: change(-1)).pack(side="left")
56
+ ttk.Button(head, text="»", width=3, command=lambda: change(12)).pack(side="right")
57
+ ttk.Button(head, text="›", width=3, command=lambda: change(1)).pack(side="right")
58
+ title.pack(side="left", fill="x", expand=True)
59
+ win.bind("<Escape>", lambda e: win.destroy())
60
+ draw()
61
+ win.grab_set()
62
+ win.wait_window()
63
+ return result[0] if result else None
xvexos/config.py ADDED
@@ -0,0 +1,97 @@
1
+ """Configuration persistante (``~/.config/xvexos/config.toml``).
2
+
3
+ Au premier lancement, les réglages de l'ancien xvExos (``~/.xvExos``) sont
4
+ importés : classe et lycée par défaut, liens de ``Racine/`` (racines des
5
+ exercices) et répertoire ``Devoirs/`` (archives).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ import tomllib
13
+ from dataclasses import asdict, dataclass, field, fields
14
+ from pathlib import Path
15
+
16
+ from .core import read_text
17
+
18
+ HOME = Path.home()
19
+ CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", HOME / ".config")) / "xvexos"
20
+ CONFIG_FILE = CONFIG_DIR / "config.toml"
21
+ LEGACY_DIR = HOME / ".xvExos"
22
+
23
+
24
+ @dataclass
25
+ class Config:
26
+ roots: list[str] = field(default_factory=list) # racines des exercices
27
+ archive_dir: str = str(LEGACY_DIR / "Devoirs")
28
+ work_dir: str = str(Path(os.environ.get("XDG_CACHE_HOME", HOME / ".cache")) / "xvexos")
29
+ texinputs: list[str] = field(default_factory=list)
30
+ docclass: str = "exercice_pdf"
31
+ compile_cmd: list[str] = field(default_factory=lambda: [
32
+ "latexmk", "-pdf", "-interaction=nonstopmode", "-file-line-error", "{tex}"])
33
+ viewer_cmd: list[str] = field(default_factory=lambda: ["xdg-open", "{pdf}"])
34
+ # Valeurs par défaut d'une nouvelle feuille
35
+ kind: str = "ds"
36
+ orientation: str = "portrait"
37
+ size: str = "12pt"
38
+ mode: str = "final"
39
+ classe: str = ""
40
+ lycee: str = ""
41
+ scale: float = 0.0 # échelle de l'interface ; 0 = automatique (HiDPI)
42
+
43
+ @property
44
+ def root_paths(self) -> list[Path]:
45
+ return [Path(r).expanduser() for r in self.roots]
46
+
47
+ # -- lecture / écriture ------------------------------------------------
48
+
49
+ @classmethod
50
+ def load(cls, path: Path = CONFIG_FILE) -> "Config":
51
+ if path.exists():
52
+ with open(path, "rb") as f:
53
+ data = tomllib.load(f)
54
+ known = {f.name for f in fields(cls)}
55
+ return cls(**{k: v for k, v in data.items() if k in known})
56
+ cfg = cls()
57
+ cfg.import_legacy()
58
+ cfg.save(path)
59
+ return cfg
60
+
61
+ def save(self, path: Path = CONFIG_FILE) -> None:
62
+ path.parent.mkdir(parents=True, exist_ok=True)
63
+ lines = ["# Configuration de xvExos (générée automatiquement, modifiable)", ""]
64
+ for key, value in asdict(self).items():
65
+ lines.append(f"{key} = {_toml(value)}")
66
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
67
+
68
+ # -- import de l'ancien xvExos -------------------------------------------
69
+
70
+ def import_legacy(self, legacy: Path = LEGACY_DIR) -> None:
71
+ defaults = legacy / "xvExos_defaults"
72
+ if defaults.exists():
73
+ text, _ = read_text(defaults)
74
+ opts = dict(re.findall(r"set optionsTex\((\d)\) (\S+)", text))
75
+ self.kind = opts.get("0", self.kind)
76
+ self.orientation = opts.get("1", self.orientation)
77
+ self.size = opts.get("2", self.size)
78
+ self.mode = opts.get("3", self.mode)
79
+ titles = dict(re.findall(r'set makeTitle\((\d)\)\s+"?([^"}\n]*)"?', text))
80
+ self.classe = titles.get("4", self.classe).strip()
81
+ self.lycee = titles.get("5", self.lycee).strip()
82
+ racine = legacy / "Racine"
83
+ if racine.is_dir():
84
+ for p in sorted(racine.iterdir()):
85
+ if p.is_dir():
86
+ self.roots.append(str(p.resolve()))
87
+
88
+
89
+ def _toml(value) -> str:
90
+ if isinstance(value, bool):
91
+ return "true" if value else "false"
92
+ if isinstance(value, (int, float)):
93
+ return str(value)
94
+ if isinstance(value, list):
95
+ return "[" + ", ".join(_toml(v) for v in value) + "]"
96
+ s = str(value).replace("\\", "\\\\").replace('"', '\\"')
97
+ return f'"{s}"'
xvexos/core.py ADDED
@@ -0,0 +1,359 @@
1
+ """Logique métier de xvExos, indépendante de l'interface graphique.
2
+
3
+ - lecture des exercices (titre tiré du premier ``\\section{...}``) ;
4
+ - modèle d'une feuille (:class:`Sheet`) ;
5
+ - génération du source LaTeX (:func:`render`) et relecture d'une feuille
6
+ existante (:func:`parse`), compatible avec les feuilles produites par
7
+ l'ancien xvExos (Tcl/Tk) ;
8
+ - index des exercices des différentes racines (:class:`ExerciseIndex`).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import datetime as dt
14
+ import os
15
+ import re
16
+ import unicodedata
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ # Fichiers LaTeX fournis avec le package (exercice_pdf.cls, alias…)
21
+ TEX_DIR = Path(__file__).parent / "tex"
22
+
23
+ # Options reconnues par exercice_pdf.cls
24
+ SHEET_TYPES = ["ds", "dm", "td", "interro", "colle", "collefiche", "inventaire"]
25
+ ORIENTATIONS = ["portrait", "landscape"]
26
+ FONT_SIZES = ["10pt", "11pt", "12pt"]
27
+ MODES = ["final", "draft"]
28
+
29
+ # Champs du titre : (attribut de Sheet, macro LaTeX)
30
+ TITLE_FIELDS = [
31
+ ("titre", "titre"),
32
+ ("numero", "numeroYC"),
33
+ ("jour", "jour"),
34
+ ("annee", "annee"),
35
+ ("classe", "classe"),
36
+ ("lycee", "lycee"),
37
+ ]
38
+
39
+ JOURS = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]
40
+ MOIS = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet",
41
+ "août", "septembre", "octobre", "novembre", "décembre"]
42
+
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # Utilitaires
46
+ # ---------------------------------------------------------------------------
47
+
48
+ def french_date(d: dt.date | None = None) -> str:
49
+ """« jeudi 13 août 2015 », indépendamment de la locale du système."""
50
+ d = d or dt.date.today()
51
+ return f"{JOURS[d.weekday()]} {d.day} {MOIS[d.month - 1]} {d.year}"
52
+
53
+
54
+ def parse_french_date(text: str) -> dt.date | None:
55
+ """Inverse de :func:`french_date` (« jeudi 13 août 2015 », « 1er mars 2026 »,
56
+ « 13/08/2015 ») ; ``None`` si la date n'est pas reconnue."""
57
+ t = normalize(text)
58
+ m = re.search(r"(\d{1,2})/(\d{1,2})/(\d{4})", t)
59
+ if m:
60
+ d, mo, y = map(int, m.groups())
61
+ else:
62
+ months = [normalize(x) for x in MOIS]
63
+ m = re.search(r"(\d{1,2})(?:er)?\s+([a-z]+)\.?\s+(\d{4})", t)
64
+ if not m:
65
+ return None
66
+ name = m.group(2)
67
+ hits = [i for i, x in enumerate(months) if x.startswith(name[:3])]
68
+ if not hits:
69
+ return None
70
+ d, mo, y = int(m.group(1)), hits[0] + 1, int(m.group(3))
71
+ try:
72
+ return dt.date(y, mo, d)
73
+ except ValueError:
74
+ return None
75
+
76
+
77
+ def school_year(d: dt.date | None = None) -> str:
78
+ """Année scolaire « 2026-27 » (bascule au 1er août)."""
79
+ d = d or dt.date.today()
80
+ y = d.year if d.month >= 8 else d.year - 1
81
+ return f"{y}-{(y + 1) % 100:02d}"
82
+
83
+
84
+ def read_text(path: Path) -> tuple[str, str]:
85
+ """Lit un fichier texte en UTF-8, ou en Latin-1 à défaut.
86
+
87
+ Renvoie ``(texte, encodage)`` pour pouvoir réécrire dans le même encodage.
88
+ """
89
+ data = Path(path).read_bytes()
90
+ try:
91
+ return data.decode("utf-8"), "utf-8"
92
+ except UnicodeDecodeError:
93
+ return data.decode("latin-1"), "latin-1"
94
+
95
+
96
+ def strip_comment(line: str) -> str:
97
+ """Supprime un commentaire LaTeX (``%`` non précédé de ``\\``)."""
98
+ m = re.search(r"(?<!\\)%", line)
99
+ return line if m is None else line[: m.start()]
100
+
101
+
102
+ def uncommented(text: str) -> str:
103
+ return "\n".join(strip_comment(line) for line in text.splitlines())
104
+
105
+
106
+ def braced(text: str, start: int) -> str | None:
107
+ """Contenu de la paire d'accolades ouverte à ``text[start] == '{'``."""
108
+ if start >= len(text) or text[start] != "{":
109
+ return None
110
+ depth, i = 0, start
111
+ while i < len(text):
112
+ c = text[i]
113
+ if c == "\\": # caractère échappé (\{, \}, \\) : on le saute
114
+ i += 2
115
+ continue
116
+ if c == "{":
117
+ depth += 1
118
+ elif c == "}":
119
+ depth -= 1
120
+ if depth == 0:
121
+ return text[start + 1: i]
122
+ i += 1
123
+ return None
124
+
125
+
126
+ def macro_argument(text: str, macro: str) -> str | None:
127
+ """Argument de la première occurrence non commentée de ``\\macro{...}``."""
128
+ clean = uncommented(text)
129
+ m = re.search(r"\\" + re.escape(macro) + r"\s*(?=\{)", clean)
130
+ return None if m is None else braced(clean, m.end())
131
+
132
+
133
+ def normalize(s: str) -> str:
134
+ """Minuscules sans accents, pour la recherche."""
135
+ s = unicodedata.normalize("NFKD", s.casefold())
136
+ return "".join(c for c in s if not unicodedata.combining(c))
137
+
138
+
139
+ # ---------------------------------------------------------------------------
140
+ # Exercices
141
+ # ---------------------------------------------------------------------------
142
+
143
+ _title_cache: dict[Path, tuple[float, str | None]] = {}
144
+
145
+
146
+ def exercise_title(path: Path) -> str | None:
147
+ """Titre d'un exercice (premier ``\\section{...}``).
148
+
149
+ Renvoie ``None`` si le fichier est un document complet (il contient un
150
+ ``\\documentclass``) : ce n'est alors pas un exercice. Renvoie ``""`` s'il
151
+ n'y a pas de section.
152
+ """
153
+ path = Path(path)
154
+ try:
155
+ mtime = path.stat().st_mtime
156
+ except OSError:
157
+ return None
158
+ cached = _title_cache.get(path)
159
+ if cached and cached[0] == mtime:
160
+ return cached[1]
161
+ try:
162
+ text, _ = read_text(path)
163
+ except OSError:
164
+ return None
165
+ clean = uncommented(text)
166
+ if "\\documentclass" in clean:
167
+ title = None
168
+ else:
169
+ m = re.search(r"\\section\*?\s*(?=\{)", clean)
170
+ title = "" if m is None else " ".join((braced(clean, m.end()) or "").split())
171
+ _title_cache[path] = (mtime, title)
172
+ return title
173
+
174
+
175
+ def forget_title(path: Path) -> None:
176
+ _title_cache.pop(Path(path), None)
177
+
178
+
179
+ def list_dir(path: Path) -> tuple[list[Path], list[Path]]:
180
+ """Sous-répertoires et fichiers ``.tex`` d'un répertoire (triés, sans
181
+ fichiers cachés, en suivant les liens symboliques)."""
182
+ dirs, files = [], []
183
+ try:
184
+ entries = sorted(Path(path).iterdir(), key=lambda p: p.name.casefold())
185
+ except OSError:
186
+ return [], []
187
+ for p in entries:
188
+ if p.name.startswith("."):
189
+ continue
190
+ try:
191
+ if p.is_dir():
192
+ dirs.append(p)
193
+ elif p.suffix == ".tex" and p.is_file():
194
+ files.append(p)
195
+ except OSError:
196
+ pass
197
+ return dirs, files
198
+
199
+
200
+ def collect_exercises(path: Path, recursive: bool) -> list[Path]:
201
+ """Exercices d'un répertoire (et de ses sous-répertoires si demandé)."""
202
+ dirs, files = list_dir(path)
203
+ result = [f for f in files if exercise_title(f) is not None]
204
+ if recursive:
205
+ for d in dirs:
206
+ result += collect_exercises(d, True)
207
+ return result
208
+
209
+
210
+ class ExerciseIndex:
211
+ """Index ``nom de fichier -> chemins`` de tous les exercices des racines."""
212
+
213
+ def __init__(self, roots: list[Path]):
214
+ self.roots = [Path(r) for r in roots]
215
+ self._by_name: dict[str, list[Path]] | None = None
216
+
217
+ def _build(self) -> dict[str, list[Path]]:
218
+ if self._by_name is None:
219
+ self._by_name = {}
220
+ for root in self.roots:
221
+ for dirpath, dirnames, filenames in os.walk(root, followlinks=True):
222
+ dirnames[:] = sorted(d for d in dirnames if not d.startswith("."))
223
+ for f in sorted(filenames):
224
+ if f.endswith(".tex"):
225
+ self._by_name.setdefault(f, []).append(Path(dirpath, f))
226
+ return self._by_name
227
+
228
+ def resolve(self, name: str) -> list[Path]:
229
+ """Chemins correspondant à un argument de ``\\newfile{...}``."""
230
+ name = Path(name).name
231
+ if not name.endswith(".tex"):
232
+ name += ".tex"
233
+ return list(self._build().get(name, []))
234
+
235
+ def search(self, query: str) -> list[Path]:
236
+ """Exercices dont le nom ou le titre contient tous les mots de
237
+ ``query`` (sans tenir compte de la casse ni des accents)."""
238
+ words = normalize(query).split()
239
+ hits = []
240
+ for paths in self._build().values():
241
+ for p in paths:
242
+ title = exercise_title(p)
243
+ if title is None:
244
+ continue
245
+ hay = normalize(p.name + " " + title)
246
+ if all(w in hay for w in words):
247
+ hits.append(p)
248
+ return sorted(hits, key=lambda p: p.name.casefold())
249
+
250
+ def root_of(self, path: Path) -> Path | None:
251
+ path = Path(path)
252
+ for root in self.roots:
253
+ try:
254
+ path.relative_to(root)
255
+ return root
256
+ except ValueError:
257
+ continue
258
+ return None
259
+
260
+
261
+ # ---------------------------------------------------------------------------
262
+ # Feuille
263
+ # ---------------------------------------------------------------------------
264
+
265
+ @dataclass
266
+ class Sheet:
267
+ kind: str = "ds"
268
+ orientation: str = "portrait"
269
+ size: str = "12pt"
270
+ mode: str = "final"
271
+ extra: list[str] = field(default_factory=list) # options inconnues gardées telles quelles
272
+ titre: str = ""
273
+ numero: str = "1"
274
+ jour: str = ""
275
+ annee: str = ""
276
+ classe: str = ""
277
+ lycee: str = ""
278
+ exercises: list[Path] = field(default_factory=list)
279
+ newdir: bool = True # \newdir avant chaque répertoire (inventaire)
280
+ docclass: str = "exercice_pdf"
281
+
282
+ def options(self) -> list[str]:
283
+ return [self.kind, self.orientation, self.size, self.mode, *self.extra]
284
+
285
+ def archive_name(self) -> str:
286
+ """Nom d'archive de l'ancien xvExos : ``devoirs2026-27/ds-3.tex``."""
287
+ return f"devoirs{self.annee}/{self.kind}-{self.numero}.tex"
288
+
289
+
290
+ def _newdir_label(path: Path, roots: list[Path]) -> str:
291
+ for root in roots:
292
+ try:
293
+ rel = Path(path).parent.relative_to(root)
294
+ except ValueError:
295
+ continue
296
+ return str(Path(root.name, rel)) if str(rel) != "." else root.name
297
+ return Path(path).parent.name
298
+
299
+
300
+ def render(sheet: Sheet, roots: list[Path] = (), program: str = "xvExos") -> str:
301
+ """Source LaTeX de la feuille."""
302
+ out = [f"% Fichier TeX généré automatiquement par {program}", "",
303
+ f"\\documentclass[{','.join(sheet.options())}]{{{sheet.docclass}}}", ""]
304
+ for attr, macro in TITLE_FIELDS:
305
+ out.append(f"\\{macro}{{{getattr(sheet, attr)}}}")
306
+ out += ["", "\\begin{document}", "\\maketitle", ""]
307
+ previous = None
308
+ for exo in sheet.exercises:
309
+ if sheet.kind == "inventaire" and sheet.newdir:
310
+ label = _newdir_label(exo, list(roots))
311
+ if label != previous:
312
+ out += [f"\\newdir{{{label}}}", ""]
313
+ previous = label
314
+ out += [f"\\newfile{{{Path(exo).name}}}", ""]
315
+ out += ["\\findelafeuille", "\\end{document}", ""]
316
+ return "\n".join(out)
317
+
318
+
319
+ def parse(text: str) -> tuple[Sheet, list[str]]:
320
+ """Relit une feuille. Renvoie la feuille (sans exercices) et la liste des
321
+ arguments des ``\\newfile{...}`` non commentés, dans l'ordre."""
322
+ sheet = Sheet(extra=[])
323
+ clean = uncommented(text)
324
+ m = re.search(r"\\documentclass\s*(?:\[([^\]]*)\])?\s*\{([^}]*)\}", clean)
325
+ if m:
326
+ sheet.docclass = m.group(2).strip()
327
+ for opt in (o.strip() for o in (m.group(1) or "").split(",")):
328
+ if not opt:
329
+ continue
330
+ if opt in SHEET_TYPES:
331
+ sheet.kind = opt
332
+ elif opt in ORIENTATIONS:
333
+ sheet.orientation = opt
334
+ elif opt in FONT_SIZES:
335
+ sheet.size = opt
336
+ elif opt in MODES:
337
+ sheet.mode = opt
338
+ elif opt not in sheet.extra:
339
+ sheet.extra.append(opt)
340
+ for attr, macro in TITLE_FIELDS:
341
+ value = macro_argument(text, macro)
342
+ if value is None and macro == "numeroYC":
343
+ value = macro_argument(text, "numero")
344
+ if value is not None:
345
+ setattr(sheet, attr, value)
346
+ sheet.newdir = re.search(r"\\newdir\s*\{", clean) is not None
347
+ names = []
348
+ for m in re.finditer(r"\\newfile\s*(?=\{)", clean):
349
+ arg = braced(clean, m.end())
350
+ if arg:
351
+ names.append(arg.strip())
352
+ return sheet, names
353
+
354
+
355
+ def texinputs(dirs: list[Path]) -> str:
356
+ """Valeur de TEXINPUTS : répertoire courant, ``dirs`` (récursivement), puis
357
+ les chemins par défaut de TeX (``:`` final)."""
358
+ parts = ["."] + [f"{Path(d)}//" for d in dirs]
359
+ return os.pathsep.join(parts) + os.pathsep