ms-components 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. ms_components/__init__.py +0 -0
  2. ms_components/base.qss +252 -0
  3. ms_components/listview.py +1287 -0
  4. ms_components/ms_dockwidget/__init__.py +0 -0
  5. ms_components/ms_dockwidget/resources/__init__.py +1 -0
  6. ms_components/ms_dockwidget/resources/icons/__init__.py +10 -0
  7. ms_components/ms_dockwidget/resources/icons/folder.svg +5 -0
  8. ms_components/ms_dockwidget/widget.py +1975 -0
  9. ms_components/ms_monitor/__init__.py +43 -0
  10. ms_components/ms_monitor/bridge.py +400 -0
  11. ms_components/ms_monitor/cards.py +75 -0
  12. ms_components/ms_monitor/chunk_panel.py +85 -0
  13. ms_components/ms_monitor/config.py +20 -0
  14. ms_components/ms_monitor/events_panel.py +178 -0
  15. ms_components/ms_monitor/executor_panel.py +149 -0
  16. ms_components/ms_monitor/executors_tab.py +355 -0
  17. ms_components/ms_monitor/formatting.py +51 -0
  18. ms_components/ms_monitor/job_cards.py +536 -0
  19. ms_components/ms_monitor/job_filter_proxy.py +48 -0
  20. ms_components/ms_monitor/job_tree_model.py +106 -0
  21. ms_components/ms_monitor/models.py +165 -0
  22. ms_components/ms_monitor/palette.py +41 -0
  23. ms_components/ms_monitor/polling.py +498 -0
  24. ms_components/ms_monitor/widget.py +401 -0
  25. ms_components/ms_projects/__init__.py +4 -0
  26. ms_components/ms_projects/app.py +18 -0
  27. ms_components/ms_projects/browser.py +2132 -0
  28. ms_components/ms_projects/scratch.py +772 -0
  29. ms_components/ms_projects/widget.py +284 -0
  30. ms_components/ms_pymol/__init__.py +13 -0
  31. ms_components/ms_pymol/icons/actions.svg +1 -0
  32. ms_components/ms_pymol/icons/box.svg +1 -0
  33. ms_components/ms_pymol/icons/center.svg +1 -0
  34. ms_components/ms_pymol/icons/display.svg +4 -0
  35. ms_components/ms_pymol/icons/hide.svg +1 -0
  36. ms_components/ms_pymol/icons/menu.svg +5 -0
  37. ms_components/ms_pymol/icons/orient.svg +11 -0
  38. ms_components/ms_pymol/icons/presets.svg +7 -0
  39. ms_components/ms_pymol/icons/rock.svg +6 -0
  40. ms_components/ms_pymol/icons/selection.svg +11 -0
  41. ms_components/ms_pymol/icons/settings.svg +4 -0
  42. ms_components/ms_pymol/icons/zoom.svg +6 -0
  43. ms_components/ms_pymol/plugins.py +158 -0
  44. ms_components/ms_pymol/widget.py +700 -0
  45. ms_components/ms_settings/__init__.py +3 -0
  46. ms_components/ms_settings/panel.py +899 -0
  47. ms_components/ms_settings/workers_editor.py +335 -0
  48. ms_components/ms_stepper.py +1106 -0
  49. ms_components/ms_table/__init__.py +67 -0
  50. ms_components/ms_table/action_header.py +502 -0
  51. ms_components/ms_table/cell_delegate.py +278 -0
  52. ms_components/ms_table/column_panel.py +120 -0
  53. ms_components/ms_table/example_usage.py +376 -0
  54. ms_components/ms_table/filter_panel.py +326 -0
  55. ms_components/ms_table/icons/columns.svg +5 -0
  56. ms_components/ms_table/icons/export.svg +6 -0
  57. ms_components/ms_table/icons/filter.svg +1 -0
  58. ms_components/ms_table/icons/menu.svg +5 -0
  59. ms_components/ms_table/icons/reload.svg +4 -0
  60. ms_components/ms_table/icons/search.svg +1 -0
  61. ms_components/ms_table/icons/settings.svg +4 -0
  62. ms_components/ms_table/icons/sort-asc.svg +1 -0
  63. ms_components/ms_table/icons/sort-desc.svg +1 -0
  64. ms_components/ms_table/icons/sort.svg +1 -0
  65. ms_components/ms_table/metric_filter_bar.py +232 -0
  66. ms_components/ms_table/pagination_control.py +178 -0
  67. ms_components/ms_table/query_builder.py +545 -0
  68. ms_components/ms_table/session_provider.py +11 -0
  69. ms_components/ms_table/smart_table_view.py +1378 -0
  70. ms_components/ms_table/sort_panel.py +171 -0
  71. ms_components/ms_table/table_config.py +394 -0
  72. ms_components/ms_table/table_model.py +329 -0
  73. ms_components/ms_table/test_external_filters.py +66 -0
  74. ms_components/ms_table/test_toolbar.py +130 -0
  75. ms_components/pagination.py +221 -0
  76. ms_components/step_dialog.py +135 -0
  77. ms_components/theme.py +346 -0
  78. ms_components/tool_panel.py +480 -0
  79. ms_components/wheel.py +66 -0
  80. ms_components-0.1.0.dist-info/METADATA +47 -0
  81. ms_components-0.1.0.dist-info/RECORD +84 -0
  82. ms_components-0.1.0.dist-info/WHEEL +5 -0
  83. ms_components-0.1.0.dist-info/licenses/LICENSE +21 -0
  84. ms_components-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1975 @@
