Coverage for graphica/gui/panels/axis_settings.py: 84.9%
439 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"""軸の設定の部品: 画面の欄と設定の辞書の相互変換、サブプロットの行数と列数、フォントと色の選択、その信号の配線。"""
2import copy
3import functools
4import logging
5from PySide6.QtCore import QTimer
6from PySide6.QtGui import QFont
7from PySide6.QtWidgets import QDialog, QFontDialog, QMessageBox
9from graphica.core.i18n import tr
10from graphica.gui import notify
11from graphica.core.axis_settings import AXIS_SETTING_DEFAULTS, axis_setting
12from graphica.gui import log_axis_notes, theme
13from graphica.gui.axis_bindings import CARRIED_AXIS_KEYS
14from graphica.gui.builders.axis_format_sections import refresh_axis_format_widgets
15from graphica.gui.color_history import get_color_with_history
16from graphica.gui.rendering.appearance import waterfall_x_shift
17from graphica.gui.dialogs import LegendOrderDialog, LabelEditDialog
19logger = logging.getLogger(__name__)
22# Windows の「Arial Narrow」は matplotlib には family="Arial", stretch="condensed" として登録されていて、
23# 名前のままでは見つからず黙って既定のフォントになる。末尾の語を stretch に読み替えて探し直す。
24_FONT_STRETCH_KEYWORDS = {
25 'narrow': 'condensed',
26 'condensed': 'condensed',
27 'semicondensed': 'semi-condensed',
28 'extracondensed': 'extra-condensed',
29 'ultracondensed': 'ultra-condensed',
30 'wide': 'expanded',
31 'expanded': 'expanded',
32 'semiexpanded': 'semi-expanded',
33 'extraexpanded': 'extra-expanded',
34 'ultraexpanded': 'ultra-expanded',
35}
38@functools.lru_cache(maxsize=256)
39def _resolve_font_family_for_matplotlib(family_name: str):
40 """(matplotlib に渡す family, stretch または None, 解決できたか) を返す。
42 軸の設定を変えるたびに呼ばれるので、findfont の結果をキャッシュする。
43 """
44 import matplotlib.font_manager as fm
46 try:
47 fm.findfont(fm.FontProperties(family=family_name), fallback_to_default=False)
48 return family_name, None, True
49 except ValueError:
50 pass
52 words = family_name.rsplit(None, 1)
53 if len(words) == 2:
54 base, suffix = words
55 stretch = _FONT_STRETCH_KEYWORDS.get(suffix.lower())
56 if stretch is not None:
57 try:
58 fm.findfont(fm.FontProperties(family=base, stretch=stretch), fallback_to_default=False)
59 return base, stretch, True
60 except ValueError:
61 pass
63 return family_name, None, False
66def _order_labels(labels, order):
67 """order の順に並べ、order に無いラベルは元の順のまま末尾に置く。"""
68 if not order:
69 return list(labels)
70 order_index = {name: i for i, name in enumerate(order)}
71 indices = sorted(
72 range(len(labels)),
73 key=lambda i: (0, order_index[labels[i]]) if labels[i] in order_index else (1, i)
74 )
75 return [labels[i] for i in indices]
78# 「この書式を全サブプロットに適用」で写す鍵: ラベル/書式のタブの見た目だけ(文字・範囲・目盛の間隔・凡例は写さない)
79AXIS_FORMAT_KEYS = (
80 'x_label_visible', 'y_label_visible',
81 'tick_font', 'tick_color', 'major_tick_direction', 'minor_tick_direction',
82 'major_tick_direction_y2', 'minor_tick_direction_y2', 'tick_width', 'major_tick_length', 'minor_tick_length',
83 'axis_label_font', 'axis_label_color',
84 'grid_visible', 'minor_grid_visible',
85 *(f'{axis}_{which}_grid_{part}' for axis in ('x', 'y') for which in ('major', 'minor')
86 for part in ('linestyle', 'width', 'alpha')),
87 'spine_width', 'spine_color',
88 'colorbar_enabled', 'colorbar_position', 'colorbar_width_fraction',
89)
92class AxisSettingsPanel:
93 """状態はタブが持ち、この部品はメソッドと信号の配線だけを持つ。PlotterApp の同じ名前は窓口(gui/panels/__init__.py)。"""
95 # PlotterApp から同じ名前で使えるもの(テスト・メニュー・ほかの部品が使う)
96 EXPOSED_NAMES = (
97 '_on_y2_autoscale_changed', '_on_y2_axis_state_changed', '_refresh_y2_axis_state',
98 '_apply_settings_to_ui_controls', '_block_all_signals', '_connect_axis_setting_signals',
99 '_connect_layout_signals', '_current_active_axis', '_font_props_to_dict', '_gather_settings_from_ui',
100 '_grid_linestyle_code', '_grid_linestyle_index', '_on_active_axis_changed', '_on_axis_setting_changed',
101 '_on_change_axis_label_color', '_on_change_axis_label_font', '_on_change_legend_color',
102 '_on_change_legend_font', '_on_change_spine_color', '_on_change_tick_color', '_on_change_tick_font',
103 '_on_edit_legend_order', '_on_grid_visibility_changed', '_on_layout_changed', '_on_legend_drag_release',
104 '_on_legend_loc_changed', '_on_legend_visibility_changed', '_on_share_axis_changed',
105 '_on_x_autoscale_changed', '_on_x_minor_tick_visibility_changed', '_on_x_tick_mode_changed',
106 '_on_y_autoscale_changed', '_on_y_minor_tick_visibility_changed', '_on_y_tick_mode_changed',
107 '_open_label_edit_dialog', '_refresh_all_label_previews', '_refresh_grid_state', '_refresh_label_preview',
108 '_refresh_legend_state', '_refresh_x_autoscale_enabled_state', '_refresh_x_minor_tick_state',
109 '_refresh_x_tick_mode_state', '_refresh_y_autoscale_enabled_state', '_refresh_y_minor_tick_state',
110 '_refresh_y_tick_mode_state', '_seed_min_max_spinboxes', '_store_dragged_legend_positions',
111 '_update_subplot_combos', '_warn_if_font_family_unavailable_for_graph',
112 )
114 def __init__(self, app):
115 self._app = app
117 def _on_layout_changed(self):
118 if getattr(self._app.project, 'layout_mode', 'grid') == 'free': 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true
119 return
121 # 欄の値を変える間、変更の通知が連鎖しないように
122 self._block_all_signals(True)
124 rows = self._app.subplot_rows_spinbox.value()
125 cols = self._app.subplot_cols_spinbox.value()
126 total_plots = rows * cols
128 current_plot_count = len(self._app.project.all_plot_settings)
130 if total_plots > current_plot_count:
131 # 増えた分は今の軸の設定をもとにする
132 default_settings = self._gather_settings_from_ui()
133 for _ in range(total_plots - current_plot_count):
134 new_settings = default_settings.copy()
135 # 注釈は引き継がない。浅いコピーなので、空のリストにしないと全部が同じリストを共有する
136 new_settings['annotations'] = []
137 new_settings['legend_order'] = []
138 self._app.project.all_plot_settings.append(new_settings)
140 elif total_plots < current_plot_count: 140 ↛ 149line 140 didn't jump to line 149 because the condition on line 140 was always true
141 self._app.project.all_plot_settings = self._app.project.all_plot_settings[:total_plots]
143 # 無くなったサブプロットを描画先にしていたデータセットは、どこにも描かれず
144 # エクスポートにも入らないのに気づけないので、最後のサブプロットに移す
145 for dataset in self._app.project.datasets:
146 if dataset.subplot_target >= total_plots: 146 ↛ 145line 146 didn't jump to line 145 because the condition on line 146 was always true
147 dataset.subplot_target = total_plots - 1
149 if self._app.project.active_axis_index >= total_plots:
150 self._app.project.active_axis_index = 0
152 self._update_subplot_combos()
153 self._apply_settings_to_ui_controls(self._app.project.all_plot_settings[self._app.project.active_axis_index])
155 self._block_all_signals(False)
157 self._app._update_plot()
159 def _on_share_axis_changed(self):
160 self._app.project.share_x_axis = self._app.share_x_checkbox.isChecked()
161 self._app.project.share_y_axis = self._app.share_y_checkbox.isChecked()
162 self._app._update_plot()
164 def _on_active_axis_changed(self, index):
165 """切り替える前の欄の値を元の軸に保存してから、新しい軸の設定を欄に読み込む。"""
167 if index == -1 or index >= len(self._app.project.all_plot_settings): 167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true
168 return
170 self._app.project.all_plot_settings[self._app.project.active_axis_index] = self._gather_settings_from_ui()
172 self._app.project.active_axis_index = index
174 settings_to_load = self._app.project.all_plot_settings[self._app.project.active_axis_index]
175 self._apply_settings_to_ui_controls(settings_to_load)
176 log_axis_notes.update_log_axis_notes(self._app)
178 def _on_axis_setting_changed(self):
179 current_settings = self._gather_settings_from_ui()
181 self._app.project.all_plot_settings[self._app.project.active_axis_index] = current_settings
183 self._app._update_plot_appearance()
185 def _update_subplot_combos(self):
186 total_plots = len(self._app.project.all_plot_settings)
187 plot_names = [tr("プロット {number}").format(number=i + 1) for i in range(total_plots)]
189 self._app.active_axis_combo.blockSignals(True)
190 self._app.subplot_target_combo.blockSignals(True)
192 self._app.active_axis_combo.clear()
193 self._app.subplot_target_combo.clear()
195 self._app.active_axis_combo.addItems(plot_names)
196 self._app.subplot_target_combo.addItems(plot_names)
198 self._app.active_axis_combo.setCurrentIndex(self._app.project.active_axis_index)
200 # 「描画先」の選択はデータセットを選んだときに property_panel.update_ui_state が決める
201 self._app.active_axis_combo.blockSignals(False)
202 self._app.subplot_target_combo.blockSignals(False)
203 self._app.subplot_target_bar.refresh()
206 def _seed_min_max_spinboxes(self, min_spinbox, max_spinbox, limits):
207 """オートスケールを切った瞬間に、いま表示している範囲を最小値・最大値の欄に入れる。
209 欄が初期値 0/0 のままだと、最小値を先に変えたとき「最小 >= 最大」で反映されない。
210 """
211 if limits is None: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true
212 return
213 min_lim, max_lim = limits
214 min_spinbox.blockSignals(True)
215 max_spinbox.blockSignals(True)
216 min_spinbox.setValue(min_lim)
217 max_spinbox.setValue(max_lim)
218 min_spinbox.blockSignals(False)
219 max_spinbox.blockSignals(False)
221 def _current_active_axis(self):
222 axis_index = self._app.project.active_axis_index
223 if 0 <= axis_index < len(self._app.canvas.all_axes):
224 return self._app.canvas.all_axes[axis_index]
225 return None
227 def _refresh_x_autoscale_enabled_state(self):
228 """最小値・最大値の欄の有効/無効だけをオートスケールに合わせる。値は書き換えない。
230 保存した設定を戻すときはこちらを使う。_on_x_autoscale_changed() は表示中の範囲を欄に入れるので、
231 保存されていた範囲が上書きされる。
232 """
233 is_autoscale = self._app.ui.x_autoscale_checkbox.isChecked()
234 self._app.ui.x_min_spinbox.setEnabled(not is_autoscale)
235 self._app.ui.x_max_spinbox.setEnabled(not is_autoscale)
236 return is_autoscale
238 def _refresh_y_autoscale_enabled_state(self):
239 is_autoscale = self._app.ui.y_autoscale_checkbox.isChecked()
240 self._app.ui.y_min_spinbox.setEnabled(not is_autoscale)
241 self._app.ui.y_max_spinbox.setEnabled(not is_autoscale)
242 return is_autoscale
244 def _on_x_autoscale_changed(self):
245 """利用者がチェックを変えたとき(設定を戻すときは _refresh_x_autoscale_enabled_state)。"""
246 is_autoscale = self._refresh_x_autoscale_enabled_state()
248 if not is_autoscale:
249 axis = self._current_active_axis()
250 self._seed_min_max_spinboxes(
251 self._app.ui.x_min_spinbox, self._app.ui.x_max_spinbox, axis.get_xlim() if axis is not None else None)
253 # 欄の値を書き換えたので、描き直すだけでなく設定も集め直す
254 self._on_axis_setting_changed()
256 def _on_y_autoscale_changed(self):
257 is_autoscale = self._refresh_y_autoscale_enabled_state()
259 if not is_autoscale:
260 axis = self._current_active_axis()
261 self._seed_min_max_spinboxes(
262 self._app.ui.y_min_spinbox, self._app.ui.y_max_spinbox, axis.get_ylim() if axis is not None else None)
264 self._on_axis_setting_changed()
266 def apply_format_to_all_subplots(self):
267 """今のサブプロットのラベル/書式(AXIS_FORMAT_KEYS)を、ほかの全サブプロットに写す。軸の設定は Undo できないので確かめる。"""
268 settings_list = self._app.project.all_plot_settings
269 active = self._app.project.active_axis_index
270 others = [index for index in range(len(settings_list)) if index != active]
271 if not others: 271 ↛ 272line 271 didn't jump to line 272 because the condition on line 271 was never true
272 return
273 answer = notify.question(
274 self._app, tr("書式を全サブプロットに適用"),
275 tr("プロット {number} の書式(フォント・目盛・グリッド・外枠・カラーバー)を、"
276 "ほかの {count} 個のサブプロットに写します。元に戻せません。").format(number=active + 1, count=len(others)),
277 QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
278 if answer != QMessageBox.StandardButton.Ok: 278 ↛ 279line 278 didn't jump to line 279 because the condition on line 278 was never true
279 return
280 current = self._gather_settings_from_ui()
281 settings_list[active] = current
282 for index in others:
283 for key in AXIS_FORMAT_KEYS:
284 if key in current: 284 ↛ 283line 284 didn't jump to line 283 because the condition on line 284 was always true
285 settings_list[index][key] = copy.deepcopy(current[key])
286 self._app._update_plot_appearance()
287 self._app.statusBar().showMessage(
288 tr("書式を {count} 個のサブプロットに適用しました").format(count=len(others)), 3000)
290 def fill_range_from_view(self, axis_key):
291 """表示中の範囲(マウスで拡大・移動した範囲も)を最小値・最大値の欄に入れ、自動スケールを切る。axis_key は 'x' / 'y' / 'y2'。"""
292 app = self._app
293 axis_index = app.project.active_axis_index
294 if axis_key == 'y2':
295 secondary_axes = getattr(app.canvas, 'all_secondary_axes', [])
296 target = secondary_axes[axis_index] if 0 <= axis_index < len(secondary_axes) else None
297 autoscale, min_spinbox, max_spinbox = app.y2_autoscale_checkbox, app.y2_min_spinbox, app.y2_max_spinbox
298 else:
299 target = self._current_active_axis()
300 ui = app.ui
301 autoscale = getattr(ui, f'{axis_key}_autoscale_checkbox')
302 min_spinbox, max_spinbox = getattr(ui, f'{axis_key}_min_spinbox'), getattr(ui, f'{axis_key}_max_spinbox')
303 if target is None: 303 ↛ 304line 303 didn't jump to line 304 because the condition on line 303 was never true
304 return
305 # 反転した軸は get_xlim が (大, 小) を返す。欄には小さい方を最小値に入れる(向きは「軸を反転」が決める)
306 low, high = sorted(target.get_xlim() if axis_key == 'x' else target.get_ylim())
307 if axis_key == 'x':
308 # ウォーターフォールで X をずらしていると、描くときに手動の範囲をその分広げるので、広げる前の範囲に戻す
309 left, right = waterfall_x_shift(app.canvas, axis_index)
310 low, high = low - left, high - right
311 blocked = autoscale.blockSignals(True)
312 autoscale.setChecked(False)
313 autoscale.blockSignals(blocked)
314 if axis_key == 'y2':
315 self._refresh_y2_axis_state()
316 else:
317 getattr(self, f'_refresh_{axis_key}_autoscale_enabled_state')()
318 self._seed_min_max_spinboxes(min_spinbox, max_spinbox, (low, high))
319 self._on_axis_setting_changed()
321 def _on_x_tick_mode_changed(self):
322 self._refresh_x_tick_mode_state()
323 self._app._update_plot_appearance()
325 def _refresh_x_tick_mode_state(self):
326 is_fixed_interval = (self._app.ui.x_major_tick_mode_combo.currentIndex() == 1)
327 self._app.ui.x_major_tick_interval_spinbox.setEnabled(is_fixed_interval)
329 def _on_y_tick_mode_changed(self):
330 self._refresh_y_tick_mode_state()
331 self._app._update_plot_appearance()
333 def _refresh_y_tick_mode_state(self):
334 is_fixed_interval = (self._app.ui.y_major_tick_mode_combo.currentIndex() == 1)
335 self._app.ui.y_major_tick_interval_spinbox.setEnabled(is_fixed_interval)
337 def _on_x_minor_tick_visibility_changed(self):
338 """補助目盛の表示と対数表示の両方に依存するので、同じスロットで受ける。"""
339 self._refresh_x_minor_tick_state()
340 self._app._update_plot_appearance()
342 def _refresh_x_minor_tick_state(self):
343 is_visible = self._app.ui.x_minor_ticks_visible_checkbox.isChecked()
344 is_log = self._app.ui.x_log_checkbox.isChecked()
345 # 対数軸は MultipleLocator ではなく LogLocator なので間隔は使わない
346 self._app.ui.x_minor_tick_interval_spinbox.setEnabled(is_visible and not is_log)
347 self._app.x_log_minor_subs_label.setVisible(is_log)
348 self._app.x_log_minor_subs_combo.setVisible(is_log)
349 self._app.x_log_minor_labels_checkbox.setVisible(is_log)
350 self._app.x_log_minor_subs_combo.setEnabled(is_log and is_visible)
351 self._app.x_log_minor_labels_checkbox.setEnabled(is_log and is_visible)
353 def _on_y_minor_tick_visibility_changed(self):
354 self._refresh_y_minor_tick_state()
355 self._app._update_plot_appearance()
357 def _refresh_y_minor_tick_state(self):
358 is_visible = self._app.ui.y_minor_ticks_visible_checkbox.isChecked()
359 is_log = self._app.ui.y_log_checkbox.isChecked()
360 self._app.ui.y_minor_tick_interval_spinbox.setEnabled(is_visible and not is_log)
361 self._app.y_log_minor_subs_label.setVisible(is_log)
362 self._app.y_log_minor_subs_combo.setVisible(is_log)
363 self._app.y_log_minor_labels_checkbox.setVisible(is_log)
364 self._app.y_log_minor_subs_combo.setEnabled(is_log and is_visible)
365 self._app.y_log_minor_labels_checkbox.setEnabled(is_log and is_visible)
367 def _refresh_y2_axis_state(self):
368 """第 2 Y 軸の欄の有効/無効を、自動スケール・目盛りの方式・補助目盛り・対数に合わせる。値は書き換えない。"""
369 app = self._app
370 is_autoscale = app.y2_autoscale_checkbox.isChecked()
371 app.y2_min_spinbox.setEnabled(not is_autoscale)
372 app.y2_max_spinbox.setEnabled(not is_autoscale)
373 app.y2_major_tick_interval_spinbox.setEnabled(app.y2_major_tick_mode_combo.currentIndex() == 1)
374 # 対数軸の補助目盛りは間隔ではなく対数の刻みで打つ
375 app.y2_minor_tick_interval_spinbox.setEnabled(
376 app.y2_minor_ticks_visible_checkbox.isChecked() and not app.y2_log_checkbox.isChecked())
378 def _on_y2_axis_state_changed(self):
379 self._refresh_y2_axis_state()
381 def _on_y2_autoscale_changed(self):
382 """自動スケールを切った瞬間に、いまの第 2 Y 軸の範囲を最小値・最大値の欄に入れる(主の Y 軸と同じ)。"""
383 self._refresh_y2_axis_state()
384 if not self._app.y2_autoscale_checkbox.isChecked(): 384 ↛ 390line 384 didn't jump to line 390 because the condition on line 384 was always true
385 axis_index = self._app.project.active_axis_index
386 secondary_axes = getattr(self._app.canvas, 'all_secondary_axes', [])
387 secondary = secondary_axes[axis_index] if 0 <= axis_index < len(secondary_axes) else None
388 self._seed_min_max_spinboxes(self._app.y2_min_spinbox, self._app.y2_max_spinbox,
389 secondary.get_ylim() if secondary is not None else None)
390 self._on_axis_setting_changed()
392 def _on_legend_visibility_changed(self):
393 self._refresh_legend_state()
394 self._app._update_plot_appearance()
396 def _refresh_legend_state(self):
397 is_visible = self._app.ui.legend_visible_checkbox.isChecked()
399 self._app.legend_loc_label.setEnabled(is_visible)
400 self._app.legend_loc_combo.setEnabled(is_visible)
401 for widget in (self._app.legend_columns_label, self._app.legend_columns_spinbox, self._app.legend_frame_checkbox):
402 widget.setEnabled(is_visible)
403 self._app.legend_font_label.setEnabled(is_visible)
404 self._app.legend_font_button.setEnabled(is_visible)
405 self._app.legend_color_label.setEnabled(is_visible)
406 self._app.legend_color_button.setEnabled(is_visible)
408 def _grid_linestyle_code(self, combo_index: int) -> str:
409 choices = self._app.grid_linestyle_choices
410 if 0 <= combo_index < len(choices): 410 ↛ 412line 410 didn't jump to line 412 because the condition on line 410 was always true
411 return choices[combo_index][1]
412 return '-'
414 def _grid_linestyle_index(self, linestyle_code: str) -> int:
415 """未知の値は 0(実線)。"""
416 for i, (_label, code) in enumerate(self._app.grid_linestyle_choices): 416 ↛ 419line 416 didn't jump to line 419 because the loop on line 416 didn't complete
417 if code == linestyle_code:
418 return i
419 return 0
421 def _on_grid_visibility_changed(self):
422 self._refresh_grid_state()
423 self._app._update_plot_appearance()
425 def _refresh_grid_state(self):
426 is_visible = self._app.ui.grid_visible_checkbox.isChecked()
428 sections = getattr(self._app, '_axis_sections', None)
429 grid_form = sections['grid']['form'] if sections is not None else None
430 self._app.ui.minor_grid_visible_checkbox.setEnabled(is_visible)
431 if grid_form is not None: 431 ↛ 436line 431 didn't jump to line 436 because the condition on line 431 was always true
432 grid_form.setRowVisible(self._app.ui.minor_grid_visible_checkbox, is_visible)
434 # 主のグリッドの欄はグリッドの表示に、補助の欄はさらに補助グリッドの表示にも従う。
435 # 使わない欄は灰色で並べず隠す(名前も一緒に)
436 is_minor_visible = is_visible and self._app.ui.minor_grid_visible_checkbox.isChecked()
437 for prefix, shown in (("x_major", is_visible), ("y_major", is_visible),
438 ("x_minor", is_minor_visible), ("y_minor", is_minor_visible)):
439 for suffix in ("grid_linestyle_combo", "grid_linestyle_segments", "grid_width_spinbox", "grid_alpha_spinbox"):
440 getattr(self._app, f"{prefix}_{suffix}").setEnabled(shown)
441 if grid_form is not None: 441 ↛ 437line 441 didn't jump to line 437 because the condition on line 441 was always true
442 grid_form.setRowVisible(getattr(self._app, f"{prefix}_grid_style_label"), shown)
445 def _warn_if_font_family_unavailable_for_graph(self, font):
446 """グラフのフォントが matplotlib で見つからなければ知らせる(選択は保存する)。
448 QFontDialog は OS のフォント一覧を出すが、matplotlib は別の一覧で探し、見つからないと黙って既定のフォントになる。
449 """
450 family = font.family()
451 _resolved_name, _stretch, resolved = _resolve_font_family_for_matplotlib(family)
452 if not resolved:
453 notify.warning(
454 self._app, "フォントが見つかりません",
455 f"フォント「{family}」はグラフの描画エンジン(matplotlib)には認識されず、"
456 "代わりに既定のフォントで表示されます。\n\n"
457 "OS側のフォント一覧には表示されていても、グラフの描画には使えない"
458 "フォントがあります。別のフォントをお試しください。"
459 )
461 def _ask_font(self, initial):
462 """フォントを選ばせる。(選んだか, フォント)。
464 どの OS でも Qt のダイアログを使う。macOS の OS のフォントパネルは、選んだフォントを Qt へ通知(changeFont:)で
465 渡すが、それが届かないと OK でも最初のフォントのまま返り、選んでも反映されない。
466 """
467 return QFontDialog.getFont(initial, self._app, "", QFontDialog.FontDialogOption.DontUseNativeDialog)
469 def _on_change_tick_font(self):
470 ok, font = self._ask_font(self._app._tick_font)
471 if ok:
472 self._warn_if_font_family_unavailable_for_graph(font)
473 self._app._tick_font = font
474 self._on_axis_setting_changed()
476 def _on_change_tick_color(self):
477 color = get_color_with_history(self._app.settings, self._app)
478 if color.isValid():
479 self._app._tick_color = color.name()
480 self._on_axis_setting_changed()
482 def _on_change_axis_label_font(self):
483 ok, font = self._ask_font(self._app._axis_label_font)
484 if ok:
485 self._warn_if_font_family_unavailable_for_graph(font)
486 self._app._axis_label_font = font
487 # _update_plot_appearance() だけでは all_plot_settings に保存されない
488 self._on_axis_setting_changed()
490 def _on_change_axis_label_color(self):
491 color = get_color_with_history(self._app.settings, self._app)
492 if color.isValid():
493 self._app._axis_label_color = color.name()
494 self._on_axis_setting_changed()
496 def _on_change_legend_font(self):
497 ok, font = self._ask_font(self._app._legend_font)
498 if ok:
499 self._warn_if_font_family_unavailable_for_graph(font)
500 self._app._legend_font = font
501 self._on_axis_setting_changed()
503 def _on_change_legend_color(self):
504 color = get_color_with_history(self._app.settings, self._app)
505 if color.isValid():
506 self._app._legend_color = color.name()
507 self._on_axis_setting_changed()
509 def _on_change_spine_color(self):
510 color = get_color_with_history(self._app.settings, self._app)
511 if color.isValid():
512 self._app._spine_color = color.name()
513 self._on_axis_setting_changed()
515 def _open_label_edit_dialog(self, line_edit, dialog_title):
516 """編集ダイアログの結果を line_edit に setText() する(textChanged からいつもの経路で反映される)。
518 LABEL_SYMBOL_PALETTE は main_window がこの mixin を import しているので、ここで遅れて import する。
519 """
520 from graphica.gui.main_window import LABEL_SYMBOL_PALETTE
522 dialog = LabelEditDialog(line_edit.text(), dialog_title, LABEL_SYMBOL_PALETTE, parent=self._app)
523 if dialog.exec() == QDialog.DialogCode.Accepted:
524 line_edit.setText(dialog.get_text())
526 def _refresh_label_preview(self, preview_label, text, placeholder):
527 """プレビューを matplotlib で描いた見た目にする。空なら placeholder を文字で出す。"""
528 from graphica.gui.mathtext_preview import render_mathtext_to_pixmap
530 if not text:
531 preview_label.set_placeholder_text(placeholder)
532 return
533 pixmap = render_mathtext_to_pixmap(text, color=theme.current_tokens()["text_primary"])
534 # 欄の幅が決まるたびに収まるよう縮める(setPixmap だと、この時点の幅がまだ確定していないとはみ出す)
535 preview_label.set_natural_pixmap(pixmap)
537 def _refresh_all_label_previews(self):
538 """文字色がテーマに従うので、ダークモードの切り替えで描き直す。"""
539 for preview_label, line_edit, placeholder in self._app._label_preview_widgets:
540 self._refresh_label_preview(preview_label, line_edit.text(), placeholder)
542 def _on_legend_loc_changed(self, *_args):
543 """ドラッグした位置(legend_position)が残っていると選んだ位置が効かないので消す。"""
544 axis_index = self._app.project.active_axis_index
545 if axis_index < len(self._app.project.all_plot_settings): 545 ↛ 547line 545 didn't jump to line 547 because the condition on line 545 was always true
546 self._app.project.all_plot_settings[axis_index].pop('legend_position', None)
547 self._on_axis_setting_changed()
549 def _on_legend_drag_release(self, _event):
550 """凡例のドラッグは matplotlib 側の button_release_event で確定し、こちらが先に呼ばれうるので、処理の後で読む。"""
551 QTimer.singleShot(0, self._app, self._store_dragged_legend_positions)
553 def _store_dragged_legend_positions(self):
554 """凡例がドラッグで置かれていれば、その位置を legend_position に保存する(しないと次の描画で戻る)。どれか変えたら True。"""
555 changed = False
556 settings_list = self._app.project.all_plot_settings
557 secondary_axes = getattr(self._app.canvas, 'all_secondary_axes', [])
558 for index, ax in enumerate(getattr(self._app.canvas, 'all_axes', [])):
559 if index >= len(settings_list): 559 ↛ 560line 559 didn't jump to line 560 because the condition on line 559 was never true
560 break
561 legend = ax.get_legend()
562 if legend is None and index < len(secondary_axes) and secondary_axes[index] is not None: 562 ↛ 563line 562 didn't jump to line 563 because the condition on line 562 was never true
563 legend = secondary_axes[index].get_legend()
564 loc = getattr(legend, '_loc', None) if legend is not None else None
565 if not isinstance(loc, tuple) or len(loc) != 2:
566 continue
567 position = [round(float(loc[0]), 4), round(float(loc[1]), 4)]
568 if axis_setting(settings_list[index], 'legend_position') != position: 568 ↛ 558line 568 didn't jump to line 558 because the condition on line 568 was always true
569 settings_list[index]['legend_position'] = position
570 changed = True
571 return changed
573 def _on_edit_legend_order(self):
574 """今の軸の凡例の並びをダイアログで決め、legend_order に保存する。"""
575 axis_index = self._app.project.active_axis_index
576 if axis_index >= len(self._app.canvas.all_axes):
577 return
578 ax = self._app.canvas.all_axes[axis_index]
579 _, labels = ax.get_legend_handles_labels()
580 if axis_index < len(self._app.canvas.all_secondary_axes) and self._app.canvas.all_secondary_axes[axis_index] is not None:
581 _, secondary_labels = self._app.canvas.all_secondary_axes[axis_index].get_legend_handles_labels()
582 labels = labels + secondary_labels
583 if not labels:
584 notify.information(self._app, "凡例の順序", "この軸には凡例に表示するデータセットがありません。")
585 return
587 current_order = axis_setting(self._app.project.all_plot_settings[axis_index], 'legend_order') or []
588 dialog = LegendOrderDialog(_order_labels(labels, current_order), self._app)
589 if dialog.exec() != QDialog.DialogCode.Accepted:
590 return
591 self._app.project.all_plot_settings[axis_index]['legend_order'] = dialog.get_order()
592 self._app._update_plot()
594 def _font_props_to_dict(self, qfont: QFont) -> dict:
595 """QFont を JSON に保存できる辞書にする。
597 'family' は families() の候補リストのまま保存する(.family() の先頭1つにすると、macOS に無い
598 "Yu Gothic" だけが残って日本語が化ける)。各候補は _resolve_font_family_for_matplotlib で解決する。
599 """
600 resolved_families = []
601 stretch = None
602 for name in qfont.families():
603 resolved_name, resolved_stretch, _ok = _resolve_font_family_for_matplotlib(name)
604 resolved_families.append(resolved_name)
605 if stretch is None and resolved_stretch is not None:
606 stretch = resolved_stretch
608 result = {
609 'family': resolved_families,
610 'size': qfont.pointSize(),
611 'weight': 'bold' if qfont.bold() else 'normal',
612 'style': 'italic' if qfont.italic() else 'normal'
613 }
614 if stretch is not None:
615 result['stretch'] = stretch
616 return result
618 def _gather_settings_from_ui(self) -> dict:
619 """今の軸の設定を、画面の欄から集めた辞書(保存形式そのもの)で返す。キーは AXIS_SETTING_DEFAULTS と同じ順。"""
620 values = self._app._axis_binder.gather()
621 # 欄を持たず操作から直接書き込まれるもの。辞書は丸ごと入れ替わるので、引き継がないと消える。
622 settings_list = self._app.project.all_plot_settings
623 current = settings_list[self._app.project.active_axis_index] if self._app.project.active_axis_index < len(settings_list) else {}
624 for key in CARRIED_AXIS_KEYS:
625 values[key] = axis_setting(current, key)
626 return {key: values[key] for key in AXIS_SETTING_DEFAULTS}
628 def _apply_settings_to_ui_controls(self, settings: dict):
629 """設定の辞書を画面の欄に戻す。無いキーは AXIS_SETTING_DEFAULTS の既定値になる。"""
630 try:
631 # 欄に値を入れる間は、変更の通知で設定を書き換えないようにする
632 self._block_all_signals(True)
634 self._app._axis_binder.restore(settings, axis_setting)
635 refresh_axis_format_widgets(self._app)
637 # 復元では _on_x_autoscale_changed(今の表示範囲を欄に入れる)を呼ばない。
638 # 呼ぶと、オートスケールを切って保存した範囲が今の表示範囲で上書きされる。
639 self._refresh_x_autoscale_enabled_state()
640 self._refresh_y_autoscale_enabled_state()
641 self._refresh_x_tick_mode_state()
642 self._refresh_y_tick_mode_state()
643 self._refresh_x_minor_tick_state()
644 self._refresh_y_minor_tick_state()
645 self._refresh_legend_state()
646 self._refresh_grid_state()
647 self._refresh_y2_axis_state()
648 # 欄の状態をそろえてから 1 回だけ描く(どれも同じ設定で描くので、欄ごとに描いても結果は同じ)
649 self._app._update_plot_appearance()
651 except Exception as e:
652 notify.warning(self._app, "設定適用エラー", f"設定の適用中にエラーが発生しました:\n{e}")
653 logger.exception("設定の適用中にエラー")
654 finally:
655 # 途中で失敗しても必ず戻す
656 self._block_all_signals(False)
658 def _block_all_signals(self, block: bool):
659 self._app._axis_binder.block_signals(block)
661 def _connect_layout_signals(self):
662 self._app.subplot_rows_spinbox.valueChanged.connect(self._on_layout_changed)
663 self._app.subplot_cols_spinbox.valueChanged.connect(self._on_layout_changed)
665 self._app.share_x_checkbox.toggled.connect(self._on_share_axis_changed)
666 self._app.share_y_checkbox.toggled.connect(self._on_share_axis_changed)
668 self._app.active_axis_combo.currentIndexChanged.connect(self._on_active_axis_changed)
670 self._app.free_layout_checkbox.toggled.connect(self._app._on_toggle_free_layout)
671 self._app.add_free_subplot_button.clicked.connect(self._app._on_add_free_subplot)
672 self._app.remove_free_subplot_button.clicked.connect(self._app._on_remove_free_subplot)
674 self._app.free_layout_x_spinbox.valueChanged.connect(self._app._on_free_layout_position_spinbox_changed)
675 self._app.free_layout_y_spinbox.valueChanged.connect(self._app._on_free_layout_position_spinbox_changed)
676 self._app.free_layout_width_spinbox.valueChanged.connect(self._app._on_free_layout_position_spinbox_changed)
677 self._app.free_layout_height_spinbox.valueChanged.connect(self._app._on_free_layout_position_spinbox_changed)
679 def _connect_axis_setting_signals(self):
680 # 値を持つ欄は表(gui/axis_bindings.py)の順につなぐ。タイトルと軸ラベルの編集ボタンは _build_label_editors でつなぐ
681 self._app._axis_binder.connect()
683 self._app.ui.tick_font_button.clicked.connect(self._on_change_tick_font)
684 self._app.ui.tick_color_button.clicked.connect(self._on_change_tick_color)
685 self._app.ui.axis_label_font_button.clicked.connect(self._on_change_axis_label_font)
686 self._app.ui.axis_label_color_button.clicked.connect(self._on_change_axis_label_color)
687 self._app.legend_font_button.clicked.connect(self._on_change_legend_font)
688 self._app.legend_color_button.clicked.connect(self._on_change_legend_color)
689 self._app.legend_order_button.clicked.connect(self._on_edit_legend_order)
690 self._app.ui.spine_color_button.clicked.connect(self._on_change_spine_color)