Coverage for graphica/gui/shell/dataset_page.py: 100.0%
199 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"""左パネルの「データセット」のページ。今の一覧・検索欄・操作のボタンを、中央の下から移して並べ直す。
3見本(docs/dev/mockups/gui_redesign/)の並び: 見出し(件数・フォルダ・+追加)、検索欄、一覧、選んでいる
4データセットの統計カード(2段目はアドバンスドだけ)、下に操作のボタンの行。
5"""
6import numpy as np
7from PySide6.QtCore import QSize, Qt, QTimer
8from PySide6.QtGui import QAction
9from PySide6.QtWidgets import (QFrame, QGridLayout, QHBoxLayout, QLabel, QSizePolicy, QTreeWidgetItemIterator,
10 QVBoxLayout, QWidget)
12from graphica.core.analysis import sample_standard_deviation
13from graphica.core.i18n import tr
14from graphica.gui.builders.common import discard_widget
15from graphica.gui.dataset_style_icon import make_dataset_style_icon
16from graphica.gui.shell.icons import themed_icon
17from graphica.gui.widgets import ElidedLabel, StatCard
19LEFT_PANEL_WIDTH = 280
20# ボタンの行に残すもの(左から)。曲線フィット・ピーク検出・多峰フィット・新規作成は「…」のメニューへ
21FOOT_BUTTONS = (
22 ("view_edit_data_button", "table"),
23 ("duplicate_dataset_button", "copy"),
24 ("auto_color_button", "palette"),
25)
26OVERFLOW_BUTTON_ACTIONS = (
27 ("new_dataset_button", "新規作成..."),
28 None,
29 ("fit_curve_button", "曲線フィット..."),
30 ("find_peaks_button", "ピーク検出..."),
31 ("multi_peak_fit_button", "多峰フィット..."),
32)
35def _ghost(button, icon_name, size=30):
36 """枠の無いアイコンのボタンにする(今のボタンをそのまま使う)。"""
37 button.setProperty("iconOnly", True)
38 button.setProperty("ghostButton", True)
39 button.setText("")
40 button.setFixedSize(size, size)
41 button.setIconSize(QSize(18, 18))
42 button.setIcon(themed_icon(icon_name))
43 button.setProperty("iconName", icon_name)
44 button.style().unpolish(button)
45 button.style().polish(button)
46 return button
49def _take_all(layout):
50 """レイアウトから部品を全部外す(部品は消さない。区切りの線は消す)。"""
51 while layout.count():
52 item = layout.takeAt(0)
53 widget = item.widget()
54 if widget is not None and widget.objectName() == "button_row_separator":
55 discard_widget(widget)
58def _dataset_items(tree):
59 iterator = QTreeWidgetItemIterator(tree)
60 while iterator.value():
61 item = iterator.value()
62 if item.data(0, Qt.ItemDataRole.UserRole) is not None:
63 yield item
64 iterator += 1
67class DatasetPage(QWidget):
68 def __init__(self, app, parent=None):
69 super().__init__(parent)
70 self.setObjectName("dataset_page")
71 self._app = app
72 tree = app.ui.dataset_list_widget
73 old_container = tree.parentWidget()
74 app.ui.gridLayout_2.removeWidget(old_container)
75 _take_all(old_container.layout())
76 discard_widget(old_container)
77 _take_all(app.ui.horizontalLayout_3)
78 app.ui.gridLayout_2.removeItem(app.ui.horizontalLayout_3)
80 layout = QVBoxLayout(self)
81 layout.setContentsMargins(0, 0, 0, 0)
82 layout.setSpacing(0)
84 # 見出し
85 head = QHBoxLayout()
86 head.setContentsMargins(14, 0, 10, 0)
87 head.setSpacing(6)
88 title = QLabel(tr("データセット"))
89 title.setObjectName("panel_title")
90 self.count_label = QLabel("0")
91 self.count_label.setObjectName("count_pill")
92 self.count_label.setFixedHeight(18)
93 self.count_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
94 head.addWidget(title)
95 head.addWidget(self.count_label)
96 head.addStretch(1)
97 head.addWidget(_ghost(app.new_folder_button, "folder-plus", size=28))
98 add_button = app.ui.add_dataset_button
99 add_button.setProperty("iconOnly", False)
100 add_button.setProperty("primaryButton", True)
101 add_button.setText(tr("追加"))
102 add_button.setMinimumSize(0, 0)
103 add_button.setMaximumSize(16777215, 16777215)
104 add_button.setIconSize(QSize(14, 14))
105 add_button.setIcon(themed_icon("plus", size=14, token="on_accent"))
106 add_button.style().unpolish(add_button)
107 add_button.style().polish(add_button)
108 head.addWidget(add_button)
109 head_box = QWidget()
110 head_box.setFixedHeight(52)
111 head_box.setLayout(head)
112 layout.addWidget(head_box)
114 search_row = QHBoxLayout()
115 search_row.setContentsMargins(12, 0, 12, 8)
116 search_row.addWidget(app.dataset_search_edit)
117 layout.addLayout(search_row)
119 tree_row = QHBoxLayout()
120 tree_row.setContentsMargins(8, 0, 8, 4)
121 # 余った高さは一覧に回す(カードや見出しは中身の高さのまま)
122 tree.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
123 tree_row.addWidget(tree)
124 layout.addLayout(tree_row, 1)
126 # 選んでいるデータセットの統計
127 stats_head = QHBoxLayout()
128 stats_head.setContentsMargins(14, 6, 14, 6)
129 stats_head.setSpacing(6)
130 self.stats_swatch = QLabel()
131 self.stats_name = ElidedLabel("-")
132 self.stats_name.setObjectName("stats_target_label")
133 stats_head.addWidget(self.stats_swatch)
134 stats_head.addWidget(self.stats_name, 1)
135 layout.addLayout(stats_head)
136 self.cards = {}
137 layout.addWidget(self._card_row((("n", "点の数"), ("mean", "平均"), ("sd", "標準偏差"))))
138 app.dataset_stats_advanced_row = self._card_row((("min", "最小"), ("max", "最大"), ("missing", "欠損")))
139 layout.addWidget(app.dataset_stats_advanced_row)
140 layout.addSpacing(6)
142 # 操作のボタンの行
143 foot = QFrame()
144 foot.setObjectName("panel_foot")
145 foot_layout = QHBoxLayout(foot)
146 foot_layout.setContentsMargins(8, 6, 8, 6)
147 foot_layout.setSpacing(2)
148 for attr, icon_name in FOOT_BUTTONS:
149 foot_layout.addWidget(_ghost(getattr(app, attr), icon_name))
150 foot_layout.addStretch(1)
151 overflow = app.dataset_overflow_button
152 overflow.setText("")
153 overflow.setProperty("ghostButton", True)
154 overflow.setFixedSize(30, 30)
155 overflow.setIconSize(QSize(18, 18))
156 overflow.setIcon(themed_icon("dots"))
157 overflow.setProperty("iconName", "dots")
158 overflow.setStyleSheet("QToolButton::menu-indicator { image: none; width: 0; }")
159 self._extend_overflow_menu(overflow.menu())
160 foot_layout.addWidget(overflow)
161 foot_layout.addWidget(_ghost(app.ui.remove_dataset_button, "trash"))
162 layout.addWidget(foot)
164 # 移さなかったボタン(…のメニューから押す)は見せないだけで残す(シグナルとテストはそのまま)
165 for entry in OVERFLOW_BUTTON_ACTIONS:
166 if entry is not None:
167 button = getattr(app, entry[0])
168 button.setParent(self)
169 button.hide()
171 # ダークモードの切り替えでアイコンを作り直す表(_refresh_custom_svg_icons)を、移したボタンの形に合わせる
172 icons = app._dataset_action_button_icons
173 for attr, icon_name in FOOT_BUTTONS:
174 button = getattr(app, attr)
175 icons[button] = (icon_name, icons.get(button, (icon_name, ""))[1])
176 icons.pop(add_button, None)
178 self.setFixedWidth(LEFT_PANEL_WIDTH)
179 self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding)
181 self._count_timer = QTimer(self)
182 self._count_timer.setSingleShot(True)
183 self._count_timer.timeout.connect(self.refresh_count)
184 model = tree.model()
185 for signal in (model.rowsInserted, model.rowsRemoved, model.modelReset):
186 signal.connect(lambda *args: self._count_timer.start(0))
187 self.refresh_count()
188 self.set_stats(None)
190 def _card_row(self, entries):
191 row = QWidget()
192 row.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
193 grid = QGridLayout(row)
194 grid.setContentsMargins(12, 0, 12, 6)
195 grid.setSpacing(6)
196 for column, (key, label) in enumerate(entries):
197 card = StatCard(tr(label))
198 self.cards[key] = card
199 grid.addWidget(card, 0, column)
200 return row
202 def _extend_overflow_menu(self, menu):
203 """今の「…」のメニューの頭に、ボタンの行から外した操作を足す(押すと元のボタンを押したのと同じ)。"""
204 first = menu.actions()[0] if menu.actions() else None
205 self._overflow_actions = []
206 for entry in OVERFLOW_BUTTON_ACTIONS:
207 if entry is None:
208 action = menu.insertSeparator(first)
209 else:
210 attr, text = entry
211 button = getattr(self._app, attr)
212 action = QAction(tr(text), menu)
213 menu.insertAction(first, action)
214 action.triggered.connect(button.click)
215 self._overflow_actions.append((action, button))
216 menu.insertSeparator(first)
217 # ボタンの有効・無効は選択で変わるので、開くたびに写す
218 menu.aboutToShow.connect(self._sync_overflow_enabled)
220 def _sync_overflow_enabled(self):
221 for action, button in self._overflow_actions:
222 action.setEnabled(button.isEnabled())
224 def refresh_count(self):
225 self.count_label.setText(str(sum(1 for _ in _dataset_items(self._app.ui.dataset_list_widget))))
227 def set_stats(self, dataset):
228 """選んでいるデータセットの Y の統計(NaN は数えない)。None なら全部「-」。"""
229 values = dict.fromkeys(("n", "mean", "sd", "min", "max", "missing"), "-")
230 if dataset is None:
231 self.stats_name.setText("-")
232 self.stats_swatch.clear()
233 else:
234 self.stats_name.setText(dataset.name)
235 self.stats_swatch.setPixmap(make_dataset_style_icon(dataset).pixmap(QSize(16, 10)))
236 try:
237 y = np.asarray(dataset.y_data, dtype=float)
238 valid = y[~np.isnan(y)]
239 values["missing"] = str(int(len(y) - len(valid)))
240 if len(valid):
241 std = sample_standard_deviation(valid)
242 values.update(n=str(len(valid)), mean=f"{np.mean(valid):.4g}",
243 sd="-" if np.isnan(std) else f"{std:.4g}",
244 min=f"{np.min(valid):.4g}", max=f"{np.max(valid):.4g}")
245 except (TypeError, ValueError):
246 pass
247 for key, card in self.cards.items():
248 card.set_value(values[key])
250 def refresh_icons(self):
251 app = self._app
252 for attr, icon_name in FOOT_BUTTONS:
253 getattr(app, attr).setIcon(themed_icon(icon_name))
254 app.new_folder_button.setIcon(themed_icon("folder-plus"))
255 app.ui.remove_dataset_button.setIcon(themed_icon("trash"))
256 app.dataset_overflow_button.setIcon(themed_icon("dots"))
257 app.ui.add_dataset_button.setIcon(themed_icon("plus", size=14, token="on_accent"))