Coverage for graphica/gui/main_app_window.py: 90.8%

218 statements  

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

1"""最上位のウィンドウ。各タブは独立した PlotterApp(QMainWindow)で、Undo もメニューもドックも別々に持つ。 

2 

3アプリ全体で1回だけの処理(オートセーブの復元確認、初回の案内、ドック配置の保存、clean_exit)は最初のタブだけが行う。 

4上部バー(gui/shell/header.py)はここに1つだけ置き、押したときは表示中のタブに届ける。 

5""" 

6import logging 

7import sys 

8 

9from PySide6.QtCore import Qt 

10from PySide6.QtGui import QIcon, QUndoGroup 

11from PySide6.QtWidgets import QApplication, QDockWidget, QMainWindow, QMenu, QUndoView, QVBoxLayout, QWidget 

12 

13from graphica.core.i18n import tr 

14from graphica.gui import app_settings, theme, ui_mode 

15from graphica.gui import motion 

16from graphica.gui.theme_color import theme_color_or_default 

17from graphica.gui.main_window import PlotterApp, resource_path 

18from graphica.gui.shell.header import AppHeader 

19from graphica.gui.shell.project_tabs import ProjectTabs 

20from graphica.core.version import APP_NAME, __version__ 

21from graphica.models.project import LEGACY_PICKLE_EXTENSION, PROJECT_FILE_EXTENSIONS 

22 

23logger = logging.getLogger(__name__) 

24 

25DEFAULT_WINDOW_WIDTH = 1300 

26DEFAULT_WINDOW_HEIGHT = 850 

27 

28 

29class MainAppWindow(QMainWindow): 

30 def __init__(self): 

31 super().__init__() 

32 self.setWindowTitle(f"{APP_NAME} {__version__}") 

33 icon_path = resource_path("Graphica.ico") 

34 self.setWindowIcon(QIcon(icon_path)) 

35 

36 # ウィンドウ全体の大きさと位置はここで持つ 

37 self._settings = app_settings.open_settings() 

38 motion.set_enabled(app_settings.ANIMATIONS.read(self._settings)) 

39 # 最初のタブがスタートアップ画面を見たことにする前に決める(今までの利用者はアドバンスドで始める) 

40 self.ui_mode = ui_mode.initial_mode(self._settings) 

41 

42 # 各タブは自分の QUndoStack を持ち、ここでグループにまとめて、表示中のタブのものを有効にする 

43 # (履歴パネルと上部バーの元に戻す・やり直すは、グループを通して表示中のタブに効く) 

44 self.undo_group = QUndoGroup(self) 

45 self._create_undo_history_dock() 

46 # 履歴パネルはこのウィンドウのドックなので、タブとは別にここでもフォーカスの強調を付ける 

47 theme.install_dock_focus_highlight(self) 

48 

49 self._next_tab_id = 1 

50 self._tab_menus = {} # タブ -> ≡ で開くメニュー(回収されないよう持つ) 

51 

52 self.tab_widget = ProjectTabs() 

53 self.tab_widget.setTabsClosable(True) 

54 self.tab_widget.setMovable(True) 

55 self.tab_widget.tabCloseRequested.connect(self._on_tab_close_requested) 

56 self.tab_widget.currentChanged.connect(self._on_current_tab_changed) 

57 

58 self.header = AppHeader(self.tab_widget.tabBar(), icon_path) 

59 self._connect_header() 

60 

61 central = QWidget() 

62 central_layout = QVBoxLayout(central) 

63 central_layout.setContentsMargins(0, 0, 0, 0) 

64 central_layout.setSpacing(0) 

65 central_layout.addWidget(self.header) 

66 central_layout.addWidget(self.tab_widget, 1) 

67 self.setCentralWidget(central) 

68 

69 saved_geometry = app_settings.WINDOW_GEOMETRY.read(self._settings) 

70 if saved_geometry is not None: 70 ↛ 73line 70 didn't jump to line 73 because the condition on line 70 was never true

71 # 先にネイティブのハンドルを作る。窓が実体化する前に restoreGeometry() すると枠の幅が確定しておらず、 

72 # 画面上の位置の認識がずれて、ポップアップやクリックの位置が全部ずれる 

73 self.winId() 

74 self.restoreGeometry(saved_geometry) 

75 else: 

76 self.resize(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT) 

77 

78 # 最初のタブは起動時の確認をするタブ 

