Coverage for graphica/gui/mixins/export_mixin.py: 88.9%
310 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-25 19:22 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-25 19:22 +0000
1"""画像・PDF・SVG への書き出し、印刷、クリップボード、書き出しのプレビュー。"""
2import contextlib
3import copy
4import datetime
5import io
6import os
7import dataclasses
8import logging
9import matplotlib as mpl
10from PySide6.QtCore import Qt
11from PySide6.QtGui import QPixmap, QPainter, QImage
12from PySide6.QtWidgets import QApplication, QDialog, QProgressDialog
13from PySide6.QtPrintSupport import QPrinter, QPrintDialog
14from matplotlib.figure import Figure
15from matplotlib.backends.backend_pdf import PdfPages
17from graphica.gui import notify
18from graphica.gui import dialog_dirs
19from graphica.core.axis_settings import axis_setting
20from graphica.gui.dialogs import BatchExportDialog, CaptionGeneratorDialog, CVDSimulationDialog
21from graphica.gui.canvas import _HeadlessRenderCanvas
22from graphica.gui.export_settings import export_rc_params, is_croppable_format, outside_frame_cropped
23from graphica.gui.export_size import size_in_inches
24from graphica.gui.task_runner import TaskRunner
25from graphica.models.project import ProjectModel
26from graphica.core.plugin_api import get_plugin_api, get_registered_exporters
27from graphica.core.plugin_types import PluginExecutionError
28from graphica.core.script_export import generate_python_script
29from graphica.core.caption_export import sanitize_label
30from graphica.core.report_export import collect_methods_sections, generate_html_report
32logger = logging.getLogger(__name__)
34CLIPBOARD_COPY_DPI = 150
36PRINT_RENDER_DPI = 200
38BATCH_EXPORT_FIGSIZE = (8, 6)
41class ExportMixin:
42 def output_dark_mode(self):
43 """書き出し・コピー・印刷の図をダークの配色で描くか。エクスポートのタブの「ライト配色で書き出す」が既定でオン。"""
44 panel = getattr(self, 'export_preview_panel', None)
45 light = panel is None or panel.light_colors_checkbox.isChecked()
46 return self.canvas.dark_mode and not light
48 @contextlib.contextmanager
49 def _screen_figure_in_output_colors(self):
50 """画面の図をそのまま保存する経路のため、ダークのまま書き出さないときだけ、その間ライトで描き直しておく。"""
51 if self.output_dark_mode() == self.canvas.dark_mode:
52 yield
53 return
54 self.canvas.dark_mode = False
55 self._update_plot(light=True)
56 try:
57 yield
58 finally:
59 self.canvas.dark_mode = True
60 self._update_plot(light=True)
62 def _on_copy_plot_to_clipboard(self):
63 buf = io.BytesIO()
64 try:
65 with self._screen_figure_in_output_colors():
66 self.canvas.fig.savefig(buf, format='png', dpi=CLIPBOARD_COPY_DPI, bbox_inches='tight')
67 except Exception as e:
68 logger.exception("グラフのクリップボードコピーに失敗しました。")
69 notify.warning(self, "コピーエラー", f"グラフのコピー中にエラーが発生しました:\n{e}")
70 return
71 buf.seek(0)
73 pixmap = QPixmap()
74 pixmap.loadFromData(buf.read())
75 buf.close()
77 QApplication.clipboard().setPixmap(pixmap)
79 def _on_show_cvd_simulation(self):
80 """今のグラフを1回だけ PNG にし、ダイアログはその画像を変換して見せる(グラフは描き直さない)。"""
81 buf = io.BytesIO()
82 try:
83 with self._screen_figure_in_output_colors():
84 self.canvas.fig.savefig(buf, format='png', dpi=CLIPBOARD_COPY_DPI, bbox_inches='tight')
85 except Exception as e:
86 logger.exception("色覚シミュレーションプレビュー用の画像生成に失敗しました。")
87 notify.warning(self, "プレビューエラー", f"プレビュー画像の生成中にエラーが発生しました:\n{e}")
88 return
89 buf.seek(0)
90 image = QImage()
91 image.loadFromData(buf.read())
92 buf.close()
94 dialog = CVDSimulationDialog(image, self)
95 dialog.exec()
97 def _on_print_plot(self):
98 """PNG に描いてから QPrinter に貼る(書き出しと同じ描画結果になる)。"""
99 printer = QPrinter(QPrinter.PrinterMode.HighResolution)
100 print_dialog = QPrintDialog(printer, self)
101 if print_dialog.exec() != QDialog.DialogCode.Accepted:
102 return
104 buf = io.BytesIO()
105 try:
106 with self._screen_figure_in_output_colors():
107 self.canvas.fig.savefig(buf, format='png', dpi=PRINT_RENDER_DPI, bbox_inches='tight')
108 except Exception as e:
109 logger.exception("印刷用画像の生成に失敗しました。")
110 notify.warning(self, "印刷エラー", f"印刷用の画像生成中にエラーが発生しました:\n{e}")
111 return
112 buf.seek(0)
114 pixmap = QPixmap()
115 pixmap.loadFromData(buf.read())
116 buf.close()
118 if pixmap.isNull(): 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true
119 notify.warning(self, "印刷エラー", "印刷用の画像生成に失敗しました。")
120 return
122 painter = QPainter()
123 if not painter.begin(printer): 123 ↛ 124line 123 didn't jump to line 124 because the condition on line 123 was never true
124 notify.warning(self, "印刷エラー", "プリンターへの描画を開始できませんでした。")
125 return
126 try:
127 page_rect = printer.pageRect(QPrinter.Unit.DevicePixel).toRect()
128 scaled = pixmap.scaled(
129 page_rect.size(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation
130 )
131 x = page_rect.x() + (page_rect.width() - scaled.width()) // 2
132 y = page_rect.y() + (page_rect.height() - scaled.height()) // 2
133 painter.drawPixmap(x, y, scaled)
134 finally:
135 painter.end()
137 self.statusBar().showMessage("印刷を実行しました", 3000)
139 def _on_batch_export(self):
140 """サブプロットごと、または複数のプロジェクトファイルをまとめて書き出す。別スレッドで1本の TaskRunner で行う。
142 rc_context はプロセス全体の rcParams を書き換えるので、並列にはしない。
143 """
144 if self._batch_export_task_runner is not None:
145 notify.information(self, "実行中", "別のバッチエクスポート処理が実行中です。完了までお待ちください。")
146 return
148 extra_formats = [exp.format_name for exp in get_registered_exporters()]
149 dialog = BatchExportDialog(len(self.project.all_plot_settings), self, extra_formats=extra_formats)
150 if dialog.exec() != QDialog.DialogCode.Accepted:
151 return
153 options = dialog.get_common_options()
154 # 別スレッドではタブの欄を読まないので、配色もここで決めておく
155 options['dark_mode'] = self.output_dark_mode()
156 if not options['output_dir']:
157 notify.warning(self, "バッチエクスポート", "出力先フォルダを指定してください。")
158 return
160 mode = dialog.get_mode()
161 if mode == "subplots":
162 indices = dialog.get_selected_subplot_indices()
163 if not indices:
164 notify.warning(self, "バッチエクスポート", "書き出すサブプロットを選択してください。")
165 return
166 items = indices
167 worker_fn = self._batch_export_subplots
168 # 別スレッドで描くので、画面のマウスで変えた範囲はここで写しておく
169 options['view_overrides'] = (
170 copy.deepcopy(self.canvas.view_overrides) if dialog.visible_range_checkbox.isChecked() else {})
171 else:
172 paths = dialog.get_project_file_paths()
173 if not paths:
174 notify.warning(self, "バッチエクスポート", "プロジェクトファイルを追加してください。")
175 return
176 items = paths
177 worker_fn = self._batch_export_project_files
179 progress_dialog = QProgressDialog("バッチエクスポートを実行中...", "キャンセル", 0, len(items), self)
180 progress_dialog.setWindowModality(Qt.WindowModality.WindowModal)
181 progress_dialog.setMinimumDuration(0)
182 progress_dialog.setValue(0)
184 runner = TaskRunner(worker_fn, items, options)
185 runner.progress.connect(lambda done, total, message: progress_dialog.setValue(done))
186 progress_dialog.canceled.connect(runner.requestInterruption)
187 runner.succeeded.connect(lambda results: self._on_batch_export_succeeded(results, progress_dialog))
188 runner.failed.connect(lambda msg: self._on_batch_export_failed(msg, progress_dialog))
189 self._batch_export_task_runner = runner
190 runner.start()
192 def _cleanup_batch_export_task_runner(self):
193 if self._batch_export_task_runner is not None: 193 ↛ exitline 193 didn't return from function '_cleanup_batch_export_task_runner' because the condition on line 193 was always true
194 self._batch_export_task_runner.wait()
195 self._batch_export_task_runner.deleteLater()
196 self._batch_export_task_runner = None
198 def _on_batch_export_failed(self, error_message, progress_dialog):
199 self._cleanup_batch_export_task_runner()
200 progress_dialog.close()
201 notify.warning(self, "バッチエクスポート", f"バッチエクスポート処理に失敗しました:\n{error_message}")
203 def _on_batch_export_succeeded(self, results, progress_dialog):
204 """結果は [(出力ファイル名, エラーか None), ...]。キャンセルなら終わった分だけ。"""
205 self._cleanup_batch_export_task_runner()
206 progress_dialog.close()
208 succeeded = [name for name, error in results if error is None]
209 failed = [(name, error) for name, error in results if error is not None]
211 if not succeeded and not failed: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true
212 return # 1件も終わらないうちにキャンセルされた
214 message = f"{len(succeeded)}件を書き出しました。"
215 if failed:
216 message += "\n\n失敗:\n" + "\n".join(f"{name}: {error}" for name, error in failed)
217 notify.information(self, "バッチエクスポート完了", message)
219 def _save_figure_with_options(self, fig, out_path, options):
220 """bbox_inches='tight' で保存する。rc の設定は export_rc_params(SVG の文字の扱い、PDF の TrueType 埋め込み)。
222 形式がプラグインの書き出しの名前なら、プラグインの writer を呼ぶ。
223 """
224 api = get_plugin_api()
225 exporter = api.get_exporter(options['format']) if api is not None else None
226 if exporter is not None:
227 try:
228 exporter.writer(fig, out_path)
229 except Exception as e:
230 raise PluginExecutionError(exporter.name, f"「{out_path}」への書き出しに失敗しました: {e}") from e
231 return
233 save_kwargs = {'transparent': options.get('transparent', True), 'bbox_inches': 'tight'}
234 if options['format'] not in ('pdf', 'svg'):
235 save_kwargs['dpi'] = options['dpi']
236 crop = options.get('crop_outside_frame', False) and is_croppable_format(options['format'])
237 with mpl.rc_context(export_rc_params(options['format'], options.get('svg_text_as_path', False))), outside_frame_cropped(fig, crop):
238 fig.savefig(out_path, **save_kwargs)
240 def _batch_export_subplots(self, indices, options, report_progress=None, is_cancelled=None):
241 """サブプロットを1枚ずつ書き出す。1x1 の一時キャンバスなので、subplot_target を 0 にした写しを渡す。
243 別スレッドで呼ばれるので Qt には触れない(_HeadlessRenderCanvas は QWidget ではない)。
244 キャンセルは1件ごとにしか見ない(1件の描画と保存は中断できない)。
245 """
246 results = []
247 total = len(indices)
248 for i, idx in enumerate(indices): 248 ↛ 272line 248 didn't jump to line 272 because the loop on line 248 didn't complete
249 if is_cancelled is not None and is_cancelled():
250 break
251 if report_progress is not None: 251 ↛ 252line 251 didn't jump to line 252 because the condition on line 251 was never true
252 report_progress(i, total, f"P{idx + 1}")
253 out_name = f"{options['prefix']}_P{idx + 1}.{options['format']}"
254 out_path = os.path.join(options['output_dir'], out_name)
255 try:
256 settings = self.project.all_plot_settings[idx]
257 datasets_for_axis = [
258 dataclasses.replace(ds, subplot_target=0)
259 for ds in self.project.datasets if ds.subplot_target == idx
260 ]
261 temp_canvas = _HeadlessRenderCanvas(width=BATCH_EXPORT_FIGSIZE[0], height=BATCH_EXPORT_FIGSIZE[1], dpi=options['dpi'])
262 temp_canvas.dark_mode = options.get('dark_mode', self.canvas.dark_mode)
263 visible_range = options.get('view_overrides', {}).get(idx)
264 if visible_range: 264 ↛ 265line 264 didn't jump to line 265 because the condition on line 264 was never true
265 temp_canvas.view_overrides = {0: dict(visible_range)}
266 temp_canvas.redraw_all(datasets_for_axis, 1, 1, [settings], full_resolution=options.get('full_resolution', False))
267 self._save_figure_with_options(temp_canvas.fig, out_path, options)
268 results.append((out_name, None))
269 except Exception as e:
270 logger.exception("バッチエクスポート(サブプロット)に失敗しました: %s", out_name)
271 results.append((out_name, str(e)))
272 return results
274 def _batch_export_project_files(self, paths, options, report_progress=None, is_cancelled=None):
275 """プロジェクトファイルを1つずつ読み、その図を書き出す。開いているプロジェクトには触れない。別スレッドで呼ばれる。"""
276 results = []
277 total = len(paths)
278 for i, path in enumerate(paths): 278 ↛ 314line 278 didn't jump to line 314 because the loop on line 278 didn't complete
279 if is_cancelled is not None and is_cancelled():
280 break
281 if report_progress is not None: 281 ↛ 282line 281 didn't jump to line 282 because the condition on line 281 was never true
282 report_progress(i, total, os.path.basename(path))
283 base_name = os.path.splitext(os.path.basename(path))[0]
284 out_name = f"{options['prefix']}_{base_name}.{options['format']}"
285 out_path = os.path.join(options['output_dir'], out_name)
286 try:
287 temp_project = ProjectModel()
288 temp_project.load_project(path)
289 layout_mode = getattr(temp_project, 'layout_mode', 'grid')
290 if layout_mode == 'free': 290 ↛ 292line 290 didn't jump to line 292 because the condition on line 290 was never true
291 # 自由配置には行×列が無いので、サブプロットの数に応じた大きさにする
292 if not temp_project.all_plot_settings:
293 raise ValueError("有効なプロット設定が見つかりません")
294 rows, cols = 0, 0
295 fig_width, fig_height = BATCH_EXPORT_FIGSIZE[0] * 2, BATCH_EXPORT_FIGSIZE[1] * 2
296 else:
297 rows, cols = temp_project.layout_rows, temp_project.layout_cols
298 if rows * cols == 0 or not temp_project.all_plot_settings: 298 ↛ 299line 298 didn't jump to line 299 because the condition on line 298 was never true
299 raise ValueError("有効なプロット設定が見つかりません")
300 fig_width, fig_height = BATCH_EXPORT_FIGSIZE[0] * cols, BATCH_EXPORT_FIGSIZE[1] * rows
302 temp_canvas = _HeadlessRenderCanvas(width=fig_width, height=fig_height, dpi=options['dpi'])
303 temp_canvas.dark_mode = options.get('dark_mode', self.canvas.dark_mode)
304 temp_canvas.redraw_all(
305 temp_project.datasets, rows, cols, temp_project.all_plot_settings, layout_mode=layout_mode,
306 panel_labels_enabled=temp_project.panel_labels_enabled,
307 full_resolution=options.get('full_resolution', False),
308 )
309 self._save_figure_with_options(temp_canvas.fig, out_path, options)
310 results.append((out_name, None))
311 except Exception as e:
312 logger.exception("バッチエクスポート(プロジェクトファイル)に失敗しました: %s", path)
313 results.append((os.path.basename(path), str(e)))
314 return results
316 def _on_export_python_script(self):
317 """matplotlib だけで図を再現するスクリプトを書き出す(生成は core/script_export.py)。"""
318 file_path, _ = dialog_dirs.get_save_file_name(
319 self, dialog_dirs.EXPORT, "Pythonスクリプトとしてエクスポート", dialog_dirs.project_stem(self),
320 "Python Files (*.py)", preferred_dir=dialog_dirs.output_dir(self)
321 )
322 if not file_path:
323 return
324 if not file_path.endswith('.py'):
325 file_path += '.py'
327 # サブプロットの行数と列数は画面にしか無いことがある(保存の前)。古い値のままだと 2 つ目以降の軸が抜ける
328 self._sync_project_from_ui()
329 try:
330 script_text = generate_python_script(self.project)
331 with open(file_path, 'w', encoding='utf-8') as f:
332 f.write(script_text)
333 except Exception as e:
334 notify.warning(self, "保存エラー", f"スクリプトの書き出し中にエラーが発生しました:\n{e}")
335 logger.exception("Pythonスクリプトの書き出し中にエラー")
336 return
338 self.statusBar().showMessage(f"Pythonスクリプトを書き出しました: {file_path}", 3000)
340 def _on_generate_caption(self):
341 """今の軸のタイトルを初期値にキャプションのダイアログを出す(生成は core/caption_export.py)。"""
342 settings = {}
343 if 0 <= self.project.active_axis_index < len(self.project.all_plot_settings): 343 ↛ 345line 343 didn't jump to line 345 because the condition on line 343 was always true
344 settings = self.project.all_plot_settings[self.project.active_axis_index]
345 default_caption = axis_setting(settings, 'title') or ''
346 default_label = sanitize_label(default_caption)
348 dialog = CaptionGeneratorDialog(default_caption, default_label, self)
349 dialog.exec()
351 def _on_generate_report(self):
352 """グラフの画像と、履歴のある全データセットの方法の文を1つのレポートにする。形式は拡張子(.html / .pdf)で決まる。"""
353 settings = {}
354 if 0 <= self.project.active_axis_index < len(self.project.all_plot_settings): 354 ↛ 356line 354 didn't jump to line 356 because the condition on line 354 was always true
355 settings = self.project.all_plot_settings[self.project.active_axis_index]
356 title = axis_setting(settings, 'title') or "実験レポート"
358 file_path, _ = dialog_dirs.get_save_file_name(
359 self, dialog_dirs.EXPORT, "実験レポートを生成", dialog_dirs.project_stem(self),
360 "HTML Files (*.html);;PDF Files (*.pdf)", preferred_dir=dialog_dirs.output_dir(self)
361 )
362 if not file_path:
363 return
364 file_ext = os.path.splitext(file_path)[1].lower()
365 if file_ext not in ('.html', '.pdf'):
366 file_ext = '.html'
367 file_path += file_ext
369 methods_sections = collect_methods_sections(self.project)
371 try:
372 with self._screen_figure_in_output_colors():
373 if file_ext == '.pdf':
374 self._write_pdf_report(file_path, title, methods_sections)
375 else:
376 buf = io.BytesIO()
377 self.canvas.fig.savefig(buf, format='png', dpi=150, bbox_inches='tight')
378 html_text = generate_html_report(buf.getvalue(), methods_sections, title=title)
379 with open(file_path, 'w', encoding='utf-8') as f:
380 f.write(html_text)
381 except Exception as e:
382 logger.exception("実験レポートの生成中にエラーが発生しました。")
383 notify.warning(self, "保存エラー", f"実験レポートの生成中にエラーが発生しました:\n{e}")
384 return
386 self.statusBar().showMessage(f"実験レポートを書き出しました: {file_path}", 3000)
388 def _write_pdf_report(self, file_path, title, methods_sections):
389 """1ページ目にグラフ、2ページ目にタイトルと方法の文。"""
390 from graphica.gui.mathtext_preview import JP_CAPABLE_FONT_FAMILIES
392 with mpl.rc_context(export_rc_params('pdf')), PdfPages(file_path) as pdf:
393 pdf.savefig(self.canvas.fig, bbox_inches='tight')
395 text_fig = Figure(figsize=(8.27, 11.69)) # A4 縦
396 text_fig.text(0.08, 0.95, title, fontsize=16, fontweight='bold', va='top',
397 family=JP_CAPABLE_FONT_FAMILIES)
398 body_lines = [f"生成日時: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}", "", "方法:"]
399 if methods_sections: 399 ↛ 400line 399 didn't jump to line 400 because the condition on line 399 was never true
400 for name, text in methods_sections:
401 body_lines.append(f"・{name}: {text}")
402 else:
403 body_lines.append("(処理履歴を持つデータセットはありません)")
404 text_fig.text(0.08, 0.88, "\n".join(body_lines), fontsize=10, va='top', wrap=True,
405 family=JP_CAPABLE_FONT_FAMILIES)
406 pdf.savefig(text_fig)
408 def _on_export_plot(self):
409 """メニューと上部バーの書き出し。インスペクタの「エクスポート」タブの設定で保存し、その設定をタブで見せる。"""
410 self.show_export_preview()
411 self.export_preview_panel.save_to_chosen_file()
413 def _calculate_size_in_inches(self, options):
414 """ダイアログの幅と高さをインチにする。"""
415 return size_in_inches(options["width"], options["height"], options["unit"], options["dpi"])