Coverage for graphica/gui/motion.py: 87.6%

332 statements  

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

1"""画面の短い動き(タブの切り替え・節の開閉・セグメントの板・下のパネル・ポップアップ)。 

2 

3環境設定の「画面の動き」(app_settings.ANIMATIONS)で止められる。画面の無い環境(offscreen: テストと 

4特性テスト)では常に止め、どの部品もすぐ最後の状態になる(記録が時間で揺れないように)。 

5""" 

6import shiboken6 

7from PySide6.QtCore import QEasingCurve, QEvent, QObject, QPoint, QPropertyAnimation, QRect, Qt, QTimer, QVariantAnimation 

8from PySide6.QtGui import QPalette, QPixmap, QRegion 

9from PySide6.QtWidgets import QApplication, QGraphicsOpacityEffect, QLabel, QScrollArea, QVBoxLayout, QWidget 

10 

11# ms。短いほど「待たされる」感じが出ない。開閉のように大きく動くものだけ少し長く 

12FADE_MS = 140 

13EXPAND_MS = 220 

14SLIDE_MS = 160 

15POPUP_MS = 110 

16EASING = QEasingCurve.Type.OutCubic 

17# 高さのように大きく動くものは、ゆっくり動き出して途中で速く、ゆっくり止める。 

18# 始めが一番速い OutCubic だと、最初の1コマで大きく飛んでガクッと見える 

19EXPAND_EASING = QEasingCurve.Type.InOutCubic 

20# 1コマの中でレイアウトの知らせを片付ける回数(入れ子の深さぶん。知らせが無ければすぐ終わる) 

21LAYOUT_FLUSH_PASSES = 4 

22# Qt の QWIDGETSIZE_MAX。開き終わった節の高さの上限を外すのに使う 

23UNBOUNDED_HEIGHT = 16777215 

24 

25_enabled = True 

26# 動いている(動き出す前も含む)ものの一覧。テストが「全部止まるまで待つ」のに使う 

27_active = set() 

28 

29 

30def busy(): 

31 """動いている途中か、動き出しを待っているものがあるか。""" 

32 for animation in list(_active): 

33 if not shiboken6.isValid(animation): 33 ↛ 34line 33 didn't jump to line 34 because the condition on line 33 was never true

34 _active.discard(animation) 

35 return bool(_active) 

36 

37 

38def _track(animation): 

39 _active.add(animation) 

40 animation.finished.connect(lambda: _active.discard(animation)) 

41 animation.destroyed.connect(lambda *_args: _active.discard(animation)) 

42 return animation 

43 

44 

45def set_enabled(enabled): 

46 """止めたり戻したりする。メニュー(★ や右クリック)とツールチップは Qt のふわっと出す効果をそろえて切り替える。""" 

47 global _enabled 

48 _enabled = bool(enabled) 

49 app = QApplication.instance() 

50 if app is None: 50 ↛ 51line 50 didn't jump to line 51 because the condition on line 50 was never true

51 return 

52 on = is_enabled() 

53 for effect in (Qt.UIEffect.UI_AnimateMenu, Qt.UIEffect.UI_FadeMenu, Qt.UIEffect.UI_AnimateTooltip, 

54 Qt.UIEffect.UI_FadeTooltip): 

55 QApplication.setEffectEnabled(effect, on) 

56 

57 

58def is_enabled(): 

59 app = QApplication.instance() 

60 return _enabled and app is not None and app.platformName() != "offscreen" 

61 

62 

63def _keep(owner, name, animation): 

64 """動きの途中で GC されないよう持ち主に持たせる。同じ名前の前の動きは止める。""" 

65 previous = getattr(owner, name, None) 

66 # 前のものは終わったときに Qt 側で消えていることがある(重ね絵は消し終わると deleteLater する) 

67 if previous is not None and shiboken6.isValid(previous): 

68 if hasattr(previous, "stop"): 

69 previous.stop() 

70 _active.discard(previous) 