79 self.add_new_project_tab(run_startup_checks=True) 

80 

81 @property 

82 def add_tab_button(self): 

83 return self.header.add_tab_button 

84 

85 def _create_undo_history_dock(self): 

86 """表示中のタブの Undo 履歴(既定では隠す)。""" 

87 self.undo_history_dock = QDockWidget(tr("Undo履歴"), self) 

88 self.undo_history_dock.setObjectName("undo_history_dock") 

89 undo_view = QUndoView(self.undo_group, self.undo_history_dock) 

90 self.undo_history_dock.setWidget(undo_view) 

91 self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.undo_history_dock) 

92 self.undo_history_dock.setVisible(False) 

93 self.undo_history_action = self.undo_history_dock.toggleViewAction() 

94 self.undo_history_action.setText(tr("Undo履歴")) 

95 

96 def _connect_header(self): 

97 header = self.header 

98 header.add_tab_button.clicked.connect(lambda: self.add_new_project_tab()) 

99 self._undo_action = self.undo_group.createUndoAction(self, tr("元に戻す")) 

100 self._redo_action = self.undo_group.createRedoAction(self, tr("やり直し")) 

101 for button, action in ((header.undo_button, self._undo_action), (header.redo_button, self._redo_action)): 

102 icon = button.icon() 

103 button.setDefaultAction(action) 

104 # setDefaultAction() はボタンのアイコンを QAction のもので上書きするので、戻す 

105 action.setIcon(icon) 

106 header.save_button.clicked.connect(lambda: self._trigger_on_current_tab("save_project_action")) 

107 header.export_button.clicked.connect(lambda: self._trigger_on_current_tab("save_action")) 

108 header.search_button.clicked.connect(lambda: self._trigger_on_current_tab("command_palette_action")) 

109 header.quick_access_menu.aboutToShow.connect(self._fill_quick_access_menu) 

110 header.set_mode(self.ui_mode) 

111 header.mode_switch.mode_changed.connect(self.set_ui_mode) 

112 

113 def _fill_quick_access_menu(self): 

114 """★ の一覧: 表示中のタブのピン留め(ピン留めした順)と、管理の項目。""" 

115 menu = self.header.quick_access_menu 

116 menu.clear() 

117 tab = self.tab_widget.currentWidget() 

118 if tab is None: 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true

119 return 

120 pinned = [action for action in tab.quick_access_toolbar.actions() if not action.isSeparator() 

121 and action is not tab.quick_access_manage_action] 

122 for action in pinned: 

123 menu.addAction(action) 

124 if not pinned: 

125 hint = menu.addAction(tr("ピン留めした項目はありません(メニューの項目を右クリックで追加)")) 

126 hint.setEnabled(False) 

127 menu.addSeparator() 

128 menu.addAction(tab.quick_access_manage_action) 

129 

130 def _trigger_on_current_tab(self, action_attr): 

131 tab = self.tab_widget.currentWidget() 

132 action = getattr(tab, action_attr, None) if tab is not None else None 

133 if action is not None: 133 ↛ exitline 133 didn't return from function '_trigger_on_current_tab' because the condition on line 133 was always true

134 action.trigger() 

135 

136 def set_theme_color(self, color): 

137 """テーマカラーを替えて保存し、全部のタブと上部バーに当てる(QSS とパレットはアプリ全体、アイコンや図はタブごと)。""" 

138 color = theme_color_or_default(color) 

139 app_settings.THEME_COLOR.write(self._settings, color) 

140 current = self.tab_widget.currentWidget() 

141 dark = current.canvas.dark_mode if current is not None else app_settings.DARK_MODE.read(self._settings) 

142 theme.apply_theme(QApplication.instance(), dark, color) 

143 for index in range(self.tab_widget.count()): 

144 tab = self.tab_widget.widget(index) 

145 if tab is not None and hasattr(tab, 'refresh_theme_colors'): 145 ↛ 143line 145 didn't jump to line 143 because the condition on line 145 was always true

146 tab.refresh_theme_colors() 

147 self.header.refresh_icons() 

148 

149 def set_ui_mode(self, mode): 

150 """シンプル / アドバンスドを全部のタブに当て、次の起動のために保存する。""" 

151 if mode not in ui_mode.MODES: 151 ↛ 152line 151 didn't jump to line 152 because the condition on line 151 was never true

152 return 

153 self.ui_mode = mode 

