Coverage for graphica/gui/mixins/project_io_mixin.py: 93.7%

227 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-25 19:22 +0000

1"""プロジェクトの保存と読み込みのメニュー、書式テンプレート、環境設定、設定の書き出しと読み込み。""" 

2import json 

3import logging 

4 

5from graphica.gui import notify 

6from graphica.gui import motion 

7from graphica.gui import dialog_dirs 

8from graphica.gui import app_settings 

9from graphica.gui import theme 

10from graphica.gui.builders import canvas_area 

11from graphica.gui.theme_color import normalize_hex 

12from graphica.gui.dialogs import PreferencesDialog 

13from graphica.gui.datasets.operations.transfer import STYLE_ATTRS 

14from graphica.core.i18n import tr, get_language 

15 

16logger = logging.getLogger(__name__) 

17 

18AUTOSAVE_INTERVAL_MIN_BOUNDS = (0, 180) 

19 

20TEMPLATE_FORMAT_VERSION = 1 

21 

22# 書き出すキーは app_settings.EXPORTED_SETTINGS。ウィンドウの状態や最近使ったファイルなど、 

23# その環境だけの項目は入れない(別の PC に持ち込んでも意味が無いか害になる) 

24SETTINGS_EXPORT_FORMAT_VERSION = 1 

25 

26# サブプロットの中身に近いもの。テンプレートでは保存も適用もしない(適用先の値を残す) 

27TEMPLATE_EXCLUDED_AXIS_SETTING_KEYS = ('annotations', 'legend_order', 'free_rect') 

28 

29 

30def read_style_template(file_path): 

31 """書式テンプレートのファイルを読む。""" 

32 with open(file_path, 'r', encoding='utf-8') as f: 

33 return json.load(f) 

34 

35 

36def _apply_dataset_style(dataset, style): 

37 for attr, value in style.items(): 

38 setattr(dataset, attr, value) 

39 

40 

41class ProjectIOMixin: 

42 def _on_save_project(self): 

43 self.manual_save() 

44 

45 def _on_save_project_as(self): 

46 self.manual_save_as() 

47 

48 def _on_load_project(self): 

49 self.manual_load() 

50 

51 def _on_configure_autosave_interval(self): 

52 """0 分で無効。""" 