71 elif isinstance(previous, QWidget): 71 ↛ 73line 71 didn't jump to line 73 because the condition on line 71 was always true

72 previous.deleteLater() 

73 setattr(owner, name, animation) 

74 return animation 

75 

76 

77def crossfade(container, old_pixmap, duration=FADE_MS): 

78 """切り替える前の絵(old_pixmap)を container の上に重ね、それを消していく。 

79 

80 新しいページは最初からふつうに描かれる。ページそのものを半透明にすると、後ろに前のページの絵が残って見える。 

81 """ 

82 if not is_enabled() or container is None or old_pixmap is None or old_pixmap.isNull(): 

83 return 

84 overlay = QLabel(container) 

85 overlay.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) 

86 overlay.setPixmap(old_pixmap) 

87 # 引き伸ばさず撮ったときの大きさのまま重ねる(ページの高さが違うと、絵がゆがんでちらついて見える) 

88 ratio = old_pixmap.devicePixelRatio() or 1.0 

89 overlay.setGeometry(QRect(0, 0, round(old_pixmap.width() / ratio), round(old_pixmap.height() / ratio))) 

90 effect = QGraphicsOpacityEffect(overlay) 

91 effect.setOpacity(1.0) 

92 overlay.setGraphicsEffect(effect) 

93 overlay.show() 

94 overlay.raise_() 

95 animation = _track(QPropertyAnimation(effect, b"opacity", overlay)) 

96 animation.setDuration(duration) 

97 animation.setStartValue(1.0) 

98 animation.setEndValue(0.0) 

99 animation.setEasingCurve(EASING) 

100 animation.finished.connect(overlay.deleteLater) 

101 _keep(container, "_motion_crossfade_overlay", overlay) 

102 # 新しいページを初めて描くのは重いので、描き終わってから消し始める 

103 QTimer.singleShot(0, lambda: animation.start() if shiboken6.isValid(animation) else None) 

104 

105 

106class SectionClip(QWidget): 

107 """節の中身(body)を入れる外枠。開閉の間だけ高さを動かし、はみ出した中身は切って見せる。 

108 

109 中身は動いている間、本来の高さに固定する(外枠と一緒に縮めると、中の行が毎回詰め直されて揺れる)。 

110 """ 

111 

112 def __init__(self, body, parent=None): 

113 super().__init__(parent) 

114 layout = QVBoxLayout(self) 

115 layout.setContentsMargins(0, 0, 0, 0) 

116 layout.setSpacing(0) 

117 layout.addWidget(body, 0, Qt.AlignmentFlag.AlignTop) 

118 self.body = body 

119 

120 

121def _fit_scroll_content(widget): 

122 """widget の入ったスクロールの中身を、今の高さに合わせてすぐ広げる・縮める。 

123 

124 外枠を高くしたとき、中身の入れ物は次のレイアウトの回まで前の高さのままなので、その間はほかの節が 

125 押し縮められ(上の節が数 px 動いて戻る)、1コマごとに揺れて見える。同じ回のうちに入れ物の高さを合わせる。 

126 """ 

127 parent = widget.parentWidget() 

128 while parent is not None and not isinstance(parent, QScrollArea): 

129 parent = parent.parentWidget() 

130 if parent is None or not parent.widgetResizable() or parent.widget() is None: 

131 return 

132 content = parent.widget() 

133 # 外枠から中身の入れ物まで、途中の入れ物の覚えている大きさを全部捨てる。 

134 # 1段ずつ知らせが上がるのを待つと、その途中の回で、前の高さの入れ物の中の節が押し縮められる 

135 ancestor = widget 

136 while ancestor is not None: 136 ↛ 142line 136 didn't jump to line 142 because the condition on line 136 was always true

137 if ancestor.layout() is not None: 137 ↛ 139line 137 didn't jump to line 139 because the condition on line 137 was always true

138 ancestor.layout().invalidate() 

139 if ancestor is content: 

140 break 

141 ancestor = ancestor.parentWidget() 

142 width = content.width() 