154 app_settings.UI_MODE.write(self._settings, mode) 

155 self.header.set_mode(mode) 

156 for index in range(self.tab_widget.count()): 

157 tab = self.tab_widget.widget(index) 

158 if tab is not None: 158 ↛ 156line 158 didn't jump to line 156 because the condition on line 158 was always true

159 ui_mode.apply_ui_mode(tab, mode) 

160 

161 def _attach_tab_chrome(self, project_window): 

162 """タブを上部バーにつなぐ: ≡ のメニュー、ショートカット、クイックアクセス、モード、アイコンの色。""" 

163 menu = QMenu(self.header) 

164 # 最上位のメニューは、組み立て時に持たせた属性から取る(menuBar().actions() から .menu() で辿ると回収されることがある) 

165 for attr in ("_file_menu", "_edit_menu", "_dataset_menu", "_view_menu", "_plugin_menu", "_help_menu"): 

166 top_menu = getattr(project_window, attr, None) 

167 if top_menu is not None: 167 ↛ 165line 167 didn't jump to line 165 because the condition on line 167 was always true

168 menu.addMenu(top_menu) 

169 menu.addSeparator() 

170 menu.addAction(project_window.quick_access_manage_action) 

171 menu.addAction(self.undo_history_action) 

172 self._tab_menus[project_window] = menu 

173 

174 if sys.platform != "darwin": 174 ↛ 177line 174 didn't jump to line 177 because the condition on line 174 was never true

175 # Windows では上部バーの ≡ にまとめる(macOS は画面上のメニューバーのまま)。メニューバーを隠すと 

176 # そこにしか無い QAction のショートカットが効かなくなるので、全部をタブにも足す 

177 project_window.menuBar().hide() 

178 project_window.addActions([action for _path, action in project_window._collect_menu_actions() 

179 if not action.shortcut().isEmpty()]) 

180 

181 # クイックアクセスのツールバーは画面に出さず、ピン留めの並びを持つだけにする(上部バーの ★ が一覧で出す) 

182 toolbar = project_window.quick_access_toolbar 

183 project_window.removeToolBar(toolbar) 

184 toolbar.hide() 

185 

186 ui_mode.apply_ui_mode(project_window, self.ui_mode) 

187 project_window.dark_mode_action.toggled.connect(lambda _checked: self.header.refresh_icons()) 

188 

189 def add_new_project_tab(self, run_startup_checks=False): 

190 tab_id = self._next_tab_id 

191 self._next_tab_id += 1 

192 

193 project_window = PlotterApp( 

194 run_startup_checks=run_startup_checks, 

195 tab_id=(None if run_startup_checks else tab_id), 

196 ) 

197 project_window.project_state_changed.connect( 

198 lambda pw=project_window: self._refresh_tab_title(pw) 

199 ) 

200 

201 self.undo_group.addStack(project_window.undo_stack) 

202 self._attach_tab_chrome(project_window) 

203 

204 # 埋め込んだ QMainWindow は最上位ウィンドウのフラグが残るので外す。親を確定させてから1回だけ変える 

205 # (変更と付け替えの2段階にすると、macOS でタブが入力を受け付けなくなる) 

206 index = self.tab_widget.addTab(project_window, self._tab_title_for(project_window)) 

207 project_window.setWindowFlags(Qt.WindowType.Widget) 

208 self.tab_widget.setCurrentIndex(index) 

209 project_window.show() 

210 return project_window 

211 

212 def open_files(self, paths, reuse_empty_tab=False): 

213 """外から渡されたファイル(起動の引数・起動中のアプリへの受け渡し・macOS の Finder)を開く。 

214 

215 プロジェクトは 1 つずつ新しいタブに開き、データファイルは最後に開いたタブ(無ければ新しいタブ)に加える。 

216 reuse_empty_tab なら、今のタブが空で未保存の変更も無いときだけ最初のプロジェクトをそこに開く(起動直後)。 

217 """ 

218 project_suffixes = PROJECT_FILE_EXTENSIONS + (LEGACY_PICKLE_EXTENSION,) 

219 project_paths = [p for p in paths if p.lower().endswith(project_suffixes)] 

220 data_paths = [p for p in paths if not p.lower().endswith(project_suffixes)] 

221 

222 target = None 

223 current = self.tab_widget.currentWidget() 

224 if reuse_empty_tab and current is not None and not current.project.datasets \ 

225 and not current.has_unsaved_changes(): 