53 current_minutes = (self.autosave_timer.interval() // 60000) if self.autosave_timer.isActive() else 0 

54 min_minutes, max_minutes = AUTOSAVE_INTERVAL_MIN_BOUNDS 

55 minutes, ok = notify.get_int( 

56 self, "オートセーブ間隔の設定", 

57 "オートセーブの間隔を分単位で入力してください (0で無効化):", 

58 current_minutes, min_minutes, max_minutes 

59 ) 

60 if not ok: 

61 return 

62 

63 self._apply_autosave_interval(minutes) 

64 

65 def _apply_autosave_interval(self, minutes): 

66 """メニューと環境設定の両方から呼ばれる。""" 

67 app_settings.AUTOSAVE_INTERVAL_MIN.write(self.settings, minutes) 

68 if minutes <= 0: 

69 self.autosave_timer.stop() 

70 self.statusBar().showMessage("オートセーブを無効化しました", 3000) 

71 else: 

72 self.autosave_timer.start(minutes * 60 * 1000) 

73 self.statusBar().showMessage(f"オートセーブ間隔を{minutes}分に設定しました", 3000) 

74 

75 self._update_autosave_menu_text() 

76 canvas_area.refresh_status_bar(self) 

77 

78 def _on_show_preferences(self): 

79 current_minutes = (self.autosave_timer.interval() // 60000) if self.autosave_timer.isActive() else 0 

80 # 言語だけは、未設定なら今の表示言語を既定にする 

81 current_language = app_settings.LANGUAGE.read(self.settings, default=get_language()) 

82 current_autosave_dir = app_settings.AUTOSAVE_DIR.read(self.settings) 

83 current_point_label_max = app_settings.POINT_LABEL_MAX_POINTS.read(self.settings) 

84 current_snap_to_grid = app_settings.SNAP_TO_GRID_ENABLED.read(self.settings) 

85 current_snap_grid_interval = app_settings.SNAP_GRID_INTERVAL_PX.read(self.settings) 

86 

87 # main_window がこの mixin を import しているので、関数の中で import する 

88 from graphica.core.plugin_api import get_loaded_plugin_records, get_plugin_registration_errors 

89 current_disabled_plugin_names = app_settings.disabled_plugin_names(self.settings) 

90 

91 current_default_template = app_settings.DEFAULT_STYLE_TEMPLATE.read(self.settings) 

92 current_wheel_zoom_speed = app_settings.WHEEL_ZOOM_SPEED.read(self.settings) 

93 dlg = PreferencesDialog( 

94 self.canvas.dark_mode, current_minutes, 

95 autosave_bounds=AUTOSAVE_INTERVAL_MIN_BOUNDS, parent=self, 

96 current_language=current_language, autosave_dir=current_autosave_dir, 

97 point_label_max_points=current_point_label_max, 

98 snap_to_grid_enabled=current_snap_to_grid, 

99 snap_grid_interval_px=current_snap_grid_interval, 

100 plugin_records=get_loaded_plugin_records(), 

101 plugin_registration_errors=get_plugin_registration_errors(), 

102 disabled_plugin_names=current_disabled_plugin_names, 

103 default_style_template=current_default_template, 

104 wheel_zoom_speed=current_wheel_zoom_speed, 

105 theme_color=theme.current_theme_color(), 

106 on_check_plugin_updates=self._on_check_plugin_updates, 

107 animations=app_settings.ANIMATIONS.read(self.settings), 

108 ) 

109 if dlg.exec() != PreferencesDialog.DialogCode.Accepted: 

110 return 

111 

112 (new_dark_mode, new_autosave_minutes, new_language, 

113 new_autosave_dir, new_point_label_max, 

114 new_snap_to_grid, new_snap_grid_interval) = dlg.get_settings() 

115 

116 # 次の起動から効く(読み込んだプラグインをその場で入れ替える仕組みは無い) 

117 new_disabled_plugin_names = dlg.get_disabled_plugin_names() 

118 if new_disabled_plugin_names != current_disabled_plugin_names: 

119 app_settings.DISABLED_PLUGINS.write(self.settings, list(new_disabled_plugin_names)) 

120 

121 if new_autosave_dir != current_autosave_dir: 

122 app_settings.AUTOSAVE_DIR.write(self.settings, new_autosave_dir) 

123 self._update_autosave_path() 

124 

125 # 次に作るタブ・プロジェクトから効く(開いているタブの見た目は変えない) 

126 new_default_template = dlg.get_default_style_template() 

127 if new_default_template != current_default_template: 

128 app_settings.DEFAULT_STYLE_TEMPLATE.write(self.settings, new_default_template) 

129 

130 # どのタブもホイールのたびに設定を読むので、書くだけで全部のタブに効く 

131 new_wheel_zoom_speed = dlg.get_wheel_zoom_speed() 

132 if new_wheel_zoom_speed != current_wheel_zoom_speed: 132 ↛ 133line 132 didn't jump to line 133 because the condition on line 132 was never true

133 app_settings.WHEEL_ZOOM_SPEED.write(self.settings, new_wheel_zoom_speed) 

134 

135 # 動きは開いている全部のタブに同時に効く(gui/motion.py の1つの切り替え) 

136 new_animations = dlg.get_animations() 

137 if new_animations != app_settings.ANIMATIONS.read(self.settings): 137 ↛ 138line 137 didn't jump to line 138 because the condition on line 137 was never true

138 app_settings.ANIMATIONS.write(self.settings, new_animations) 

139 motion.set_enabled(new_animations) 

140 

141 new_theme_color = dlg.get_theme_color() 

142 if new_theme_color != normalize_hex(theme.current_theme_color()): 

143 self.set_theme_color(new_theme_color) 

144 

145 # 表示メニューのチェック経由で切り替える(toggled から _on_toggle_dark_mode が適用し、チェックの状態も揃う) 

146 if new_dark_mode != self.canvas.dark_mode: 

147 self.dark_mode_action.setChecked(new_dark_mode) 

148 

149 if new_autosave_minutes != current_minutes: 149 ↛ 152line 149 didn't jump to line 152 because the condition on line 149 was always true

150 self._apply_autosave_interval(new_autosave_minutes) 

151 

152 if new_point_label_max != current_point_label_max: 

153 app_settings.POINT_LABEL_MAX_POINTS.write(self.settings, new_point_label_max) 

154 self.canvas.point_label_max_points = new_point_label_max 

155 self._update_plot() 

156 self.property_panel.update_point_labels_limit_note() 

157 

158 if new_snap_to_grid != current_snap_to_grid: 

159 app_settings.SNAP_TO_GRID_ENABLED.write(self.settings, new_snap_to_grid) 

160 self.snap_to_grid_enabled = new_snap_to_grid 

161 if new_snap_grid_interval != current_snap_grid_interval: 

162 app_settings.SNAP_GRID_INTERVAL_PX.write(self.settings, new_snap_grid_interval) 

163 self.snap_grid_interval_px = new_snap_grid_interval 

164 

165 # 作った画面をその場で訳し直す仕組みは無いので、次の起動からと知らせる 

166 if new_language != current_language: 

167 app_settings.LANGUAGE.write(self.settings, new_language) 

168 notify.information( 

169 self, tr("表示言語の変更"), 

170 tr("表示言語の変更は、次回起動時に反映されます。") 

171 ) 

172 

173 def _update_autosave_menu_text(self): 

174 if not self.autosave_timer.isActive(): 

175 self.autosave_interval_action.setText(tr("オートセーブ: 無効(&I)...")) 

176 else: 

177 minutes = self.autosave_timer.interval() // 60000 

178 self.autosave_interval_action.setText(tr("オートセーブ: {minutes}分間隔(&I)...").format(minutes=minutes)) 

179 

180 def _on_save_plot_template(self): 

181 """全サブプロットの見た目と全データセットのスタイルを *.graphica-style に保存する(データは含めない)。""" 

182 file_path, _ = dialog_dirs.get_save_file_name( 

183 self, dialog_dirs.TEMPLATE, "書式テンプレートを保存", "", "Graphica Style Template (*.graphica-style)" 

184 ) 

185 if not file_path: 

186 return 

187 if not (file_path.endswith('.graphica-style') or file_path.endswith('.json')): 187 ↛ 188line 187 didn't jump to line 188 because the condition on line 187 was never true

188 file_path += '.graphica-style' 

189 

190 # 今の軸の欄の値はまだ all_plot_settings に入っていない 

191 if self.project.active_axis_index < len(self.project.all_plot_settings): 191 ↛ 194line 191 didn't jump to line 194 because the condition on line 191 was always true

192 self.project.all_plot_settings[self.project.active_axis_index] = self._gather_settings_from_ui() 

193 

194 subplot_styles = [ 

195 {k: v for k, v in settings.items() if k not in TEMPLATE_EXCLUDED_AXIS_SETTING_KEYS} 

196 for settings in self.project.all_plot_settings 

197 ] 

198 dataset_styles = [ 

199 {attr: getattr(ds, attr) for attr in STYLE_ATTRS} 

200 for ds in self.project.datasets 

201 ] 

202 

203 template_data = { 

204 'format_version': TEMPLATE_FORMAT_VERSION, 

205 'subplot_styles': subplot_styles, 

206 'dataset_styles': dataset_styles, 

207 } 

208 

209 try: 

210 with open(file_path, 'w', encoding='utf-8') as f: 

211 json.dump(template_data, f, indent=4, ensure_ascii=False) 

212 except Exception as e: 

213 notify.warning(self, "保存エラー", f"テンプレートの保存中にエラーが発生しました:\n{e}") 

214 logger.exception("テンプレートの保存中にエラー") 

215 

216 def _on_load_plot_template(self): 

217 """書式テンプレートを今のプロジェクトに当てる。Undo はできない。 

218 

219 新しい形式(format_version あり)は、保存した順にサブプロットとデータセットへ繰り返し当てる(数が違ってもよい)。 

220 古い .json(plot_settings だけ)は今の軸だけに当てる。 

221 """ 

222 file_path, _ = dialog_dirs.get_open_file_name( 

223 self, dialog_dirs.TEMPLATE, "書式テンプレートを適用", "Graphica Style Template (*.graphica-style *.json)" 

224 ) 

225 if not file_path: 

226 return 

227 

228 try: 

229 if not self._apply_plot_template(read_style_template(file_path)): 

230 notify.warning(self, "読込エラー", "有効な書式設定がファイルに含まれていません。") 

231 except Exception as e: 

232 notify.warning(self, "読込エラー", f"テンプレートの読み込み中にエラーが発生しました:\n{e}") 

233 logger.exception("テンプレートの読み込み中にエラー") 

234 

235 def _apply_plot_template(self, template_data): 

236 """書式テンプレートの中身を今のプロジェクトに当てる。有効な書式が無ければ何もせず False。 

237 

238 手動の適用(_on_load_plot_template)と、新しいタブへの既定のテンプレート(_apply_default_style_template)の共通の経路。 

239 """ 

240 if 'format_version' not in template_data: 

241 # 古い形式: 今の軸だけ 

242 settings = template_data.get('plot_settings', {}) 

243 if not settings: 

244 return False 

245 self._apply_settings_to_ui_controls(settings) 

246 self._on_axis_setting_changed() 

247 return True 

248 

249 subplot_styles = template_data.get('subplot_styles') or [] 

250 if not subplot_styles: 

251 return False 

252 

253 for i, settings in enumerate(self.project.all_plot_settings): 

254 style = subplot_styles[i % len(subplot_styles)] 

255 merged = dict(settings) 

256 for k, v in style.items(): 

257 if k not in TEMPLATE_EXCLUDED_AXIS_SETTING_KEYS: 

258 merged[k] = v 

259 self.project.all_plot_settings[i] = merged 

260 if i == self.project.active_axis_index: 

261 self._apply_settings_to_ui_controls(merged) 

262 

263 dataset_styles = template_data.get('dataset_styles') or [] 

264 if dataset_styles: 

265 for i, dataset in enumerate(self.project.datasets): 

266 _apply_dataset_style(dataset, dataset_styles[i % len(dataset_styles)]) 

267 

268 self._update_plot() 

269 return True 

270 

271 def _apply_default_style_template(self): 

272 """環境設定の既定の書式テンプレートを、この新しいタブに当てる。 

273 

274 データセットのスタイルは、このあと読み込むデータセットに順に当てる(_style_imported_dataset)。 

275 ファイルが無いか読めなければ、知らせるだけで何も当てない。 

276 """ 

277 self._default_dataset_styles = [] 

278 self._styled_import_count = 0 

279 file_path = app_settings.DEFAULT_STYLE_TEMPLATE.read(self.settings) 

280 if not file_path: 

281 return 

282 try: 

283 template_data = read_style_template(file_path) 

284 except (OSError, ValueError) as e: 

285 logger.warning("既定の書式テンプレートを読めませんでした: %s (%s)", file_path, e) 

286 self.statusBar().showMessage(tr("既定の書式テンプレートを読めませんでした: {path}").format(path=file_path), 8000) 

287 return 

288 if not self._apply_plot_template(template_data): 288 ↛ 289line 288 didn't jump to line 289 because the condition on line 288 was never true

289 logger.warning("既定の書式テンプレートに有効な書式がありません: %s", file_path) 

290 return 

291 if 'format_version' in template_data: 291 ↛ exitline 291 didn't return from function '_apply_default_style_template' because the condition on line 291 was always true

292 self._default_dataset_styles = list(template_data.get('dataset_styles') or []) 

293 

294 def _style_imported_dataset(self, dataset): 

295 """読み込んだデータセットに、今のパレットの次の色を当て、既定の書式テンプレートがあればそのスタイルを 

296 読み込んだ順に繰り返し当てる(手動の適用と同じ順。テンプレートの色が優先)。""" 

297 # 何もしないと全部同じ既定の色になり、自動配色を押すまで見分けられない 

298 color_cycle = self.colors.active_color_cycle() 

299 if color_cycle: 299 ↛ 301line 299 didn't jump to line 301 because the condition on line 299 was always true

300 dataset.color = color_cycle[len(self.project.datasets) % len(color_cycle)] 

301 styles = getattr(self, '_default_dataset_styles', None) 

302 if not styles: 

303 return 

304 _apply_dataset_style(dataset, styles[self._styled_import_count % len(styles)]) 

305 self._styled_import_count += 1 

306 

307 def _forget_default_style_template(self): 

308 """開いたプロジェクトには、そのプロジェクトの書式があるので、既定のテンプレートはもう当てない。""" 

309 self._default_dataset_styles = [] 

310 

311 def _on_export_settings(self): 

312 """app_settings.EXPORTED_SETTINGS のキーだけを JSON に書き出す(別の PC や研究室での共有用)。""" 

313 file_path, _ = dialog_dirs.get_save_file_name( 

314 self, dialog_dirs.OTHER, "設定・スタイルをエクスポート", "graphica_settings.json", "JSON Files (*.json)" 

315 ) 

316 if not file_path: 

317 return 

318 if not file_path.endswith('.json'): 

319 file_path += '.json' 

320 

321 exported = {setting.key: setting.read_for_export(self.settings) for setting in app_settings.EXPORTED_SETTINGS} 

322 

323 payload = {'format_version': SETTINGS_EXPORT_FORMAT_VERSION, 'settings': exported} 

324 try: 

325 with open(file_path, 'w', encoding='utf-8') as f: 

326 json.dump(payload, f, indent=4, ensure_ascii=False) 

327 notify.information(self, "設定・スタイルをエクスポート", f"エクスポートしました:\n{file_path}") 

328 except Exception as e: 

329 notify.warning(self, "保存エラー", f"設定のエクスポート中にエラーが発生しました:\n{e}") 

330 logger.exception("設定のエクスポート中にエラー") 

331 

332 def _on_import_settings(self): 

333 """書き出した JSON から app_settings.EXPORTED_SETTINGS のキーだけを QSettings に入れる(未知のキーは無視)。 

334 

335 言語・ダークモード・パレットなどをその場で当て直すと影響が広いので、次の起動から効くと知らせる。 

336 """ 

337 file_path, _ = dialog_dirs.get_open_file_name( 

338 self, dialog_dirs.OTHER, "設定・スタイルをインポート", "JSON Files (*.json)" 

339 ) 

340 if not file_path: 

341 return 

342 

343 try: 

344 with open(file_path, 'r', encoding='utf-8') as f: 

345 payload = json.load(f) 

346 except Exception as e: 

347 notify.warning(self, "設定・スタイルをインポート", f"ファイルの読み込みに失敗しました:\n{e}") 

348 logger.exception("設定のインポート中にエラー") 

349 return 

350 

351 data = payload.get('settings') if isinstance(payload, dict) else None 

352 if not isinstance(data, dict): 

353 # 手で書いた設定ファイルも読めるよう、settings キーが無くてもよい 

354 data = payload if isinstance(payload, dict) else None 

355 if not isinstance(data, dict): 355 ↛ 356line 355 didn't jump to line 356 because the condition on line 355 was never true

356 notify.warning(self, "設定・スタイルをインポート", "対応していないファイル形式です。") 

357 return 

358 

359 valid_keys = {setting.key for setting in app_settings.EXPORTED_SETTINGS} 

360 imported_count = 0 

361 for key, value in data.items(): 

362 if key not in valid_keys: 

363 continue 

364 self.settings.setValue(key, value) 

365 imported_count += 1 

366 

367 if imported_count == 0: 

368 notify.information(self, "設定・スタイルをインポート", "インポート対象の設定が見つかりませんでした。") 

369 return 

370 

371 notify.information( 

372 self, "設定・スタイルをインポート", 

373 f"{imported_count}件の設定を反映しました。\n" 

374 "表示言語など一部の設定は、次回起動時に反映されます。" 

375 )