143 hint = content.heightForWidth(width) if content.hasHeightForWidth() else -1 

144 if hint <= 0: 144 ↛ 145line 144 didn't jump to line 145 because the condition on line 144 was never true

145 hint = content.sizeHint().height() 

146 height = max(parent.viewport().height(), hint) 

147 if content.height() != height: 147 ↛ 148line 147 didn't jump to line 148 because the condition on line 147 was never true

148 content.resize(width, height) 

149 elif content.layout() is not None: 149 ↛ 152line 149 didn't jump to line 152 because the condition on line 149 was always true

150 content.layout().activate() 

151 # まだ順番待ちのレイアウトの知らせ(下の節を動かすものなど)も、次に描く前に済ませる 

152 for _ in range(LAYOUT_FLUSH_PASSES): 

153 QApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest) 

154 

155 

156def freeze_for_close(clip, keep_picture=True): 

157 """閉じ始める瞬間の中身を、閉じ終わるまでそのまま見せる(同じ知らせで中の行が消える節があるため)。 

158 

159 スイッチでオフにした節(グラデーションなど)は、オフの知らせで中の行が先に消え、中身が空になる。 

160 そのまま縮めると、行が一気に消えて跳ねて見える。行が消える前に高さを止め、中身の絵をかぶせる。 

161 何度呼んでも同じ(閉じている途中なら何もしない)。keep_picture=False は高さを止めるだけ 

162 (見出しを押して閉じるときは中の行が変わらないので、絵を撮る時間を省く)。 

163 """ 

164 body = clip.body 

165 if clip.isHidden() or getattr(clip, "_close_picture", None) is not None or running(clip, "_motion_expand"): 

166 return 

167 if not keep_picture: 167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true

168 body.setFixedHeight(body.height()) 

169 clip.setFixedHeight(clip.height()) 

170 return 

171 picture = QLabel(clip) 

172 picture.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) 

173 picture.setPixmap(_picture(body)) 

174 picture.setGeometry(body.geometry()) 

175 picture.show() 

176 picture.raise_() 

177 clip._close_picture = picture 

178 body.setFixedHeight(body.height()) 

179 clip.setFixedHeight(clip.height()) 

180 

181 

182def _drop_close_picture(clip): 

183 picture = getattr(clip, "_close_picture", None) 

184 clip._close_picture = None 

185 if picture is not None and shiboken6.isValid(picture): 

186 picture.deleteLater() 

187 

188 

189def _natural_height(clip): 

190 """中の行が折り返す節は高さが幅で決まる(sizeHint を使うと、止まった後に 1px 揺れる)。""" 

191 body = clip.body 

192 width = clip.width() or body.width() 

193 natural = body.heightForWidth(width) if body.hasHeightForWidth() and width > 0 else -1 

194 return max(1, natural if natural > 0 else body.sizeHint().height()) 

195 

196 

197def animate_section(clip, opening): 

198 """clip(SectionClip)を開く・閉じる。中身は本来の高さに止めたまま、外枠の高さだけを動かす。 

199 

200 途中で逆に押されたら、今の高さから続ける。 

201 """ 

202 body = clip.body 

203 moving = running(clip, "_motion_expand") 

204 if opening: 

205 _drop_close_picture(clip) 

206 body.setVisible(True) 

207 clip.setVisible(True) 

208 body.setMinimumHeight(0) 

209 body.setMaximumHeight(UNBOUNDED_HEIGHT) 

210 full = _natural_height(clip) 

211 start, end = (clip.height() if moving else 0), full 

212 body.setFixedHeight(full) 

213 else: 

214 freeze_for_close(clip, keep_picture=False) 

215 start, end = clip.height(), 0 

216 clip.setFixedHeight(start) 

217 _fit_scroll_content(clip) 

218 

219 def step(value): 

220 clip.setFixedHeight(round(value)) 

221 _fit_scroll_content(clip) 

222 

223 def finish(): 

224 _drop_close_picture(clip) 

225 body.setMinimumHeight(0) 