226 target = current 

227 for index, path in enumerate(project_paths): 

228 if target is None or index > 0: 

229 target = self.add_new_project_tab() 

230 target._load_project_from_path(path) 

231 if data_paths: 

232 if target is None: 232 ↛ 233line 232 didn't jump to line 233 because the condition on line 232 was never true

233 target = current if reuse_empty_tab and current is not None else self.add_new_project_tab() 

234 target._queue_data_files(data_paths) 

235 self.bring_to_front() 

236 

237 def bring_to_front(self): 

238 if self.isMinimized(): 238 ↛ 239line 238 didn't jump to line 239 because the condition on line 238 was never true

239 self.showNormal() 

240 self.raise_() 

241 self.activateWindow() 

242 

243 def _tab_title_for(self, project_window): 

244 return project_window.document_title() 

245 

246 def _refresh_tab_title(self, project_window): 

247 index = self.tab_widget.indexOf(project_window) 

248 if index != -1: 248 ↛ exitline 248 didn't return from function '_refresh_tab_title' because the condition on line 248 was always true

249 self.tab_widget.setTabText(index, self._tab_title_for(project_window)) 

250 if index == self.tab_widget.currentIndex(): 250 ↛ exitline 250 didn't return from function '_refresh_tab_title' because the condition on line 250 was always true

251 self._update_window_title(project_window) 

252 

253 def _update_window_title(self, project_window): 

254 self.setWindowTitle(f"{APP_NAME} {__version__} - {self._tab_title_for(project_window)}") 

255 

256 def _on_current_tab_changed(self, index): 

257 if index == -1: 257 ↛ 258line 257 didn't jump to line 258 because the condition on line 257 was never true

258 return 

259 project_window = self.tab_widget.widget(index) 

260 if project_window is not None: 260 ↛ exitline 260 didn't return from function '_on_current_tab_changed' because the condition on line 260 was always true

261 self._update_window_title(project_window) 

262 self.undo_group.setActiveStack(project_window.undo_stack) 

263 menu = self._tab_menus.get(project_window) 

264 if menu is not None: 264 ↛ exitline 264 didn't return from function '_on_current_tab_changed' because the condition on line 264 was always true

265 self.header.menu_button.setMenu(menu) 

266 

267 def _on_tab_close_requested(self, index): 

268 """最後の1つを閉じたら、空のプロジェクトのタブに置き換えてスタートアップ画面を出す。 

269 

270 タブが無くなる時はつくらない(メニューは各タブが持つので、0枚だと何もできなくなる)。 

271 """ 

272 project_window = self.tab_widget.widget(index) 

273 if project_window is not None and not project_window.confirm_unsaved_changes("タブを閉じる"): 

274 return 

275 replacement = self.add_new_project_tab() if self.tab_widget.count() <= 1 else None 

276 self.tab_widget.removeTab(self.tab_widget.indexOf(project_window)) 

277 if project_window is not None: 277 ↛ 283line 277 didn't jump to line 283 because the condition on line 277 was always true

278 # 閉じた直後から履歴パネルの対象に残らないよう、明示的に外す 

279 self.undo_group.removeStack(project_window.undo_stack) 

280 self._tab_menus.pop(project_window, None) 

281 project_window.close() 

282 project_window.deleteLater() 

283 if replacement is not None: 

284 replacement._show_welcome_dialog(last_tab_closed=True) 

285 

286 def closeEvent(self, event): 

287 """全部のタブに正常終了の処理をさせてから閉じる。""" 

288 # 未保存の変更は、そのタブを前に出して尋ねる。全部尋ねてから閉じ始めるので、1つでもキャンセルなら何も閉じない 

289 for index in range(self.tab_widget.count()): 

290 project_window = self.tab_widget.widget(index) 

291 if project_window is None or not project_window.has_unsaved_changes(): 

292 continue 

293 self.tab_widget.setCurrentIndex(index) 

294 if not project_window.confirm_unsaved_changes("Graphica を終了する"): 

295 event.ignore() 

296 return 

297 app_settings.WINDOW_GEOMETRY.write(self._settings, self.saveGeometry()) 

298 for index in range(self.tab_widget.count()): 

299 project_window = self.tab_widget.widget(index) 

300 if project_window is not None: 300 ↛ 298line 300 didn't jump to line 298 because the condition on line 300 was always true

301 project_window.close() 

302 super().closeEvent(event)