1
+ import faulthandler
2
+ from dataclasses import dataclass
3
+ from enum import Enum, auto
4
+ from typing import Dict, List, Optional
5
+
6
+ from PySide6.QtCore import Qt, QSize, QMimeData, QPoint, QByteArray, QObject, QEvent, QTimer, QtMsgType, \
7
+ qInstallMessageHandler
8
+ from PySide6.QtGui import QAction, QCursor, QDrag, QIcon
9
+ from PySide6.QtWidgets import (QDockWidget, QFrame, QMainWindow, QMenu, QSizePolicy, QToolBar, QToolButton, QVBoxLayout,
10
+ QHBoxLayout, QLabel, QStyle,
11
+ QApplication, QWidget)
12
+
13
+ from .resources.icons import icon as load_icon
14
+
15
+ faulthandler.enable(all_threads=True)
16
+
17
+ def qt_message_handler(mode, context, message):
18
+ if mode == QtMsgType.QtInfoMsg:
19
+ mode_str = "INFO"
20
+ elif mode == QtMsgType.QtWarningMsg:
21
+ mode_str = "WARNING"
22
+ elif mode == QtMsgType.QtCriticalMsg:
23
+ mode_str = "CRITICAL"
24
+ elif mode == QtMsgType.QtFatalMsg:
25
+ mode_str = "FATAL"
26
+ else:
27
+ mode_str = "DEBUG"
28
+ print(f"[{mode_str}] {context.file}:{context.line} - {message}")
29
+
30
+
31
+ # Install the interceptor before creating the QApplication
32
+ qInstallMessageHandler(qt_message_handler)
33
+
34
+ DOCK_BUTTON_MIME_TYPE = "application/x-dock-id"
35
+ DOCK_BUTTON_DRAG_THRESHOLD = 6
36
+ TOOLBAR_COLLAPSED_WIDTH = 32
37
+ TOOLBAR_EXPANDED_WIDTH = 64
38
+ DEFAULT_TOOL_ICON = load_icon("folder.svg")
39
+ MENU_STYLE_SHEET = (
40
+ "QMenu { background: palette(window); color: palette(text); border: 1px solid palette(mid); }"
41
+ "QMenu::item:selected { background: palette(highlight); color: palette(highlighted-text); }"
42
+ "QMenu::separator { height: 1px; background: palette(mid); margin: 3px 0; }"
43
+ )
44
+
45
+
46
+ # ══════════════════════════════════════════════════════════════════
47
+ # Region
48
+ # ══════════════════════════════════════════════════════════════════
49
+
50
+ class Region(Enum):
51
+ LEFT_TOP = auto()
52
+ LEFT_BOTTOM = auto()
53
+ BOTTOM_LEFT = auto()
54
+ RIGHT_TOP = auto()
55
+ RIGHT_BOTTOM = auto()
56
+ BOTTOM_RIGHT = auto()
57
+
58
+ def is_left(self) -> bool:
59
+ return self in (Region.LEFT_TOP, Region.LEFT_BOTTOM, Region.BOTTOM_LEFT)
60
+
61
+ def is_right(self) -> bool:
62
+ return self in (Region.RIGHT_TOP, Region.RIGHT_BOTTOM, Region.BOTTOM_RIGHT)
63
+
64
+ def is_bottom(self) -> bool:
65
+ return self in (Region.BOTTOM_LEFT, Region.BOTTOM_RIGHT)
66
+
67
+ def is_lateral(self) -> bool:
68
+ return not self.is_bottom()
69
+
70
+ def qt_area(self) -> Qt.DockWidgetArea:
71
+ if self.is_bottom():
72
+ return Qt.DockWidgetArea.BottomDockWidgetArea
73
+ if self in (Region.LEFT_TOP, Region.LEFT_BOTTOM):
74
+ return Qt.LeftDockWidgetArea
75
+ return Qt.RightDockWidgetArea
76
+
77
+ def toolbar_side(self) -> "ToolbarSide":
78
+ return ToolbarSide.LEFT if self.is_left() else ToolbarSide.RIGHT
79
+
80
+ def toolbar_section(self) -> "ToolbarSection":
81
+ if self in (Region.LEFT_TOP, Region.RIGHT_TOP):
82
+ return ToolbarSection.TOP
83
+ if self in (Region.LEFT_BOTTOM, Region.RIGHT_BOTTOM):
84
+ return ToolbarSection.MIDDLE
85
+ return ToolbarSection.BOTTOM
86
+
87
+
88
+ class ToolbarSide(Enum):
89
+ LEFT = auto()
90
+ RIGHT = auto()
91
+
92
+
93
+ class ToolbarSection(Enum):
94
+ TOP = auto()
95
+ MIDDLE = auto()
96
+ BOTTOM = auto()
97
+
98
+
99
+ # ══════════════════════════════════════════════════════════════════
100
+ # Behavior / BottomMode
101
+ # ══════════════════════════════════════════════════════════════════
102
+
103
+ class Behavior(Enum):
104
+ EXCLUSIVE = auto()
105
+ MIXED_TAB = auto()
106
+ MIXED_EXCLUSIVE = auto()
107
+
108
+
109
+ class BottomMode(Enum):
110
+ SHARE = auto()
111
+ STACK = auto()
112
+
113
+
114
+
115
+
116
+
117
+ @dataclass
118
+ class RegionState:
119
+ order: List[str]
120
+ visible: List[str]
121
+
122
+
123
+ # ══════════════════════════════════════════════════════════════════
124
+ # TitleBarWidget
125
+ # ══════════════════════════════════════════════════════════════════
126
+
127
+ class TitleBarWidget(QWidget):
128
+ _MENU_SS = MENU_STYLE_SHEET
129
+
130
+ def __init__(self, dock: "MSDockWidget"):
131
+ super().__init__(dock)
132
+ self._dock = dock
133
+ self._drag_start: QPoint | None = None
134
+ self._system_move_started = False
135
+ self._manual_move = False
136
+
137
+ layout = QHBoxLayout(self)
138
+ layout.setContentsMargins(6, 2, 4, 2)
139
+ layout.setSpacing(4)
140
+
141
+ self.title_label = QLabel(dock.windowTitle())
142
+ self.title_label.setStyleSheet("color: palette(text); font-size: 11px;")
143
+ self.title_label.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
144
+ layout.addWidget(self.title_label)
145
+ layout.addStretch(1)
146
+
147
+ self.options_button = QToolButton()
148
+ self.options_button.setText("⋯")
149
+ self.options_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextOnly)
150
+ self.options_button.setAutoRaise(True)
151
+ self.options_button.setFixedSize(24, 24)
152
+ self.options_button.setStyleSheet(
153
+ "QToolButton { color: palette(text); border: none; padding: 0;"
154
+ " font-size: 18px; font-weight: 600; }"
155
+ "QToolButton:hover { color: palette(highlighted-text); background: palette(highlight); border-radius: 3px; }"
156
+ )
157
+ self.options_button.clicked.connect(self._show_menu)
158
+ layout.addWidget(self.options_button)
159
+
160
+ self.close_button = QToolButton()
161
+ self.close_button.setIcon(
162
+ self.style().standardIcon(QStyle.StandardPixmap.SP_DockWidgetCloseButton)
163
+ )
164
+ self.close_button.setAutoRaise(True)
165
+ self.close_button.setFixedSize(24, 24)
166
+ self.close_button.setIconSize(QSize(16, 16))
167
+ self.close_button.setStyleSheet(
168
+ "QToolButton { border: none; padding: 0; }"
169
+ "QToolButton:hover { background: #C0392B; border-radius: 3px; }"
170
+ )
171
+ self.close_button.clicked.connect(dock.close)
172
+ self.close_button.setVisible(
173
+ bool(dock.features() & QDockWidget.DockWidgetFeature.DockWidgetClosable)
174
+ )
175
+ layout.addWidget(self.close_button)
176
+
177
+ def mousePressEvent(self, event) -> None:
178
+ if event.button() == Qt.MouseButton.LeftButton:
179
+ self._drag_start = event.position().toPoint()
180
+ self._system_move_started = False
181
+ self._manual_move = False
182
+ event.accept()
183
+ return
184
+ super().mousePressEvent(event)
185
+
186
+ def mouseMoveEvent(self, event) -> None:
187
+ if (
188
+ self._drag_start is None
189
+ or not (event.buttons() & Qt.MouseButton.LeftButton)
190
+ ):
191
+ super().mouseMoveEvent(event)
192
+ return
193
+ if not self._system_move_started:
194
+ distance = (event.position().toPoint() - self._drag_start).manhattanLength()
195
+ if distance < QApplication.startDragDistance():
196
+ event.accept()
197
+ return
198
+ self._system_move_started = True
199
+ started = self._dock.begin_native_window_drag(
200
+ event.globalPosition().toPoint(),
201
+ self._drag_start,
202
+ )
203
+ self._manual_move = not started
204
+ elif self._manual_move:
205
+ self._dock.move(event.globalPosition().toPoint() - self._drag_start)
206
+ event.accept()
207
+
208
+ def mouseReleaseEvent(self, event) -> None:
209
+ if event.button() == Qt.MouseButton.LeftButton and self._drag_start is not None:
210
+ if self._system_move_started:
211
+ self._dock.finish_native_window_drag()
212
+ self._drag_start = None
213
+ self._system_move_started = False
214
+ self._manual_move = False
215
+ event.accept()
216
+ return
217
+ super().mouseReleaseEvent(event)
218
+
219
+ def mouseDoubleClickEvent(self, event) -> None:
220
+ if event.button() == Qt.MouseButton.LeftButton:
221
+ manager = self._dock._manager
222
+ dock_id = self._dock.objectName()
223
+ if manager is not None and manager.is_windowed(dock_id):
224
+ self._dock.dock_to_main_window()
225
+ else:
226
+ self._dock.open_in_window()
227
+ event.accept()
228
+ return
229
+ super().mouseDoubleClickEvent(event)
230
+
231
+ def update_title(self, title: str):
232
+ self.title_label.setText(title)
233
+
234
+ def _show_menu(self):
235
+ menu = QMenu(self)
236
+ menu.setStyleSheet(self._MENU_SS)
237
+
238
+ custom = self._dock.get_custom_actions()
239
+ if custom:
240
+ for item in custom:
241
+ if item is None:
242
+ menu.addSeparator()
243
+ elif isinstance(item, QAction):
244
+ menu.addAction(item)
245
+ elif isinstance(item, QMenu):
246
+ menu.addMenu(item)
247
+ menu.addSeparator()
248
+
249
+ window_act = QAction(
250
+ "Dock to Main Window" if self._dock.isFloating() else "Open in Window",
251
+ menu,
252
+ )
253
+ if self._dock.isFloating():
254
+ window_act.triggered.connect(self._dock.dock_to_main_window)
255
+ else:
256
+ window_act.triggered.connect(self._dock.open_in_window)
257
+ menu.addAction(window_act)
258
+ menu.addSeparator()
259
+
260
+ settings_act = QAction("Settings", menu)
261
+ settings_act.triggered.connect(self._dock.open_settings)
262
+ menu.addAction(settings_act)
263
+ menu.addSeparator()
264
+
265
+ move_menu = menu.addMenu("Move to")
266
+ move_menu.setStyleSheet(self._MENU_SS)
267
+ self._build_move_menu(move_menu)
268
+
269
+ resize_menu = menu.addMenu("Resize")
270
+ resize_menu.setStyleSheet(self._MENU_SS)
271
+ self._build_resize_menu(resize_menu)
272
+
273
+ menu.exec(self.options_button.mapToGlobal(
274
+ self.options_button.rect().bottomLeft()
275
+ ))
276
+
277
+ def _build_move_menu(self, menu: QMenu):
278
+ manager = self._dock._manager
279
+ if manager is None:
280
+ menu.addAction("(no manager)").setEnabled(False)
281
+ return
282
+ manager.populate_move_menu(menu, self._dock.objectName())
283
+
284
+ def _build_resize_menu(self, menu: QMenu):
285
+ mw = self._find_main_window()
286
+ entries = [
287
+ ("Stretch to Left", Qt.Orientation.Horizontal, True),
288
+ ("Stretch to Right", Qt.Orientation.Horizontal, False),
289
+ ("Stretch to Top", Qt.Orientation.Vertical, True),
290
+ ("Stretch to Bottom", Qt.Orientation.Vertical, False),
291
+ ]
292
+ for label, orientation, stretch_max in entries:
293
+ act = QAction(label, menu)
294
+ if mw is None:
295
+ act.setEnabled(False)
296
+ else:
297
+ act.triggered.connect(
298
+ lambda checked=False, o=orientation, s=stretch_max:
299
+ self._resize(o, s)
300
+ )
301
+ menu.addAction(act)
302
+
303
+ menu.addSeparator()
304
+ restore_act = QAction("Restore Size", menu)
305
+ if mw is None:
306
+ restore_act.setEnabled(False)
307
+ else:
308
+ restore_act.triggered.connect(self._restore_size)
309
+ menu.addAction(restore_act)
310
+
311
+ def _resize(self, orientation: Qt.Orientation, stretch_max: bool):
312
+ mw = self._find_main_window()
313
+ if mw is None:
314
+ return
315
+ size = (mw.width() if stretch_max else 1) if orientation == Qt.Orientation.Horizontal \
316
+ else (mw.height() if stretch_max else 1)
317
+ mw.resizeDocks([self._dock], [size], orientation)
318
+
319
+ def _restore_size(self):
320
+ mw = self._find_main_window()
321
+ if mw is None:
322
+ return
323
+ hint = self._dock.sizeHint()
324
+ mw.resizeDocks([self._dock], [hint.width()], Qt.Orientation.Horizontal)
325
+ mw.resizeDocks([self._dock], [hint.height()], Qt.Orientation.Vertical)
326
+
327
+ def _find_main_window(self) -> Optional[QMainWindow]:
328
+ p = self._dock.parent()
329
+ while p:
330
+ if isinstance(p, QMainWindow):
331
+ return p
332
+ p = p.parent()
333
+ return None
334
+
335
+
336
+ # ══════════════════════════════════════════════════════════════════
337
+ # MSDockWidget
338
+ # ══════════════════════════════════════════════════════════════════
339
+
340
+ class MSDockWidget(QDockWidget):
341
+ def __init__(self, title: str, manager: "DockManager", parent=None):
342
+ super().__init__(title, parent)
343
+ self._manager = manager
344
+ self._title_bar = TitleBarWidget(self)
345
+ self.setTitleBarWidget(self._title_bar)
346
+
347
+ def setWindowTitle(self, title: str):
348
+ super().setWindowTitle(title)
349
+ if hasattr(self, "_title_bar"):
350
+ self._title_bar.update_title(title)
351
+
352
+ def get_custom_actions(self) -> list:
353
+ return []
354
+
355
+ def open_in_window(self) -> None:
356
+ """Show this dock as a normal OS-managed top-level window."""
357
+ if self._manager is None:
358
+ self._promote_floating_window()
359
+ return
360
+ self._manager.open_in_window(self.objectName())
361
+
362
+ def dock_to_main_window(self) -> None:
363
+ """Return this top-level window to its configured dock region."""
364
+ if self._manager is None:
365
+ self.setFloating(False)
366
+ return
367
+ self._manager.dock_to_main_window(self.objectName())
368
+
369
+ def _promote_floating_window(self) -> None:
370
+ """Make this dock an OS-managed window while retaining its dock frame."""
371
+ flags = self.windowFlags()
372
+ if (
373
+ self.parent() is None
374
+ and self.titleBarWidget() is self._title_bar
375
+ and (flags & Qt.WindowType.WindowType_Mask) == Qt.WindowType.Window
376
+ ):
377
+ return
378
+ geometry = self.geometry()
379
+ was_visible = self.isVisible()
380
+ # Window|CustomizeWindowHint is the useful hybrid on X11/KWin: it is
381
+ # published as a NORMAL non-transient window (so startSystemMove gets OS
382
+ # snapping), while the existing dock title bar remains the only frame.
383
+ # Calling setFloating(True) first would permanently mark it as a Qt/KDE
384
+ # utility override and break this behavior.
385
+ self.setTitleBarWidget(self._title_bar)
386
+ self.setParent(
387
+ None,
388
+ Qt.WindowType.Window
389
+ | Qt.WindowType.CustomizeWindowHint,
390
+ )
391
+ if geometry.isValid():
392
+ self.setGeometry(geometry)
393
+ if was_visible:
394
+ self.show()
395
+ self.raise_()
396
+
397
+ def begin_native_window_drag(self, global_pos: QPoint, title_offset: QPoint) -> bool:
398
+ if self._manager is None:
399
+ return False
400
+ return self._manager.begin_native_window_drag(
401
+ self.objectName(),
402
+ global_pos,
403
+ title_offset,
404
+ )
405
+
406
+ def finish_native_window_drag(self) -> None:
407
+ if self._manager is not None:
408
+ self._manager.finish_native_window_drag()
409
+
410
+
411
+ def open_settings(self):
412
+ print(f"[{self.windowTitle()}] open_settings — override me")
413
+
414
+
415
+ # ══════════════════════════════════════════════════════════════════
416
+ # DockEntry
417
+ # ══════════════════════════════════════════════════════════════════
418
+
419
+ @dataclass
420
+ class DockEntry:
421
+ id: str
422
+ dock: "MSDockWidget"
423
+ title: str
424
+ region: Region
425
+ order: int
426
+ behavior: Behavior
427
+ icon: Optional[QIcon] = None
428
+ starts_visible: bool = False
429
+ bottom_mode: BottomMode = BottomMode.SHARE
430
+
431
+ # ══════════════════════════════════════════════════════════════════
432
+ # Toolbar button helpers
433
+ # ══════════════════════════════════════════════════════════════════
434
+
435
+ def _is_dock_button(widget: Optional[QWidget]) -> bool:
436
+ return isinstance(widget, QToolButton) and bool(widget.property("dock_id"))
437
+
438
+
439
+ def _create_toolbar_button(title: str, icon: Optional[QIcon] = None) -> QToolButton:
440
+ button = QToolButton()
441
+ effective_icon = icon if icon and not icon.isNull() else DEFAULT_TOOL_ICON
442
+ button.setText(title)
443
+ button.setToolTip(title)
444
+ # Kept unwrapped so set_button_style can re-derive the label for each mode.
445
+ button.setProperty("full_title", title)
446
+ button.setCheckable(True)
447
+ button.setCursor(Qt.PointingHandCursor)
448
+ button.setAutoRaise(True)
449
+ button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
450
+ button.setIcon(effective_icon)
451
+ button.setIconSize(QSize(24, 24))
452
+ button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
453
+ button.setStyleSheet(
454
+ "QToolButton {"
455
+ " color: palette(text);"
456
+ " border: none;"
457
+ " border-radius: 4px;"
458
+ " padding: 0px;"
459
+ " }"
460
+ "QToolButton:hover { background: palette(alternate-base); color: palette(text); }"
461
+ "QToolButton:checked { background: palette(highlight); color: palette(highlighted-text); }"
462
+ )
463
+ return button
464
+
465
+
466
+ class DockButtonDragFilter(QObject):
467
+ def __init__(self, parent=None):
468
+ super().__init__(parent)
469
+ self._drag_start: Dict[int, QPoint] = {}
470
+ self._dragging: Dict[int, bool] = {}
471
+
472
+ def register(self, button: QToolButton):
473
+ button.installEventFilter(self)
474
+
475
+ def eventFilter(self, watched, event):
476
+ if not isinstance(watched, QToolButton):
477
+ return super().eventFilter(watched, event)
478
+
479
+ key = id(watched)
480
+ if event.type() == QEvent.Type.MouseButtonPress and event.button() == Qt.LeftButton:
481
+ self._drag_start[key] = event.position().toPoint()
482
+ self._dragging[key] = False
483
+ elif event.type() == QEvent.Type.MouseMove:
484
+ start = self._drag_start.get(key)
485
+ if (
486
+ start is not None
487
+ and not self._dragging.get(key, False)
488
+ and (event.position().toPoint() - start).manhattanLength()
489
+ >= DOCK_BUTTON_DRAG_THRESHOLD
490
+ ):
491
+ self._dragging[key] = True
492
+ watched.setDown(False)
493
+ self._start_drag(watched)
494
+ return True
495
+ elif event.type() == QEvent.Type.MouseButtonRelease:
496
+ self._drag_start.pop(key, None)
497
+ if self._dragging.pop(key, False):
498
+ event.accept()
499
+ return True
500
+ return super().eventFilter(watched, event)
501
+
502
+ def _start_drag(self, button: QToolButton):
503
+ dock_id = button.property("dock_id")
504
+ if not dock_id:
505
+ return
506
+
507
+ pixmap = button.grab()
508
+ mime = QMimeData()
509
+ mime.setData(DOCK_BUTTON_MIME_TYPE, QByteArray(str(dock_id).encode()))
510
+
511
+ drag = QDrag(button)
512
+ drag.setMimeData(mime)
513
+ drag.setPixmap(pixmap)
514
+ drag.setHotSpot(QPoint(pixmap.width() // 2, pixmap.height() // 2))
515
+ drag.exec(Qt.MoveAction)
516
+
517
+
518
+ # ══════════════════════════════════════════════════════════════════
519
+ # ToolbarSeparator
520
+ # ══════════════════════════════════════════════════════════════════
521
+
522
+ class ToolbarSeparator(QFrame):
523
+ def __init__(self, parent=None):
524
+ super().__init__(parent)
525
+ self.setFixedHeight(1)
526
+ self.setFrameShape(QFrame.HLine)
527
+ self.setStyleSheet("background: palette(mid); margin: 2px 4px;")
528
+
529
+
530
+ # ══════════════════════════════════════════════════════════════════
531
+ # VerticalToolbar
532
+ # ══════════════════════════════════════════════════════════════════
533
+
534
+ class VerticalToolbar(QWidget):
535
+ INDICATOR_H = 2
536
+
537
+ def __init__(self, side: ToolbarSide,
538
+ manager_ref: "Optional[DockManager]" = None,
539
+ parent=None):
540
+ super().__init__(parent)
541
+ self.side = side
542
+ self._manager = manager_ref
543
+ self._indicator: Optional[QFrame] = None
544
+
545
+ self.setFixedWidth(TOOLBAR_COLLAPSED_WIDTH)
546
+ self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
547
+ self.setStyleSheet("background: palette(window);")
548
+ self.setAcceptDrops(True)
549
+
550
+ outer = QVBoxLayout(self)
551
+ outer.setContentsMargins(0, 4, 0, 4)
552
+ outer.setSpacing(5)
553
+
554
+ self._top_widget = QWidget()
555
+ self._top_layout = QVBoxLayout(self._top_widget)
556
+ self._top_layout.setContentsMargins(4, 0, 4, 0)
557
+ self._top_layout.setSpacing(5)
558
+ self._top_layout.setAlignment(Qt.AlignTop)
559
+
560
+ self._separator = ToolbarSeparator()
561
+
562
+ self._middle_widget = QWidget()
563
+ self._middle_layout = QVBoxLayout(self._middle_widget)
564
+ self._middle_layout.setContentsMargins(4, 4, 4, 0)
565
+ self._middle_layout.setSpacing(5)
566
+ self._middle_layout.setAlignment(Qt.AlignTop)
567
+
568
+ self._bottom_widget = QWidget()
569
+ self._bottom_layout = QVBoxLayout(self._bottom_widget)
570
+ self._bottom_layout.setContentsMargins(4, 0, 4, 0)
571
+ self._bottom_layout.setSpacing(5)
572
+ self._bottom_layout.setAlignment(Qt.AlignBottom)
573
+
574
+ outer.addWidget(self._top_widget)
575
+ outer.addWidget(self._separator)
576
+ outer.addWidget(self._middle_widget)
577
+ outer.addStretch(1)
578
+ outer.addWidget(self._bottom_widget)
579
+ self._update_separator_visibility()
580
+ self._install_context_menu_target(self)
581
+ self._install_context_menu_target(self._top_widget)
582
+ self._install_context_menu_target(self._middle_widget)
583
+ self._install_context_menu_target(self._bottom_widget)
584
+ self._install_context_menu_target(self._separator)
585
+
586
+ def layout_for_section(self, section: ToolbarSection) -> QVBoxLayout:
587
+ if section == ToolbarSection.TOP:
588
+ return self._top_layout
589
+ if section == ToolbarSection.MIDDLE:
590
+ return self._middle_layout
591
+ return self._bottom_layout
592
+
593
+ def layout_for_region(self, region: Region) -> QVBoxLayout:
594
+ return self.layout_for_section(region.toolbar_section())
595
+
596
+ def add_button(self, region: Region, button: QToolButton):
597
+ self.layout_for_region(region).addWidget(button)
598
+ self._update_separator_visibility()
599
+
600
+ def remove_button(self, region: Region, button: QToolButton):
601
+ layout = self.layout_for_region(region)
602
+ layout.removeWidget(button)
603
+ button.setParent(None)
604
+ self._update_separator_visibility()
605
+
606
+ def insert_button_before(self, region: Region, button: QToolButton,
607
+ before_id: Optional[str]):
608
+ layout = self.layout_for_region(region)
609
+ if before_id is None:
610
+ layout.addWidget(button)
611
+ self._update_separator_visibility()
612
+ return
613
+ for i in range(layout.count()):
614
+ w = layout.itemAt(i).widget() if layout.itemAt(i) else None
615
+ if _is_dock_button(w) and w.property("dock_id") == before_id:
616
+ layout.insertWidget(i, button)
617
+ self._update_separator_visibility()
618
+ return
619
+ layout.addWidget(button)
620
+ self._update_separator_visibility()
621
+
622
+ def dragEnterEvent(self, event):
623
+ if event.mimeData().hasFormat(DOCK_BUTTON_MIME_TYPE):
624
+ event.acceptProposedAction()
625
+ self._update_indicator(event.position().toPoint())
626
+ else:
627
+ event.ignore()
628
+
629
+ def dragMoveEvent(self, event):
630
+ if event.mimeData().hasFormat(DOCK_BUTTON_MIME_TYPE):
631
+ event.acceptProposedAction()
632
+ self._update_indicator(event.position().toPoint())
633
+ else:
634
+ event.ignore()
635
+
636
+ def dragLeaveEvent(self, event):
637
+ self._remove_indicator()
638
+
639
+ def dropEvent(self, event):
640
+ self._remove_indicator()
641
+ if not event.mimeData().hasFormat(DOCK_BUTTON_MIME_TYPE):
642
+ event.ignore()
643
+ return
644
+
645
+ dock_id = event.mimeData().data(DOCK_BUTTON_MIME_TYPE).toStdString()
646
+ drop_pos = event.position().toPoint()
647
+ section = self._section_at(drop_pos)
648
+ before_id = self._button_after_cursor(drop_pos, section)
649
+
650
+ event.acceptProposedAction()
651
+ if self._manager is not None:
652
+ self._manager.drop_button(dock_id, self, section, before_id)
653
+
654
+ def _update_indicator(self, pos: QPoint):
655
+ section = self._section_at(pos)
656
+ before_id = self._button_after_cursor(pos, section)
657
+ insert_y = self._indicator_y(section, before_id)
658
+
659
+ if self._indicator is None:
660
+ self._indicator = QFrame(self)
661
+ self._indicator.setFixedHeight(self.INDICATOR_H)
662
+ self._indicator.setStyleSheet("background: palette(highlight);")
663
+ self._indicator.setAttribute(Qt.WA_TransparentForMouseEvents)
664
+ self._indicator.show()
665
+ self._indicator.raise_()
666
+
667
+ self._indicator.setGeometry(0, insert_y, self.width(), self.INDICATOR_H)
668
+
669
+ def _remove_indicator(self):
670
+ if self._indicator is not None:
671
+ self._indicator.deleteLater()
672
+ self._indicator = None
673
+
674
+ def _indicator_y(self, section: ToolbarSection, before_id: Optional[str]) -> int:
675
+ layout = self.layout_for_section(section)
676
+ if before_id is None:
677
+ buttons = list(self._iter_buttons(layout))
678
+ if not buttons:
679
+ return self._section_start_y(section)
680
+ last_button = buttons[-1]
681
+ return last_button.mapTo(self, QPoint(0, last_button.height())).y()
682
+ for i in range(layout.count()):
683
+ w = layout.itemAt(i).widget() if layout.itemAt(i) else None
684
+ if _is_dock_button(w) and w.property("dock_id") == before_id:
685
+ return w.mapTo(self, QPoint(0, 0)).y()
686
+ return self._section_start_y(section)
687
+
688
+ def _section_at(self, pos: QPoint) -> ToolbarSection:
689
+ upper_split = (
690
+ self._section_end_y(ToolbarSection.TOP)
691
+ + self._section_start_y(ToolbarSection.MIDDLE)
692
+ ) // 2
693
+ lower_split = (
694
+ self._section_end_y(ToolbarSection.MIDDLE)
695
+ + self._section_start_y(ToolbarSection.BOTTOM)
696
+ ) // 2
697
+ if pos.y() < upper_split:
698
+ return ToolbarSection.TOP
699
+ if pos.y() < lower_split:
700
+ return ToolbarSection.MIDDLE
701
+ return ToolbarSection.BOTTOM
702
+
703
+ def _section_start_y(self, section: ToolbarSection) -> int:
704
+ buttons = list(self._iter_buttons(self.layout_for_section(section)))
705
+ if buttons:
706
+ return buttons[0].mapTo(self, QPoint(0, 0)).y()
707
+ widget = self._widget_for_section(section)
708
+ return widget.mapTo(self, QPoint(0, 0)).y()
709
+
710
+ def _section_end_y(self, section: ToolbarSection) -> int:
711
+ buttons = list(self._iter_buttons(self.layout_for_section(section)))
712
+ if buttons:
713
+ last_button = buttons[-1]
714
+ return last_button.mapTo(self, QPoint(0, last_button.height())).y()
715
+ return self._section_start_y(section)
716
+
717
+ def _button_after_cursor(self, pos: QPoint,
718
+ section: ToolbarSection) -> Optional[str]:
719
+ layout = self.layout_for_section(section)
720
+ for w in self._iter_buttons(layout):
721
+ btn_mid_y = w.mapTo(self, QPoint(0, w.height() // 2)).y()
722
+ if pos.y() < btn_mid_y:
723
+ return w.property("dock_id")
724
+ return None
725
+
726
+ def _widget_for_section(self, section: ToolbarSection) -> QWidget:
727
+ if section == ToolbarSection.TOP:
728
+ return self._top_widget
729
+ if section == ToolbarSection.MIDDLE:
730
+ return self._middle_widget
731
+ return self._bottom_widget
732
+
733
+ def _iter_buttons(self, layout: QVBoxLayout):
734
+ for i in range(layout.count()):
735
+ w = layout.itemAt(i).widget() if layout.itemAt(i) else None
736
+ if _is_dock_button(w):
737
+ yield w
738
+
739
+ def _layout_has_buttons(self, layout: QVBoxLayout) -> bool:
740
+ return any(True for _ in self._iter_buttons(layout))
741
+
742
+ def _update_separator_visibility(self):
743
+ self._separator.setVisible(
744
+ self._layout_has_buttons(self._top_layout)
745
+ and self._layout_has_buttons(self._middle_layout)
746
+ )
747
+
748
+ def set_show_tool_names(self, show: bool):
749
+ self.setFixedWidth(
750
+ TOOLBAR_EXPANDED_WIDTH if show else TOOLBAR_COLLAPSED_WIDTH
751
+ )
752
+
753
+ def _install_context_menu_target(self, widget: QWidget):
754
+ widget.setContextMenuPolicy(Qt.CustomContextMenu)
755
+ widget.customContextMenuRequested.connect(
756
+ lambda pos, target=widget: self._show_context_menu_for_target(target, pos)
757
+ )
758
+
759
+ def _show_context_menu_for_target(self, target: QWidget, pos: QPoint):
760
+ global_pos = target.mapToGlobal(pos)
761
+ local_pos = self.mapFromGlobal(global_pos)
762
+ child = self.childAt(local_pos)
763
+ if _is_dock_button(child):
764
+ return
765
+ if self._manager is not None:
766
+ self._manager.show_toolbar_context_menu(global_pos)
767
+
768
+
769
+ # ══════════════════════════════════════════════════════════════════
770
+ # DockManager
771
+ # ══════════════════════════════════════════════════════════════════
772
+
773
+ class DockManager:
774
+ def __init__(self, mw: QMainWindow):
775
+ self.mw = mw
776
+ self.entries: Dict[str, DockEntry] = {}
777
+ self.docks: Dict[str, MSDockWidget] = {}
778
+ self.buttons: Dict[str, QToolButton] = {}
779
+ # Standalone action buttons (no dock): a click runs a callback instead of toggling a dock.
780
+ # action_id -> {"region", "order", "button"}. Re-added on every _build_toolbars().
781
+ self.action_buttons: Dict[str, dict] = {}
782
+ self.region_states: Dict[Region, RegionState] = {
783
+ region: RegionState(order=[], visible=[]) for region in Region
784
+ }
785
+ self._region_defaults: Dict[Region, tuple[Behavior, BottomMode]] = {}
786
+ self._show_tool_names = False
787
+ self._bottom_rebuild_pending = False
788
+ self._lateral_rebuild_pending = False
789
+ # When True the BOTTOM_* regions stack at the bottom of their side's vertical column
790
+ # instead of the shared full-width bottom strip, so the central widget spans full height.
791
+ self._bottom_in_lateral = False
792
+ self._button_drag_filter = DockButtonDragFilter(mw)
793
+ # A windowed dock is visible independently of the exclusive/tab state of
794
+ # the region it came from. This lets users keep (for example) PyMOL on a
795
+ # second monitor while opening another tool in the original side panel.
796
+ self._windowed: set[str] = set()
797
+ self._moving_window_id: str | None = None
798
+ self._native_move_poll = QTimer(mw)
799
+ self._native_move_poll.setInterval(30)
800
+ self._native_move_poll.timeout.connect(self._poll_native_window_move)
801
+
802
+ # ── FIX P2: single flag that blocks ALL reactive handlers ──
803
+ # While True, _on_dock_visibility_changed and
804
+ # _on_dock_location_changed do nothing.
805
+ self._updating = False
806
+
807
+ self.left_toolbar = VerticalToolbar(ToolbarSide.LEFT, self, mw)
808
+ self.right_toolbar = VerticalToolbar(ToolbarSide.RIGHT, self, mw)
809
+ self._add_toolbar_widget(self.left_toolbar, Qt.LeftToolBarArea)
810
+ self._add_toolbar_widget(self.right_toolbar, Qt.RightToolBarArea)
811
+
812
+ self._bottom_left_anchor: Optional[str] = None
813
+ self._bottom_right_anchor: Optional[str] = None
814
+
815
+ # ── Registro ────────────────────────────────────────────────
816
+
817
+ def add_dock(
818
+ self,
819
+ dock: MSDockWidget,
820
+ *,
821
+ dock_id: str,
822
+ region: Region,
823
+ order: int,
824
+ behavior: Behavior,
825
+ title: Optional[str] = None,
826
+ icon: Optional[QIcon] = None,
827
+ starts_visible: bool = False,
828
+ bottom_mode: BottomMode = BottomMode.SHARE,
829
+ ) -> None:
830
+ if not isinstance(dock, MSDockWidget):
831
+ raise TypeError("DockManager.add_dock requires an MSDockWidget instance")
832
+ if dock_id in self.entries:
833
+ raise ValueError(f"Duplicate dock id: {dock_id}")
834
+
835
+ entry = DockEntry(
836
+ id=dock_id,
837
+ dock=dock,
838
+ title=title or dock.windowTitle() or dock_id,
839
+ region=region,
840
+ order=order,
841
+ behavior=behavior,
842
+ icon=icon,
843
+ starts_visible=starts_visible,
844
+ bottom_mode=bottom_mode,
845
+ )
846
+ self.entries[dock_id] = entry
847
+ self.docks[dock_id] = dock
848
+
849
+ state = self.region_states[region]
850
+ state.order.append(dock_id)
851
+ if starts_visible:
852
+ state.visible.append(dock_id)
853
+ self._region_defaults.setdefault(region, (behavior, bottom_mode))
854
+
855
+ for region_key in Region:
856
+ self._sort_region_state(region_key)
857
+
858
+ def add_action_button(
859
+ self,
860
+ action_id: str,
861
+ *,
862
+ region: Region,
863
+ order: int,
864
+ on_click,
865
+ title: str = "",
866
+ icon: Optional[QIcon] = None,
867
+ tooltip: Optional[str] = None,
868
+ checkable: bool = False,
869
+ ) -> QToolButton:
870
+ """Add a standalone action button to a toolbar region — NOT a dock. Ordered among the
871
+ region's dock buttons by ``order`` and re-added on every toolbar rebuild, so it survives
872
+ drag/drop and toggles.
873
+
874
+ Non-checkable (default): a click runs ``on_click()``.
875
+ Checkable: the button toggles (shows the :checked accent) and ``on_click(checked: bool)``
876
+ is called with the new state — use it to mirror a tab/panel that the action governs.
877
+ """
878
+ if action_id in self.action_buttons:
879
+ raise ValueError(f"Action button id duplicado: {action_id}")
880
+ button = _create_toolbar_button(title or action_id, icon)
881
+ button.setCheckable(bool(checkable))
882
+ if tooltip:
883
+ button.setToolTip(tooltip)
884
+ if checkable:
885
+ button.toggled.connect(lambda checked: on_click(checked))
886
+ else:
887
+ button.clicked.connect(lambda _checked=False: on_click())
888
+ self.action_buttons[action_id] = {"region": region, "order": int(order), "button": button}
889
+ self._build_toolbars()
890
+ return button
891
+
892
+ # ── Build ────────────────────────────────────────────────────
893
+
894
+ def build(self):
895
+ ordered = sorted(self.entries.values(), key=self._sort_key)
896
+
897
+ for entry in ordered:
898
+ self._configure_dock(entry)
899
+ button = _create_toolbar_button(entry.title, entry.icon)
900
+ button.setProperty("dock_id", entry.id)
901
+ self._button_drag_filter.register(button)
902
+ button.setContextMenuPolicy(Qt.CustomContextMenu)
903
+ button.customContextMenuRequested.connect(
904
+ lambda pos, did=entry.id, btn=button: self.show_button_context_menu(btn, did, pos)
905
+ )
906
+ button.toggled.connect(
907
+ lambda checked, did=entry.id: self.toggle(did, checked)
908
+ )
909
+ self.buttons[entry.id] = button
910
+
911
+ self._build_toolbars()
912
+ self.set_show_tool_names(self._show_tool_names)
913
+ self._init_bottom_anchors()
914
+
915
+ self._apply_all_region_visibility()
916
+ self._schedule_lateral_rebuild()
917
+ self._schedule_bottom_rebuild()
918
+ self.sync_buttons()
919
+
920
+ def _configure_dock(self, entry: DockEntry) -> None:
921
+ dock = entry.dock
922
+ dock.setObjectName(entry.id)
923
+ dock.setWindowTitle(entry.title)
924
+ if dock.parent() is not self.mw:
925
+ dock.setParent(self.mw)
926
+ content = dock.widget()
927
+ if content is None:
928
+ raise ValueError(f"Dock '{entry.id}' must have a widget configured before build")
929
+ dock.setFeatures(
930
+ QDockWidget.DockWidgetMovable |
931
+ QDockWidget.DockWidgetFloatable |
932
+ QDockWidget.DockWidgetClosable
933
+ )
934
+ self.mw.addDockWidget(self._area_for_region(entry.region), dock)
935
+ dock.hide()
936
+
937
+ dock.visibilityChanged.connect(
938
+ lambda visible, did=entry.id: self._on_dock_visibility_changed(did, visible)
939
+ )
940
+ dock.dockLocationChanged.connect(
941
+ lambda area, did=entry.id: self._on_dock_location_changed(did, area)
942
+ )
943
+ dock.topLevelChanged.connect(
944
+ lambda floating, did=entry.id: self._on_dock_top_level_changed(did, floating)
945
+ )
946
+
947
+ def _on_dock_top_level_changed(self, dock_id: str, floating: bool) -> None:
948
+ dock = self.docks.get(dock_id)
949
+ if dock is None:
950
+ return
951
+ entry = self.entries[dock_id]
952
+ if floating:
953
+ self._windowed.add(dock_id)
954
+ self._remove_region_visible(entry.region, dock_id)
955
+ # Manual dragging/double-clicking may still make Qt enter its utility
956
+ # floating mode. Reset that mode and perform our direct native detach.
957
+ if not (
958
+ dock.parent() is None
959
+ and dock.titleBarWidget() is dock._title_bar
960
+ ):
961
+ QTimer.singleShot(0, lambda did=dock_id: self._make_native_window(did))
962
+ if self._uses_bottom_area(entry.region):
963
+ self._schedule_bottom_rebuild()
964
+ else:
965
+ self._schedule_lateral_rebuild()
966
+ else:
967
+ self._windowed.discard(dock_id)
968
+ if self._updating:
969
+ self.sync_buttons()
970
+ return
971
+ if dock.isVisible():
972
+ self._activate_dock_in_state(dock_id)
973
+ self._apply_region_visibility(entry.region)
974
+ if self._uses_bottom_area(entry.region):
975
+ self._schedule_bottom_rebuild()
976
+ else:
977
+ self._schedule_lateral_rebuild()
978
+ self.sync_buttons()
979
+
980
+ def open_in_window(self, dock_id: str) -> None:
981
+ """Detach a dock as a normal OS window without consuming its old region."""
982
+ dock = self.docks.get(dock_id)
983
+ if dock is None:
984
+ return
985
+ entry = self.entries[dock_id]
986
+ self._windowed.add(dock_id)
987
+ self._remove_region_visible(entry.region, dock_id)
988
+ self._make_native_window(dock_id)
989
+ QTimer.singleShot(0, dock.activateWindow)
990
+ self.sync_buttons()
991
+
992
+ def _make_native_window(self, dock_id: str) -> None:
993
+ """Detach directly, clearing any prior QDockWidget utility-window mode."""
994
+ dock = self.docks.get(dock_id)
995
+ if dock is None:
996
+ return
997
+ was_updating = self._updating
998
+ self._updating = True
999
+ try:
1000
+ if dock.parent() is self.mw and dock.isFloating():
1001
+ dock.setFloating(False)
1002
+ self._windowed.add(dock_id)
1003
+ self._remove_region_visible(self.entries[dock_id].region, dock_id)
1004
+ dock._promote_floating_window()
1005
+ finally:
1006
+ self._updating = was_updating
1007
+ self.sync_buttons()
1008
+
1009
+ def is_windowed(self, dock_id: str) -> bool:
1010
+ return dock_id in self._windowed
1011
+
1012
+ def begin_native_window_drag(
1013
+ self,
1014
+ dock_id: str,
1015
+ global_pos: QPoint,
1016
+ title_offset: QPoint,
1017
+ ) -> bool:
1018
+ """Detach if needed, then delegate movement/snapping to the window manager."""
1019
+ dock = self.docks.get(dock_id)
1020
+ if dock is None:
1021
+ return False
1022
+ if dock_id not in self._windowed:
1023
+ self.open_in_window(dock_id)
1024
+ dock.move(global_pos - title_offset)
1025
+ self._moving_window_id = dock_id
1026
+ self._native_move_poll.start()
1027
+ handle = dock.windowHandle()
1028
+ return bool(handle is not None and handle.startSystemMove())
1029
+
1030
+ def _poll_native_window_move(self) -> None:
1031
+ if QApplication.mouseButtons() & Qt.MouseButton.LeftButton:
1032
+ return
1033
+ self.finish_native_window_drag()
1034
+
1035
+ def finish_native_window_drag(self, global_pos: QPoint | None = None) -> None:
1036
+ """Redock in the original region when a native drag ends over AMDock."""
1037
+ dock_id = self._moving_window_id
1038
+ self._moving_window_id = None
1039
+ self._native_move_poll.stop()
1040
+ if dock_id is None or dock_id not in self._windowed:
1041
+ return
1042
+ cursor_pos = global_pos if global_pos is not None else QCursor.pos()
1043
+ local_pos = self.mw.mapFromGlobal(cursor_pos)
1044
+ if self.mw.isVisible() and self.mw.rect().contains(local_pos):
1045
+ self.dock_to_main_window(dock_id)
1046
+
1047
+ def dock_to_main_window(self, dock_id: str) -> None:
1048
+ """Return a detached dock to its configured region."""
1049
+ dock = self.docks.get(dock_id)
1050
+ if dock is None:
1051
+ return
1052
+ entry = self.entries[dock_id]
1053
+ self._updating = True
1054
+ try:
1055
+ self._windowed.discard(dock_id)
1056
+ self._attach_dock_widget(dock_id)
1057
+ self._activate_dock_in_state(dock_id)
1058
+ self._apply_region_visibility(entry.region)
1059
+ dock.show()
1060
+ dock.raise_()
1061
+ finally:
1062
+ self._updating = False
1063
+ if self._uses_bottom_area(entry.region):
1064
+ self._schedule_bottom_rebuild()
1065
+ else:
1066
+ self._schedule_lateral_rebuild()
1067
+ self.sync_buttons()
1068
+
1069
+ def _attach_dock_widget(self, dock_id: str) -> None:
1070
+ """Restore a native external window to QMainWindow dock ownership."""
1071
+ dock = self.docks[dock_id]
1072
+ dock.hide()
1073
+ if dock.parent() is not self.mw:
1074
+ dock.setParent(self.mw)
1075
+ elif dock.isFloating():
1076
+ dock.setFloating(False)
1077
+ dock.setTitleBarWidget(dock._title_bar)
1078
+ self.mw.addDockWidget(self._area_for_region(self.entries[dock_id].region), dock)
1079
+
1080
+ def close_windowed_docks(self) -> None:
1081
+ """Reattach hidden external windows so they die with the main window."""
1082
+ self._moving_window_id = None
1083
+ self._native_move_poll.stop()
1084
+ self._updating = True
1085
+ try:
1086
+ for dock_id in tuple(self._windowed):
1087
+ dock = self.docks.get(dock_id)
1088
+ if dock is None:
1089
+ continue
1090
+ self._attach_dock_widget(dock_id)
1091
+ dock.hide()
1092
+ self._windowed.clear()
1093
+ finally:
1094
+ self._updating = False
1095
+ self.sync_buttons()
1096
+
1097
+ # ══════════════════════════════════════════════════════════════
1098
+ # FIX P4 / P5 — manual move detection
1099
+ # ══════════════════════════════════════════════════════════════
1100
+
1101
+ def _on_dock_location_changed(self, dock_id: str, area: Qt.DockWidgetArea):
1102
+ """
1103
+ Fires when the user drags a dock to another area.
1104
+ We infer the sub-region (lateral TOP vs BOTTOM) with a singleShot
1105
+ so Qt has time to settle the layout.
1106
+ """
1107
+ if self._updating:
1108
+ return
1109
+ # Ignore if the dock has just floated (invalid area)
1110
+ if area == Qt.NoDockWidgetArea:
1111
+ return
1112
+ QTimer.singleShot(0, lambda: self._infer_and_update_region(dock_id, area))
1113
+
1114
+ def _infer_and_update_region(self, dock_id: str, area: Qt.DockWidgetArea):
1115
+ """
1116
+ Infer the Region (sub-region) of a dock after a manual move, update the
1117
+ internal record and move the toolbar button.
1118
+ It does not call removeDockWidget/addDockWidget because Qt already moved it.
1119
+ """
1120
+ dock = self.docks.get(dock_id)
1121
+ if dock is None or dock.isFloating():
1122
+ return
1123
+
1124
+ entry = self.entries[dock_id]
1125
+ old_region = entry.region
1126
+
1127
+ # Determine the new Region from the Qt area
1128
+ new_region = self._infer_region_from_geometry(dock_id, area)
1129
+ if new_region == old_region:
1130
+ return # No real change
1131
+
1132
+ # Update internal state without touching the Qt layout
1133
+ self._updating = True
1134
+ try:
1135
+ was_visible = dock_id in self.region_states[old_region].visible
1136
+
1137
+ new_behavior, new_bottom_mode = self._defaults_for_region(new_region)
1138
+ self._remove_from_region_state(old_region, dock_id)
1139
+ entry.region = new_region
1140
+ entry.behavior = new_behavior
1141
+ entry.bottom_mode = new_bottom_mode
1142
+ self._insert_into_region_state(new_region, dock_id)
1143
+ if was_visible:
1144
+ self._activate_dock_in_state(dock_id)
1145
+
1146
+ # Move the toolbar button (FIX P5)
1147
+ self._build_toolbars()
1148
+
1149
+ if self._uses_bottom_area(new_region) or self._uses_bottom_area(old_region):
1150
+ self._init_bottom_anchors()
1151
+ self._schedule_bottom_rebuild()
1152
+ else:
1153
+ self._schedule_lateral_rebuild()
1154
+
1155
+ self.sync_buttons()
1156
+ finally:
1157
+ self._updating = False
1158
+
1159
+ def _infer_region_from_geometry(self, dock_id: str,
1160
+ area: Qt.DockWidgetArea) -> Region:
1161
+ """
1162
+ Given the Qt area and the dock's current geometry, infer the sub-region.
1163
+ For lateral areas it compares the dock's Y centre with the window's Y
1164
+ centre to decide TOP vs BOTTOM.
1165
+ For the bottom area it decides LEFT vs RIGHT by the X centre.
1166
+ """
1167
+ dock = self.docks[dock_id]
1168
+ geo = dock.geometry()
1169
+
1170
+ if area == Qt.DockWidgetArea.BottomDockWidgetArea:
1171
+ mw_center_x = self.mw.width() / 2
1172
+ return Region.BOTTOM_LEFT if geo.center().x() < mw_center_x else Region.BOTTOM_RIGHT
1173
+
1174
+ mw_center_y = self.mw.height() / 2
1175
+ is_top_half = geo.center().y() < mw_center_y
1176
+
1177
+ if area == Qt.DockWidgetArea.LeftDockWidgetArea:
1178
+ return Region.LEFT_TOP if is_top_half else Region.LEFT_BOTTOM
1179
+ if area == Qt.DockWidgetArea.RightDockWidgetArea:
1180
+ return Region.RIGHT_TOP if is_top_half else Region.RIGHT_BOTTOM
1181
+
1182
+ # Fallback: keep the current region
1183
+ return self.entries[dock_id].region
1184
+
1185
+ # ══════════════════════════════════════════════════════════════
1186
+ # move_to (FIX P3 + P2)
1187
+ # ══════════════════════════════════════════════════════════════
1188
+
1189
+ def move_to(self, dock_id: str, new_region: Region):
1190
+ """
1191
+ Move the dock to new_region via menu or button drag.
1192
+ FIX P3: preserves was_visible and restores visibility with a singleShot
1193
+ so Qt has time to settle the layout.
1194
+ FIX P2: wraps the whole operation in _updating=True so that
1195
+ visibilityChanged / dockLocationChanged do not fire reactive
1196
+ handlers during the relocation.
1197
+ """
1198
+ entry = self.entries[dock_id]
1199
+ old_region = entry.region
1200
+ dock = self.docks[dock_id]
1201
+ was_windowed = dock_id in self._windowed or dock.isFloating()
1202
+ was_visible = (
1203
+ dock.isVisible()
1204
+ if was_windowed
1205
+ else dock_id in self.region_states[old_region].visible
1206
+ )
1207
+
1208
+ if old_region == new_region:
1209
+ if was_windowed:
1210
+ self.dock_to_main_window(dock_id)
1211
+ return
1212
+
1213
+ self._updating = True
1214
+ try:
1215
+ if was_windowed:
1216
+ self._windowed.discard(dock_id)
1217
+ self._attach_dock_widget(dock_id)
1218
+ new_behavior, new_bottom_mode = self._defaults_for_region(new_region)
1219
+
1220
+ # 1. Update internal state
1221
+ self._remove_from_region_state(old_region, dock_id)
1222
+ entry.region = new_region
1223
+ entry.behavior = new_behavior
1224
+ entry.bottom_mode = new_bottom_mode
1225
+ self._insert_into_region_state(new_region, dock_id)
1226
+ if was_visible:
1227
+ self._activate_dock_in_state(dock_id)
1228
+
1229
+ # 2. Relocate the toolbar button
1230
+ self._build_toolbars()
1231
+
1232
+ # 3. Move the QDockWidget to the right Qt area
1233
+ dock.hide()
1234
+ self.mw.removeDockWidget(dock)
1235
+ self.mw.addDockWidget(self._area_for_region(new_region), dock)
1236
+
1237
+ bottom_changed = self._uses_bottom_area(old_region) or self._uses_bottom_area(new_region)
1238
+ if bottom_changed:
1239
+ self._init_bottom_anchors()
1240
+
1241
+ # 4. Apply visibility for both affected regions
1242
+ self._apply_region_visibility(old_region)
1243
+ self._apply_region_visibility(new_region)
1244
+
1245
+ # 5. Rebuild layouts
1246
+ if not self._uses_bottom_area(new_region):
1247
+ self._schedule_lateral_rebuild()
1248
+ if bottom_changed:
1249
+ self._schedule_bottom_rebuild()
1250
+
1251
+ finally:
1252
+ self._updating = False
1253
+
1254
+ # FIX P3: restore visibility AFTER Qt settles the layout.
1255
+ # raise_ also happens outside the _updating block.
1256
+ if was_visible:
1257
+ QTimer.singleShot(0, lambda: self._restore_visible_after_move(dock_id))
1258
+
1259
+ self.sync_buttons()
1260
+
1261
+ def _restore_visible_after_move(self, dock_id: str):
1262
+ """Show and raise the dock after a move_to, outside the _updating lock."""
1263
+ dock = self.docks.get(dock_id)
1264
+ if dock is None:
1265
+ return
1266
+ self._updating = True
1267
+ try:
1268
+ dock.show()
1269
+ dock.raise_()
1270
+ entry = self.entries[dock_id]
1271
+ self._anchor_in_region(dock_id, entry.region, True)
1272
+ finally:
1273
+ self._updating = False
1274
+ self.sync_buttons()
1275
+
1276
+ # ── _anchor_in_region ────────────────────────────────────────
1277
+
1278
+ def _anchor_in_region(self, dock_id: str, region: Region, was_visible: bool):
1279
+ if region.is_bottom():
1280
+ return
1281
+
1282
+ dock = self.docks[dock_id]
1283
+ region_entries = self._region_entries(region)
1284
+
1285
+ visible_siblings = [
1286
+ self.docks[entry.id]
1287
+ for entry in region_entries
1288
+ if entry.id != dock_id
1289
+ and entry.id not in self._windowed
1290
+ and self.docks[entry.id].isVisible()
1291
+ and not self.docks[entry.id].isFloating()
1292
+ ]
1293
+
1294
+ if visible_siblings:
1295
+ self.mw.tabifyDockWidget(visible_siblings[0], dock)
1296
+ return
1297
+
1298
+ other_region = self._other_lateral_region(region)
1299
+ if other_region is not None:
1300
+ other_visible = [
1301
+ self.docks[entry.id]
1302
+ for entry in self._region_entries(other_region)
1303
+ if entry.id not in self._windowed
1304
+ and self.docks[entry.id].isVisible()
1305
+ and not self.docks[entry.id].isFloating()
1306
+ ]
1307
+ if other_visible:
1308
+ ref = other_visible[0]
1309
+ if region in (Region.LEFT_TOP, Region.RIGHT_TOP):
1310
+ self.mw.splitDockWidget(dock, ref, Qt.Vertical)
1311
+ else:
1312
+ self.mw.splitDockWidget(ref, dock, Qt.Vertical)
1313
+
1314
+ def _other_lateral_region(self, region: Region) -> Optional[Region]:
1315
+ pairs = {
1316
+ Region.LEFT_TOP: Region.LEFT_BOTTOM,
1317
+ Region.LEFT_BOTTOM: Region.LEFT_TOP,
1318
+ Region.RIGHT_TOP: Region.RIGHT_BOTTOM,
1319
+ Region.RIGHT_BOTTOM: Region.RIGHT_TOP,
1320
+ }
1321
+ return pairs.get(region)
1322
+
1323
+ # ── drop_button ──────────────────────────────────────────────
1324
+
1325
+ def drop_button(self, dock_id: str, target_toolbar: VerticalToolbar,
1326
+ section: ToolbarSection, before_id: Optional[str]):
1327
+ entry = self.entries.get(dock_id)
1328
+ if entry is None:
1329
+ return
1330
+
1331
+ new_region = self._region_from_toolbar_section(target_toolbar, section)
1332
+ same_pos = (entry.region == new_region)
1333
+
1334
+ if same_pos:
1335
+ self.reorder(dock_id, new_region, before_id)
1336
+ else:
1337
+ self.move_to(dock_id, new_region)
1338
+ if before_id is not None:
1339
+ self.reorder(dock_id, new_region, before_id)
1340
+
1341
+ def _region_from_toolbar_section(self, toolbar: VerticalToolbar,
1342
+ section: ToolbarSection) -> Region:
1343
+ is_left = toolbar.side == ToolbarSide.LEFT
1344
+ if section == ToolbarSection.TOP:
1345
+ return Region.LEFT_TOP if is_left else Region.RIGHT_TOP
1346
+ if section == ToolbarSection.MIDDLE:
1347
+ return Region.LEFT_BOTTOM if is_left else Region.RIGHT_BOTTOM
1348
+ return Region.BOTTOM_LEFT if is_left else Region.BOTTOM_RIGHT
1349
+
1350
+ # ── reorder ──────────────────────────────────────────────────
1351
+
1352
+ def reorder(self, dock_id: str, region: Region, before_id: Optional[str]):
1353
+ self._insert_into_region_state(region, dock_id, before_id)
1354
+ self._build_toolbars()
1355
+
1356
+ # ── Toolbar/region helpers ───────────────────────────────────
1357
+
1358
+ def _toolbar_for_region(self, region: Region) -> VerticalToolbar:
1359
+ return self.left_toolbar if region.is_left() else self.right_toolbar
1360
+
1361
+ def set_bottom_in_lateral(self, enabled: bool) -> None:
1362
+ """If True, BOTTOM_LEFT/BOTTOM_RIGHT docks live at the bottom of the left/right
1363
+ vertical columns (freeing the central widget to fill full height) instead of the
1364
+ shared full-width bottom strip. Call before build(); a later call re-lays-out."""
1365
+ if self._bottom_in_lateral == enabled:
1366
+ return
1367
+ self._bottom_in_lateral = enabled
1368
+ if not self.docks:
1369
+ return
1370
+ for dock_id, entry in self.entries.items():
1371
+ if entry.region.is_bottom() and dock_id not in self._windowed:
1372
+ dock = self.docks[dock_id]
1373
+ self.mw.removeDockWidget(dock)
1374
+ self.mw.addDockWidget(self._area_for_region(entry.region), dock)
1375
+ self._init_bottom_anchors()
1376
+ self._apply_all_region_visibility()
1377
+ self._schedule_lateral_rebuild()
1378
+ self._schedule_bottom_rebuild()
1379
+ self.sync_buttons()
1380
+
1381
+ def _area_for_region(self, region: Region) -> Qt.DockWidgetArea:
1382
+ if self._bottom_in_lateral and region.is_bottom():
1383
+ return Qt.LeftDockWidgetArea if region == Region.BOTTOM_LEFT else Qt.RightDockWidgetArea
1384
+ return region.qt_area()
1385
+
1386
+ def _uses_bottom_area(self, region: Region) -> bool:
1387
+ """True when the region is laid out in Qt's shared bottom strip (vs. lateralized)."""
1388
+ return region.is_bottom() and not self._bottom_in_lateral
1389
+
1390
+ def _bottom_region_for_side(self, lateral_region: Region) -> Region:
1391
+ return Region.BOTTOM_LEFT if lateral_region.is_left() else Region.BOTTOM_RIGHT
1392
+
1393
+ def _sort_key(self, entry: DockEntry):
1394
+ region_order = {
1395
+ Region.LEFT_TOP: 0,
1396
+ Region.LEFT_BOTTOM: 1,
1397
+ Region.BOTTOM_LEFT: 2,
1398
+ Region.RIGHT_TOP: 3,
1399
+ Region.RIGHT_BOTTOM: 4,
1400
+ Region.BOTTOM_RIGHT: 5,
1401
+ }
1402
+ return (region_order[entry.region], entry.order)
1403
+
1404
+ def _sort_region_state(self, region: Region):
1405
+ state = self.region_states[region]
1406
+ state.order.sort(key=lambda dock_id: self.entries[dock_id].order)
1407
+ order_index = {dock_id: idx for idx, dock_id in enumerate(state.order)}
1408
+ state.visible.sort(key=lambda dock_id: order_index.get(dock_id, 10_000))
1409
+
1410
+ def _remove_from_region_state(self, region: Region, dock_id: str):
1411
+ state = self.region_states[region]
1412
+ if dock_id in state.order:
1413
+ state.order.remove(dock_id)
1414
+ if dock_id in state.visible:
1415
+ state.visible.remove(dock_id)
1416
+
1417
+ def _insert_into_region_state(self, region: Region, dock_id: str,
1418
+ before_id: Optional[str] = None):
1419
+ state = self.region_states[region]
1420
+ if dock_id in state.order:
1421
+ state.order.remove(dock_id)
1422
+ if before_id and before_id in state.order:
1423
+ index = state.order.index(before_id)
1424
+ state.order.insert(index, dock_id)
1425
+ else:
1426
+ state.order.append(dock_id)
1427
+ if dock_id in state.visible:
1428
+ state.visible.sort(key=lambda item: state.order.index(item))
1429
+
1430
+ def _set_region_visible(self, region: Region, dock_ids: List[str]):
1431
+ state = self.region_states[region]
1432
+ unique_ids = [dock_id for dock_id in state.order if dock_id in dock_ids]
1433
+ state.visible = unique_ids
1434
+
1435
+ def _add_region_visible(self, region: Region, dock_id: str):
1436
+ state = self.region_states[region]
1437
+ if dock_id not in state.visible:
1438
+ state.visible.append(dock_id)
1439
+ state.visible.sort(key=lambda item: state.order.index(item))
1440
+
1441
+ def _remove_region_visible(self, region: Region, dock_id: str):
1442
+ state = self.region_states[region]
1443
+ if dock_id in state.visible:
1444
+ state.visible.remove(dock_id)
1445
+
1446
+ def _activate_dock_in_state(self, dock_id: str):
1447
+ entry = self.entries[dock_id]
1448
+ region = entry.region
1449
+ state = self.region_states[region]
1450
+
1451
+ if self._uses_bottom_area(region):
1452
+ if entry.bottom_mode == BottomMode.SHARE:
1453
+ self._set_region_visible(region, [dock_id])
1454
+ else:
1455
+ self._add_region_visible(region, dock_id)
1456
+ return
1457
+
1458
+ if entry.behavior in (Behavior.EXCLUSIVE, Behavior.MIXED_EXCLUSIVE):
1459
+ self._set_region_visible(region, [dock_id])
1460
+ return
1461
+
1462
+ visible = [
1463
+ visible_id for visible_id in state.visible
1464
+ if self.entries[visible_id].behavior != Behavior.MIXED_EXCLUSIVE
1465
+ ]
1466
+ if dock_id not in visible:
1467
+ visible.append(dock_id)
1468
+ self._set_region_visible(region, visible)
1469
+
1470
+ def _deactivate_dock_in_state(self, dock_id: str):
1471
+ entry = self.entries[dock_id]
1472
+ self._remove_region_visible(entry.region, dock_id)
1473
+
1474
+ def _apply_region_visibility(self, region: Region):
1475
+ state = self.region_states[region]
1476
+ visible_ids = set(state.visible)
1477
+ for dock_id in state.order:
1478
+ dock = self.docks[dock_id]
1479
+ if dock_id in self._windowed:
1480
+ continue
1481
+ if dock_id in visible_ids:
1482
+ dock.show()
1483
+ else:
1484
+ dock.hide()
1485
+
1486
+ def _apply_all_region_visibility(self):
1487
+ for region in Region:
1488
+ self._apply_region_visibility(region)
1489
+
1490
+ def populate_move_menu(self, menu: QMenu, dock_id: str):
1491
+ entry = self.entries.get(dock_id)
1492
+ if entry is None:
1493
+ menu.addAction("(unknown dock)").setEnabled(False)
1494
+ return
1495
+
1496
+ destinations = [
1497
+ ("Left Top", Region.LEFT_TOP),
1498
+ ("Left Bottom", Region.LEFT_BOTTOM),
1499
+ ("Bottom Left", Region.BOTTOM_LEFT),
1500
+ ("Right Top", Region.RIGHT_TOP),
1501
+ ("Right Bottom", Region.RIGHT_BOTTOM),
1502
+ ("Bottom Right", Region.BOTTOM_RIGHT),
1503
+ ]
1504
+
1505
+ for label, region in destinations:
1506
+ act = QAction(label, menu)
1507
+ act.setCheckable(True)
1508
+ act.setChecked(entry.region == region)
1509
+ act.triggered.connect(
1510
+ lambda checked=False, r=region, did=dock_id:
1511
+ QTimer.singleShot(0, lambda: self.move_to(did, r))
1512
+ )
1513
+ menu.addAction(act)
1514
+
1515
+ def show_button_context_menu(self, button: QToolButton, dock_id: str, pos: QPoint):
1516
+ menu = QMenu(button)
1517
+ menu.setStyleSheet(MENU_STYLE_SHEET)
1518
+ window_action = menu.addAction(
1519
+ "Dock to Main Window" if self.docks[dock_id].isFloating() else "Open in Window"
1520
+ )
1521
+ if self.docks[dock_id].isFloating():
1522
+ window_action.triggered.connect(
1523
+ lambda checked=False, did=dock_id: self.dock_to_main_window(did)
1524
+ )
1525
+ else:
1526
+ window_action.triggered.connect(
1527
+ lambda checked=False, did=dock_id: self.open_in_window(did)
1528
+ )
1529
+ menu.addSeparator()
1530
+ move_menu = menu.addMenu("Move to")
1531
+ move_menu.setStyleSheet(MENU_STYLE_SHEET)
1532
+ self.populate_move_menu(move_menu, dock_id)
1533
+ menu.exec(button.mapToGlobal(pos))
1534
+
1535
+ def show_toolbar_context_menu(self, global_pos: QPoint):
1536
+ menu = QMenu(self.mw)
1537
+ menu.setStyleSheet(MENU_STYLE_SHEET)
1538
+ action = QAction("Show Tool Names", menu)
1539
+ action.setCheckable(True)
1540
+ action.setChecked(self._show_tool_names)
1541
+ action.toggled.connect(self.set_show_tool_names)
1542
+ menu.addAction(action)
1543
+ menu.exec(global_pos)
1544
+
1545
+ def set_show_tool_names(self, show: bool):
1546
+ self.set_button_style(
1547
+ Qt.ToolButtonStyle.ToolButtonTextUnderIcon
1548
+ if show else Qt.ToolButtonStyle.ToolButtonIconOnly
1549
+ )
1550
+
1551
+ def _all_toolbar_buttons(self):
1552
+ yield from self.buttons.values()
1553
+ yield from (entry["button"] for entry in self.action_buttons.values())
1554
+
1555
+ def set_button_style(
1556
+ self,
1557
+ style: Qt.ToolButtonStyle,
1558
+ *,
1559
+ icon_px: int = 24,
1560
+ font_px: int | None = None,
1561
+ width: int | None = None,
1562
+ ):
1563
+ """Icon-only / icon+text / text-only for every button in the side toolbars — dock
1564
+ buttons *and* action buttons (set_show_tool_names only ever reached the dock ones).
1565
+ Font goes through setFont, not a stylesheet, so it doesn't clobber the button's own
1566
+ palette-driven QSS. ``width`` overrides the toolbar width, which the collapsed/expanded
1567
+ defaults get wrong for text-only labels."""
1568
+ icon_only = style == Qt.ToolButtonStyle.ToolButtonIconOnly
1569
+ self._show_tool_names = not icon_only
1570
+ toolbar_width = width or (
1571
+ TOOLBAR_COLLAPSED_WIDTH if icon_only else TOOLBAR_EXPANDED_WIDTH
1572
+ )
1573
+ for toolbar in (self.left_toolbar, self.right_toolbar):
1574
+ toolbar.setFixedWidth(toolbar_width)
1575
+ wrap = style == Qt.ToolButtonStyle.ToolButtonTextUnderIcon
1576
+ for button in self._all_toolbar_buttons():
1577
+ button.setToolButtonStyle(style)
1578
+ button.setIconSize(QSize(icon_px, icon_px))
1579
+ # QToolButton elides ("Molec…Tools") instead of wrapping; it only breaks on an
1580
+ # explicit newline, so under-icon labels wrap on their spaces.
1581
+ title = str(button.property("full_title") or button.text())
1582
+ button.setText(title.replace(" ", "\n") if wrap else title)
1583
+ if font_px:
1584
+ font = button.font()
1585
+ font.setPixelSize(int(font_px))
1586
+ button.setFont(font)
1587
+
1588
+ def _defaults_for_region(self, region: Region) -> tuple[Behavior, BottomMode]:
1589
+ defaults = self._region_defaults.get(region)
1590
+ if defaults is not None:
1591
+ return defaults
1592
+
1593
+ fallback = {
1594
+ Region.LEFT_TOP: (Behavior.EXCLUSIVE, BottomMode.SHARE),
1595
+ Region.LEFT_BOTTOM: (Behavior.MIXED_TAB, BottomMode.SHARE),
1596
+ Region.BOTTOM_LEFT: (Behavior.EXCLUSIVE, BottomMode.STACK),
1597
+ Region.RIGHT_TOP: (Behavior.EXCLUSIVE, BottomMode.SHARE),
1598
+ Region.RIGHT_BOTTOM: (Behavior.MIXED_TAB, BottomMode.SHARE),
1599
+ Region.BOTTOM_RIGHT: (Behavior.EXCLUSIVE, BottomMode.STACK),
1600
+ }
1601
+ return fallback[region]
1602
+
1603
+ def _region_entries(self, region: Region) -> List[DockEntry]:
1604
+ return [self.entries[dock_id] for dock_id in self.region_states[region].order]
1605
+
1606
+ # ── Build toolbars ────────────────────────────────────────────
1607
+
1608
+ def _build_toolbars(self):
1609
+ self._clear_toolbar(self.left_toolbar)
1610
+ self._clear_toolbar(self.right_toolbar)
1611
+ for region_group, toolbar in (
1612
+ ([Region.LEFT_TOP, Region.LEFT_BOTTOM,
1613
+ Region.BOTTOM_LEFT], self.left_toolbar),
1614
+ ([Region.RIGHT_TOP, Region.RIGHT_BOTTOM,
1615
+ Region.BOTTOM_RIGHT], self.right_toolbar),
1616
+ ):
1617
+ for region in region_group:
1618
+ # dock buttons keep their (possibly drag-set) region order; standalone action
1619
+ # buttons are woven in by their `order` relative to the dock entries' orders.
1620
+ merged = [(entry.order, self.buttons[entry.id]) for entry in self._region_entries(region)]
1621
+ for action in self.action_buttons.values():
1622
+ if action["region"] != region:
1623
+ continue
1624
+ idx = next((i for i, (order, _) in enumerate(merged) if order > action["order"]), len(merged))
1625
+ merged.insert(idx, (action["order"], action["button"]))
1626
+ for _order, button in merged:
1627
+ toolbar.add_button(region, button)
1628
+
1629
+ def _clear_toolbar(self, toolbar: VerticalToolbar):
1630
+ for region in (Region.LEFT_TOP, Region.LEFT_BOTTOM, Region.BOTTOM_LEFT,
1631
+ Region.RIGHT_TOP, Region.RIGHT_BOTTOM, Region.BOTTOM_RIGHT):
1632
+ if self._toolbar_for_region(region) is not toolbar:
1633
+ continue
1634
+ layout = toolbar.layout_for_region(region)
1635
+ while layout.count():
1636
+ item = layout.takeAt(0)
1637
+ widget = item.widget()
1638
+ if widget is not None:
1639
+ widget.setParent(None)
1640
+ toolbar._update_separator_visibility()
1641
+
1642
+ def _add_toolbar_widget(self, widget: VerticalToolbar, area):
1643
+ tb = QToolBar()
1644
+ tb.setMovable(False)
1645
+ tb.setFloatable(False)
1646
+ tb.setContextMenuPolicy(Qt.PreventContextMenu)
1647
+ tb.setStyleSheet(
1648
+ "QToolBar { border: none; background: palette(window); padding: 0; spacing: 0; }"
1649
+ )
1650
+ tb.setOrientation(Qt.Orientation.Vertical)
1651
+ tb.addWidget(widget)
1652
+ self.mw.addToolBar(area, tb)
1653
+
1654
+ # ══════════════════════════════════════════════════════════════
1655
+ # Bottom anchors + rebuild (FIX P1 + P2)
1656
+ # ══════════════════════════════════════════════════════════════
1657
+
1658
+ def _init_bottom_anchors(self):
1659
+ left = self.region_states[Region.BOTTOM_LEFT].order
1660
+ right = self.region_states[Region.BOTTOM_RIGHT].order
1661
+ self._bottom_left_anchor = left[0] if left else None
1662
+ self._bottom_right_anchor = right[0] if right else None
1663
+
1664
+ def _schedule_bottom_rebuild(self):
1665
+ if self._bottom_rebuild_pending:
1666
+ return
1667
+ self._bottom_rebuild_pending = True
1668
+ QTimer.singleShot(0, self._rebuild_bottom_layouts)
1669
+
1670
+ def _rebuild_bottom_layouts(self):
1671
+ """
1672
+ Rebuild the bottom area.
1673
+ Adjusted to avoid the segfault spotted under GDB.
1674
+ """
1675
+ self._bottom_rebuild_pending = False
1676
+
1677
+ if self._bottom_in_lateral:
1678
+ return
1679
+
1680
+ if not self._bottom_docks_in_order():
1681
+ return
1682
+
1683
+ self._updating = True
1684
+
1685
+ # --- CRITICAL FIX ---
1686
+ # Save the current options and DISABLE animations.
1687
+ # This stops any QPropertyAnimation internal to the docks BEFORE we try
1688
+ # to remove the widgets.
1689
+ original_options = self.mw.dockOptions()
1690
+ self.mw.setDockOptions(
1691
+ (original_options | QMainWindow.AllowNestedDocks | QMainWindow.AllowTabbedDocks)
1692
+ & ~QMainWindow.AnimatedDocks
1693
+ )
1694
+
1695
+ try:
1696
+ # 1. Limpieza segura
1697
+ self._reset_bottom_layouts()
1698
+
1699
+ # 2. Re-posicionamiento
1700
+ left_root = self._bottom_root(Region.BOTTOM_LEFT)
1701
+ right_root = self._bottom_root(Region.BOTTOM_RIGHT)
1702
+
1703
+ if left_root and right_root and left_root is not right_root:
1704
+ self.mw.splitDockWidget(left_root, right_root, Qt.Horizontal)
1705
+
1706
+ self._retabify_bottom_region(Region.BOTTOM_LEFT)
1707
+ self._retabify_bottom_region(Region.BOTTOM_RIGHT)
1708
+
1709
+ finally:
1710
+ # Restore the options (including animations if they were on)
1711
+ self.mw.setDockOptions(original_options)
1712
+ self._updating = False
1713
+
1714
+ self.sync_buttons()
1715
+
1716
+ def _visible_bottom_docks(self, region: Region) -> List[QDockWidget]:
1717
+ return [self.docks[dock_id] for dock_id in self.region_states[region].visible]
1718
+
1719
+ def _bottom_docks_in_order(self) -> List[QDockWidget]:
1720
+ docks: List[QDockWidget] = []
1721
+ for region in (Region.BOTTOM_LEFT, Region.BOTTOM_RIGHT):
1722
+ docks.extend(
1723
+ self.docks[dock_id]
1724
+ for dock_id in self.region_states[region].order
1725
+ if dock_id not in self._windowed
1726
+ )
1727
+ return docks
1728
+
1729
+ def _bottom_root(self, region: Region) -> Optional[QDockWidget]:
1730
+ visible = self._visible_bottom_docks(region)
1731
+ if visible:
1732
+ return visible[0]
1733
+
1734
+ anchor_id = (
1735
+ self._bottom_left_anchor
1736
+ if region == Region.BOTTOM_LEFT
1737
+ else self._bottom_right_anchor
1738
+ )
1739
+ if anchor_id is not None and anchor_id not in self._windowed:
1740
+ return self.docks.get(anchor_id)
1741
+ return next(
1742
+ (
1743
+ self.docks[dock_id]
1744
+ for dock_id in self.region_states[region].order
1745
+ if dock_id not in self._windowed
1746
+ ),
1747
+ None,
1748
+ )
1749
+
1750
+ def _reset_bottom_layouts(self):
1751
+ for dock in self._bottom_docks_in_order():
1752
+ dock.hide()
1753
+ self.mw.removeDockWidget(dock)
1754
+ self.mw.addDockWidget(Qt.BottomDockWidgetArea, dock)
1755
+
1756
+ self._apply_region_visibility(Region.BOTTOM_LEFT)
1757
+ self._apply_region_visibility(Region.BOTTOM_RIGHT)
1758
+
1759
+ def _retabify_bottom_region(self, region: Region):
1760
+ visible = self._visible_bottom_docks(region)
1761
+ if len(visible) < 2:
1762
+ return
1763
+ base = visible[0]
1764
+ for dock in visible[1:]:
1765
+ if dock is not base:
1766
+ self.mw.tabifyDockWidget(base, dock)
1767
+
1768
+ # ══════════════════════════════════════════════════════════════
1769
+ # visibilityChanged handler (FIX P2)
1770
+ # ══════════════════════════════════════════════════════════════
1771
+
1772
+ def _on_dock_visibility_changed(self, dock_id: str, visible: bool):
1773
+ """
1774
+ FIX P2: this event is ignored entirely while _updating is True.
1775
+ That breaks the feedback loop that made the buttons flicker.
1776
+ """
1777
+ if self._updating:
1778
+ return
1779
+ if dock_id in self._windowed:
1780
+ self.sync_buttons()
1781
+ return
1782
+ entry = self.entries[dock_id]
1783
+ if visible:
1784
+ self._activate_dock_in_state(dock_id)
1785
+ else:
1786
+ self._deactivate_dock_in_state(dock_id)
1787
+ if self._uses_bottom_area(entry.region):
1788
+ self._schedule_bottom_rebuild()
1789
+ elif entry.region.is_bottom():
1790
+ self._schedule_lateral_rebuild()
1791
+ self.sync_buttons()
1792
+
1793
+ # ══════════════════════════════════════════════════════════════
1794
+ # Toggle (FIX P2)
1795
+ # ══════════════════════════════════════════════════════════════
1796
+
1797
+ def toggle(self, dock_id: str, checked: bool):
1798
+ """
1799
+ FIX P2: we use _updating instead of _in_toggle so a single flag blocks
1800
+ every reactive handler.
1801
+ """
1802
+ if self._updating:
1803
+ return
1804
+ dock = self.docks[dock_id]
1805
+ if dock_id in self._windowed or dock.isFloating():
1806
+ if checked:
1807
+ dock.show()
1808
+ dock.raise_()
1809
+ dock.activateWindow()
1810
+ else:
1811
+ dock.hide()
1812
+ self.sync_buttons()
1813
+ return
1814
+ self._updating = True
1815
+ try:
1816
+ entry = self.entries[dock_id]
1817
+
1818
+ if not checked:
1819
+ self._deactivate_dock_in_state(dock_id)
1820
+ self._apply_region_visibility(entry.region)
1821
+ if self._uses_bottom_area(entry.region):
1822
+ self._schedule_bottom_rebuild()
1823
+ else:
1824
+ self._schedule_lateral_rebuild()
1825
+ self.sync_buttons()
1826
+ return
1827
+
1828
+ if self._uses_bottom_area(entry.region):
1829
+ self._toggle_bottom(dock_id)
1830
+ else:
1831
+ self._toggle_lateral(dock_id)
1832
+
1833
+ self.sync_buttons()
1834
+ finally:
1835
+ self._updating = False
1836
+
1837
+ # ── Toggle lateral ────────────────────────────────────────────
1838
+
1839
+ def _toggle_lateral(self, dock_id: str):
1840
+ entry = self.entries[dock_id]
1841
+ target = self.docks[dock_id]
1842
+ self._activate_dock_in_state(dock_id)
1843
+ self._apply_region_visibility(entry.region)
1844
+ self._schedule_lateral_rebuild()
1845
+ target.raise_()
1846
+
1847
+ def _retabify_region(self, region: Region):
1848
+ visible = [self.docks[dock_id] for dock_id in self.region_states[region].visible]
1849
+ self._retabify_in_order(visible)
1850
+
1851
+ def _schedule_lateral_rebuild(self):
1852
+ if self._lateral_rebuild_pending:
1853
+ return
1854
+ self._lateral_rebuild_pending = True
1855
+ QTimer.singleShot(0, self._rebuild_lateral_layouts)
1856
+
1857
+ def _rebuild_lateral_layouts(self):
1858
+ self._lateral_rebuild_pending = False
1859
+
1860
+ if self._updating:
1861
+ self._schedule_lateral_rebuild()
1862
+ return
1863
+
1864
+ self._updating = True
1865
+ original_options = self.mw.dockOptions()
1866
+ self.mw.setDockOptions(
1867
+ (original_options | QMainWindow.AllowNestedDocks | QMainWindow.AllowTabbedDocks)
1868
+ & ~QMainWindow.AnimatedDocks
1869
+ )
1870
+
1871
+ try:
1872
+ for column in (
1873
+ [Region.LEFT_TOP, Region.LEFT_BOTTOM],
1874
+ [Region.RIGHT_TOP, Region.RIGHT_BOTTOM],
1875
+ ):
1876
+ if self._bottom_in_lateral:
1877
+ column = column + [self._bottom_region_for_side(column[0])]
1878
+
1879
+ # Split each visible section-root under the previous one, top → bottom.
1880
+ prev_root: Optional[QDockWidget] = None
1881
+ for region in column:
1882
+ visible = self._safe_lateral_docks(region)
1883
+ if not visible:
1884
+ continue
1885
+ if prev_root is not None and not self._is_lateral_split_already_ok(
1886
+ prev_root, visible[0]
1887
+ ):
1888
+ self.mw.splitDockWidget(prev_root, visible[0], Qt.Vertical)
1889
+ prev_root = visible[0]
1890
+
1891
+ for region in column:
1892
+ self._retabify_in_order(self._safe_tab_docks(region))
1893
+ finally:
1894
+ self.mw.setDockOptions(original_options)
1895
+ self._updating = False
1896
+
1897
+ self.sync_buttons()
1898
+
1899
+ def _safe_lateral_docks(self, region: Region) -> List[QDockWidget]:
1900
+ area = self._area_for_region(region)
1901
+ docks: List[QDockWidget] = []
1902
+ for dock_id in self.region_states[region].visible:
1903
+ dock = self.docks[dock_id]
1904
+ if dock.isFloating() or not dock.isVisible():
1905
+ continue
1906
+ if self.mw.dockWidgetArea(dock) != area:
1907
+ continue
1908
+ docks.append(dock)
1909
+ return docks
1910
+
1911
+ def _safe_tab_docks(self, region: Region) -> List[QDockWidget]:
1912
+ return [
1913
+ dock
1914
+ for dock_id in self.region_states[region].visible
1915
+ if self.entries[dock_id].behavior == Behavior.MIXED_TAB
1916
+ for dock in [self.docks[dock_id]]
1917
+ if dock.isVisible()
1918
+ and not dock.isFloating()
1919
+ and self.mw.dockWidgetArea(dock) == self._area_for_region(region)
1920
+ ]
1921
+
1922
+ def _is_lateral_split_already_ok(self, top_dock: QDockWidget,
1923
+ bottom_dock: QDockWidget) -> bool:
1924
+ if top_dock is bottom_dock:
1925
+ return True
1926
+ if top_dock.isFloating() or bottom_dock.isFloating():
1927
+ return True
1928
+ if self.mw.dockWidgetArea(top_dock) != self.mw.dockWidgetArea(bottom_dock):
1929
+ return False
1930
+
1931
+ top_geo = top_dock.geometry()
1932
+ bottom_geo = bottom_dock.geometry()
1933
+ if not top_geo.isValid() or not bottom_geo.isValid():
1934
+ return False
1935
+
1936
+ return top_geo.center().y() < bottom_geo.center().y()
1937
+
1938
+ # ── Toggle bottom ─────────────────────────────────────────────
1939
+
1940
+ def _toggle_bottom(self, dock_id: str):
1941
+ entry = self.entries[dock_id]
1942
+ target = self.docks[dock_id]
1943
+ self._activate_dock_in_state(dock_id)
1944
+ self._apply_region_visibility(entry.region)
1945
+ self._schedule_bottom_rebuild()
1946
+ target.raise_()
1947
+
1948
+ # ── Util ──────────────────────────────────────────────────────
1949
+
1950
+ def _retabify_in_order(self, visible_docks: List[QDockWidget]):
1951
+ candidates = [
1952
+ dock for dock in visible_docks
1953
+ if dock.isVisible() and not dock.isFloating()
1954
+ ]
1955
+ if len(candidates) < 2:
1956
+ return
1957
+ base = candidates[0]
1958
+ base_area = self.mw.dockWidgetArea(base)
1959
+ for d in candidates[1:]:
1960
+ if d is not base and self.mw.dockWidgetArea(d) == base_area:
1961
+ self.mw.tabifyDockWidget(base, d)
1962
+
1963
+ def sync_buttons(self, *args):
1964
+ visible_ids = {
1965
+ dock_id
1966
+ for state in self.region_states.values()
1967
+ for dock_id in state.visible
1968
+ }
1969
+ for dock_id, button in self.buttons.items():
1970
+ button.blockSignals(True)
1971
+ button.setChecked(
1972
+ dock_id in visible_ids
1973
+ or (dock_id in self._windowed and self.docks[dock_id].isVisible())
1974
+ )
1975
+ button.blockSignals(False)