226 body.setMaximumHeight(UNBOUNDED_HEIGHT) 

227 clip.setMinimumHeight(0) 

228 clip.setMaximumHeight(UNBOUNDED_HEIGHT) 

229 body.setVisible(opening) 

230 clip.setVisible(opening) 

231 _fit_scroll_content(clip) 

232 

233 animate_value(clip, "_motion_expand", start, end, step, finish, EXPAND_MS, EXPAND_EASING) 

234 

235 

236def grab(widget): 

237 """クロスフェードに使う今の絵。動きが止まっていれば撮らない(撮るのにも少し時間がかかる)。 

238 

239 widget.grab() は後ろを窓の地の色(灰色)で塗ってから撮るので、白い面の上に重ねると一瞬灰色に見える。 

240 面の色(パレットの Base = surface)で塗ってから中身だけを描く。 

241 """ 

242 if not is_enabled() or widget is None or not widget.isVisible(): 

243 return None 

244 return _picture(widget) 

245 

246 

247def _picture(widget): 

248 ratio = widget.devicePixelRatioF() 

249 picture = QPixmap(round(widget.width() * ratio), round(widget.height() * ratio)) 

250 picture.setDevicePixelRatio(ratio) 

251 picture.fill(widget.palette().color(QPalette.ColorRole.Base)) 

252 widget.render(picture, QPoint(), QRegion(), QWidget.RenderFlag.DrawChildren) 

253 return picture 

254 

255 

256def fade_in(widget, duration=FADE_MS): 

257 """widget を透明からふわっと出す。終わったら効果を外す(効果を付けたままだと描画が遅くなる)。""" 

258 if not is_enabled() or widget is None: 

259 return 

260 effect = QGraphicsOpacityEffect(widget) 

261 effect.setOpacity(0.0) 

262 widget.setGraphicsEffect(effect) 

263 animation = _track(QPropertyAnimation(effect, b"opacity", widget)) 

264 animation.setDuration(duration) 

265 animation.setStartValue(0.0) 

266 animation.setEndValue(1.0) 

267 animation.setEasingCurve(EASING) 

268 

269 def finish(): 

270 if widget.graphicsEffect() is effect: 

271 widget.setGraphicsEffect(None) 

272 

273 animation.finished.connect(finish) 

274 _keep(widget, "_motion_fade", animation).start() 

275 

276 

277def fade_in_window(window, duration=POPUP_MS): 

278 """ポップアップ(別の窓)を透明から出す。""" 

279 if not is_enabled() or window is None: 279 ↛ 281line 279 didn't jump to line 281 because the condition on line 279 was always true

280 return 

281 animation = _track(QPropertyAnimation(window, b"windowOpacity", window)) 

282 animation.setDuration(duration) 

283 animation.setStartValue(0.0) 

284 animation.setEndValue(1.0) 

285 animation.setEasingCurve(EASING) 

286 window.setWindowOpacity(0.0) 

287 _keep(window, "_motion_window_fade", animation).start() 

288 

289 

290def animate_value(owner, name, start, end, on_value, on_finished=None, duration=SLIDE_MS, easing=EASING, 

291 after_paint=False): 

292 """start から end へ値を動かし、途中の値を on_value に渡す。動きが止まっていればすぐ end を渡す。 

293 

294 after_paint=True は、今の重い処理(ページの切り替えなど)と次の描画が済んでから時計を動かす。 

295 すぐ動かすと、画面が固まっている間に動きの大半が過ぎ、最初に描けたときにはもう着いている。 

296 """ 

297 if not is_enabled() or start == end: 

298 on_value(end) 

299 if on_finished is not None: 299 ↛ 301line 299 didn't jump to line 301 because the condition on line 299 was always true

300 on_finished() 

301 return None 

302 animation = _track(QVariantAnimation(owner)) 

303 animation.setDuration(duration) 

304 animation.setStartValue(start) 

305 animation.setEndValue(end) 

306 animation.setEasingCurve(easing) 

307 animation.valueChanged.connect(on_value) 

