"""On-demand export queue; only final publication can touch requested output paths.""" from __future__ import annotations import copy import shutil import tempfile import threading from pathlib import Path from PySide6.QtCore import Qt, QThreadPool, Slot, QTimer from PySide6.QtWidgets import (QCheckBox, QComboBox, QDialog, QFileDialog, QHBoxLayout, QLabel, QListWidget, QListWidgetItem, QMessageBox, QPushButton, QVBoxLayout) from .batch_documents import BatchDocument, combine_documents, fingerprint, publish_outputs from .document_tree import discover_documents from .docx_exporter import export_markdown_to_docx from .export_check import check_export, confirm_export, ExportIssue from .export_jobs import ExportJob, check_cancelled from .export_workflow import ExportSnapshot from .pdf_export_task import PdfExportController class BatchExportDialog(QDialog): def __init__(self, window): super().__init__(window) self.window = window self.job = self.pdf = None self.directory = None self.cancel_event = threading.Event() self.running = False self.setWindowTitle("批量与合并导出") self.resize(750, 650) layout = QVBoxLayout(self) layout.addWidget(QLabel("勾选文件并调整顺序;导出使用当前未保存的编辑内容和当前样式。")) self.files = QListWidget() for entry in discover_documents(window.project_root, ("markdown",)): if entry.path.suffix.lower() not in {".md", ".markdown"}: continue item = QListWidgetItem(entry.relative_path) item.setData(Qt.ItemDataRole.UserRole, entry.path) item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable) item.setCheckState(Qt.CheckState.Checked if entry.path == window.current_file else Qt.CheckState.Unchecked) self.files.addItem(item) layout.addWidget(self.files) order = QHBoxLayout() for title, callback in (("上移", lambda: self.move(-1)), ("下移", lambda: self.move(1)), ("全选", lambda: self.select_all(True)), ("全不选", lambda: self.select_all(False))): button = QPushButton(title); button.clicked.connect(callback); order.addWidget(button) layout.addLayout(order) self.format = QComboBox(); self.format.addItem("Word(Pandoc)", "docx"); self.format.addItem("PDF", "pdf") self.combined = QCheckBox("合并为一份文档(按文件分章,统一目录和页码)") layout.addWidget(self.format); layout.addWidget(self.combined) self.status = QLabel("尚未开始"); self.status.setWordWrap(True); layout.addWidget(self.status) actions = QHBoxLayout() self.start_button = QPushButton("选择输出位置并导出") self.stop_button = QPushButton("取消导出"); self.stop_button.setEnabled(False) self.start_button.clicked.connect(self.start); self.stop_button.clicked.connect(self.cancel) close = QPushButton("关闭"); close.clicked.connect(self.close) for button in (self.start_button, self.stop_button, close): actions.addWidget(button) layout.addLayout(actions) def move(self, delta): if self.running: return row = self.files.currentRow(); new = row + delta if row >= 0 and 0 <= new < self.files.count(): self.files.insertItem(new, self.files.takeItem(row)); self.files.setCurrentRow(new) def select_all(self, checked): if self.running: return for index in range(self.files.count()): self.files.item(index).setCheckState(Qt.CheckState.Checked if checked else Qt.CheckState.Unchecked) def start(self): paths = [self.files.item(i).data(Qt.ItemDataRole.UserRole) for i in range(self.files.count()) if self.files.item(i).checkState() == Qt.CheckState.Checked] if self.running or not paths: return settings = self.window.exports._choose_page_settings() if settings is None: return suffix = self.format.currentData() if self.combined.isChecked(): filename, _ = QFileDialog.getSaveFileName(self, "合并导出", str(self.window.project_root / f"合并文档.{suffix}"), f"{suffix.upper()} (*.{suffix})") if not filename: return destinations = [Path(filename).with_suffix('.' + suffix)] else: folder = QFileDialog.getExistingDirectory(self, "选择批量导出文件夹") if not folder: return destinations = [Path(folder) / f"{index:03d}-{path.stem}.{suffix}" for index, path in enumerate(paths, 1)] existing = [p.name for p in destinations if p.exists()] if existing and QMessageBox.question(self, "替换已有导出文件?", '\n'.join(existing), QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes: return try: buffers = self.window._editor_sources() documents = [BatchDocument(path, buffers[path] if path in buffers else path.read_text(encoding='utf-8-sig')) for path in paths] issues = [] style = copy.deepcopy(self.window.custom_document_styles.get(self.window.document_style_id, {})) for document in documents: issues.extend(ExportIssue(issue.line, f"{document.path.name}:{issue.message}") for issue in check_export(document.source, document.path, 'pandoc' if suffix == 'docx' else 'pdf', style.get('css', ''))) if not confirm_export(self, issues): return snapshot = ExportSnapshot(paths[0], documents[0].source, style, self.window.document_font_family, self.window.document_font_size, self.window.document_style_id, self.window._render_options()) self.begin(documents, destinations, suffix, self.combined.isChecked(), snapshot, settings) except (OSError, ValueError) as exc: QMessageBox.warning(self, "无法导出", str(exc)) def begin(self, documents, destinations, kind, combined, snapshot, settings): if self.window.exports._pdf_controller is not None: raise ValueError("请先完成或取消当前 PDF 导出。") self.expected = {path: fingerprint(path) for path in destinations} self.directory = Path(tempfile.mkdtemp(prefix='mdhelper-batch-')) self.outputs = {path: self.directory / f'{i}.{kind}' for i, path in enumerate(destinations)} self.documents, self.snapshot, self.page_settings = documents, snapshot, settings self.cancel_event.clear(); self.running = True self.start_button.setEnabled(False); self.stop_button.setEnabled(True) self.files.setEnabled(False); self.format.setEnabled(False); self.combined.setEnabled(False) self.status.setText("正在准备文档…") self.pdf_queue = [] from .markdown_renderer import MarkdownRenderer renderer = MarkdownRenderer(self.window.app_root) def prepare(cancel, progress): composition = combine_documents(documents, renderer, cancel) if combined else None if kind == 'docx': jobs = [(snapshot.path, composition.word_source)] if composition else [(d.path, d.source) for d in documents] for index, ((source_path, source), staged) in enumerate(zip(jobs, self.outputs.values()), 1): check_cancelled(cancel); progress(f"正在导出 Word:{index}/{len(jobs)}") export_markdown_to_docx(source, staged, engine='pandoc', source_path=source_path, style_rules=snapshot.style.get('rules', {}), document_font_family=snapshot.font, document_font_size=snapshot.font_size, preset=snapshot.preset, page_settings=settings, cancel=cancel) return ('publish', None) queue = [] if composition: content = renderer._wrap_html(body=composition.html_body, title='合并文档', **snapshot.rendering.kwargs()) queue.append((next(iter(self.outputs.values())), content, composition.headings, documents[0].path)) else: from .markdown_utils import Heading for document, staged in zip(documents, self.outputs.values()): check_cancelled(cancel) env = {'path': str(document.path), 'headings': []} renderer.markdown.parse(document.source, env) content = renderer.render_source(document.source, document.path, **snapshot.rendering.kwargs()) queue.append((staged, content, [Heading(**h) for h in env['headings']], document.path)) return ('pdf', queue) self.run_job(prepare) def run_job(self, callback): self.job = ExportJob(callback) self.job.cancel = self.cancel_event self.job.signals.progress.connect(self.status.setText) self.job.signals.finished.connect(self.job_finished) QThreadPool.globalInstance().start(self.job) @Slot(object, str) def job_finished(self, result, error): self.job = None if result and result[0] == 'complete' and not error: self.finish('', success=True); return if error or self.cancel_event.is_set() or result is None: self.finish(error); return stage, value = result if stage == 'pdf': self.pdf_queue = value self.next_pdf() elif stage == 'publish': self.publish() else: self.finish('', success=True) def next_pdf(self): if self.cancel_event.is_set(): self.finish(''); return if not self.pdf_queue: self.publish(); return output, content, headings, source = self.pdf_queue.pop(0) self.status.setText(f"正在生成 PDF:{source.name},剩余 {len(self.pdf_queue)} 份") self.pdf = PdfExportController(self.window.exports, output, content, headings, self.page_settings, source, self.pdf_finished) self.window.exports._pdf_controller = self.pdf self.pdf.start() def pdf_finished(self, result, error): self.pdf = None if result is None or error or self.cancel_event.is_set(): self.finish(error) else: QTimer.singleShot(0, self, self.next_pdf) def publish(self): self.status.setText("全部文档转换完成,正在保存输出…") def commit(cancel, progress): publish_outputs(self.outputs, self.expected, self.directory, cancel) return ('complete', None) self.run_job(commit) def finish(self, error, success=False): if self.directory and '输出恢复失败' not in error: shutil.rmtree(self.directory, ignore_errors=True) self.directory = None self.running = False self.start_button.setEnabled(True); self.stop_button.setEnabled(False) self.files.setEnabled(True); self.format.setEnabled(True); self.combined.setEnabled(True) self.status.setText(f"已导出 {len(self.outputs)} 份文件:\n" + '\n'.join(str(p) for p in self.outputs) if success else (f"导出失败:{error}" if error else "已取消,原有输出文件保持不变。")) def cancel(self): self.cancel_event.set() if self.pdf: self.pdf.cancel() def closeEvent(self, event): if self.running: self.cancel(); self.status.setText("正在取消并清理临时文件…") event.ignore() else: super().closeEvent(event)