308 if on_finished is not None: 308 ↛ 310line 308 didn't jump to line 310 because the condition on line 308 was always true

309 animation.finished.connect(on_finished) 

310 _keep(owner, name, animation) 

311 if after_paint: 

312 on_value(start) 

313 

314 def start_if_current(): 

315 if getattr(owner, name, None) is animation and shiboken6.isValid(animation): 

316 animation.start() 

317 

318 QTimer.singleShot(0, start_if_current) 

319 else: 

320 animation.start() 

321 return animation 

322 

323 

324def stop(owner, name): 

325 animation = getattr(owner, name, None) 

326 if animation is not None and shiboken6.isValid(animation): 

327 animation.stop() 

328 

329 

330def running(owner, name): 

331 animation = getattr(owner, name, None) 

332 return (animation is not None and shiboken6.isValid(animation) 

333 and animation.state() == QVariantAnimation.State.Running) 

334 

335 

336class TabIndicator(QWidget): 

337 """下線のタブの、選んだタブの下の線。タブを替えると横に滑る(QSS の選んだタブの下線は消しておく)。""" 

338 

339 HEIGHT = 2 

340 

341 def __init__(self, tab_bar, trailing_margin=0): 

342 """trailing_margin: QSS でタブの右に空けた余白(tabRect に含まれる)。線はその手前までにする。""" 

343 super().__init__(tab_bar) 

344 self.setObjectName("tab_indicator") 

345 self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) 

346 self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) 

347 self._tab_bar = tab_bar 

348 self._trailing_margin = trailing_margin 

349 tab_bar.setProperty("slidingIndicator", True) 

350 tab_bar.style().unpolish(tab_bar) 

351 tab_bar.style().polish(tab_bar) 

352 tab_bar.currentChanged.connect(lambda _index: self.follow(animate=True)) 

353 tab_bar.installEventFilter(self) 

354 self.follow(animate=False) 

355 

356 def _target(self): 

357 index = self._tab_bar.currentIndex() 

358 if index < 0: 

359 return None 

360 rect = self._tab_bar.tabRect(index) 

361 return QRect(rect.left(), rect.bottom() - self.HEIGHT + 1, rect.width() - self._trailing_margin, self.HEIGHT) 

362 

363 def follow(self, animate): 

364 target = self._target() 

365 if target is None or target.width() <= 0: 

366 self.hide() 

367 return 

368 self.show() 

369 self.raise_() 

370 start = self.geometry() 

371 if animate and self.isVisible() and start.width() > 0 and start != target: 

372 # 滑っている間にタブの幅が決まり直すこともあるので、止まったら今の行き先に合わせ直す 

373 animate_value(self, "_motion_slide", start, target, self.setGeometry, 

374 lambda: self.follow(animate=False), duration=SLIDE_MS, after_paint=True) 

375 else: 

376 stop(self, "_motion_slide") 

377 self.setGeometry(target) 

378 

379 def eventFilter(self, watched, event): 

380 if watched is self._tab_bar and not running(self, "_motion_slide"): 

381 if event.type() in (QEvent.Type.Resize, QEvent.Type.Show, QEvent.Type.LayoutRequest, 

382 QEvent.Type.StyleChange): 

383 # タブの幅は表示されてから決まる。動いている途中でなければ行き先へ合わせる 

384 QTimer.singleShot(0, lambda: self.follow(animate=False)) 

385 elif event.type() == QEvent.Type.Paint: 

386 # タブを出し入れしても(凡例のタブなど)上の知らせが来ないことがあるので、描くたびに確かめる 

387 target = self._target() 

388 if target is not None and target != self.geometry(): 

389 QTimer.singleShot(0, lambda: self.follow(animate=False)) 

390 return super().eventFilter(watched, event) 

391 

392 

393class _SwitchMotion(QObject): 

394 """スイッチのつまみを滑らせる。描くのはスタイル(theme._draw_toggle_switch)で、途中の位置を property で渡す。 

395 

396 束ねの復元はシグナルを止めて setChecked するので、そのときは動かさない(property は動いている間だけ置く)。 

397 """ 

398 

399 def __init__(self, checkbox): 

400 super().__init__(checkbox) 

401 self._checkbox = checkbox 

402 self._shown = 1.0 if checkbox.isChecked() else 0.0 

403 checkbox.toggled.connect(self._on_toggled) 

404 

405 def _on_toggled(self, checked): 

406 target = 1.0 if checked else 0.0 

407 checkbox = self._checkbox 

408 if not (is_enabled() and checkbox.isVisible()): 

409 self._shown = target 

410 return 

411 start = checkbox.property(SWITCH_PROGRESS_PROPERTY) 

412 start = self._shown if start is None else float(start) 

413 

414 def step(value): 

415 self._shown = float(value) 

416 checkbox.setProperty(SWITCH_PROGRESS_PROPERTY, float(value)) 

417 checkbox.update() 

418 

419 def finish(): 

420 checkbox.setProperty(SWITCH_PROGRESS_PROPERTY, None) 

421 checkbox.update() 

422 

423 checkbox.setProperty(SWITCH_PROGRESS_PROPERTY, start) 

424 animate_value(self, "_motion_switch", start, target, step, finish, SLIDE_MS, after_paint=True) 

425 

426 

427# スイッチのつまみの途中の位置(0 = オフ、1 = オン)。動いている間だけ置く 

428SWITCH_PROGRESS_PROPERTY = "switchProgress" 

429 

430 

431def attach_switch_motion(checkbox): 

432 if getattr(checkbox, "_switch_motion", None) is None: 432 ↛ exitline 432 didn't return from function 'attach_switch_motion' because the condition on line 432 was always true

433 checkbox._switch_motion = _SwitchMotion(checkbox) 

434 

435 

436class Toast(QLabel): 

437 """ウィンドウの右下に短い知らせ(「保存しました」など)をふわっと出して、少したったら消す。""" 

438 

439 SHOW_MS = 1800 

440 MARGIN = 18 

441 

442 def __init__(self, window): 

443 super().__init__(window) 

444 self.setObjectName("toast") 

445 self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) 

446 self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) 

447 self.hide() 

448 self._timer = QTimer(self) 

449 self._timer.setSingleShot(True) 

450 self._timer.timeout.connect(self._fade_out) 

451 

452 def show_message(self, text): 

453 self.setText(text) 

454 self.adjustSize() 

455 window = self.parentWidget() 

456 bottom_margin = self.MARGIN + 24 # ステータスバーの上 

457 self.move(window.width() - self.width() - self.MARGIN, window.height() - self.height() - bottom_margin) 

458 self.show() 

459 self.raise_() 

460 effect = QGraphicsOpacityEffect(self) 

461 self.setGraphicsEffect(effect) 

462 if is_enabled(): 462 ↛ 463line 462 didn't jump to line 463 because the condition on line 462 was never true

463 animate_value(self, "_motion_toast", 0.0, 1.0, effect.setOpacity, duration=FADE_MS) 

464 else: 

465 effect.setOpacity(1.0) 

466 self._timer.start(self.SHOW_MS) 

467 

468 def _fade_out(self): 

469 effect = self.graphicsEffect() 

470 if effect is None or not is_enabled(): 470 ↛ 473line 470 didn't jump to line 473 because the condition on line 470 was always true

471 self.hide() 

472 return 

473 animate_value(self, "_motion_toast", 1.0, 0.0, effect.setOpacity, self.hide, FADE_MS * 2) 

474 

475 

476def toast(widget, text): 

477 """widget のウィンドウの右下に知らせを出す(ステータスバーの表示はそのまま)。""" 

478 window = widget.window() if widget is not None else None 

479 if window is None: 479 ↛ 480line 479 didn't jump to line 480 because the condition on line 479 was never true

480 return 

481 box = getattr(window, "_toast", None) 

482 if box is None: 

483 box = Toast(window) 

484 window._toast = box 

485 box.show_message(text)