datacook-app 2.13.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 (97) hide show
  1. datacook/__init__.py +6 -0
  2. datacook/allocator.py +80 -0
  3. datacook/app/README.md +141 -0
  4. datacook/app/__init__.py +23 -0
  5. datacook/app/__main__.py +7 -0
  6. datacook/app/actions.py +273 -0
  7. datacook/app/application.py +185 -0
  8. datacook/app/bridge.py +119 -0
  9. datacook/app/commands.py +220 -0
  10. datacook/app/controllers/__init__.py +15 -0
  11. datacook/app/controllers/app.py +143 -0
  12. datacook/app/controllers/command.py +108 -0
  13. datacook/app/controllers/node.py +207 -0
  14. datacook/app/controllers/preview.py +254 -0
  15. datacook/app/controllers/project.py +448 -0
  16. datacook/app/docks/__init__.py +1 -0
  17. datacook/app/docks/code.py +160 -0
  18. datacook/app/docks/dataview.py +369 -0
  19. datacook/app/docks/messages.py +329 -0
  20. datacook/app/docks/nodetree.py +588 -0
  21. datacook/app/docks/params.py +323 -0
  22. datacook/app/docks/recipes.py +656 -0
  23. datacook/app/docks/schema.py +320 -0
  24. datacook/app/eventqueue.py +148 -0
  25. datacook/app/jobs.py +187 -0
  26. datacook/app/mainwindow.py +200 -0
  27. datacook/app/pins.py +65 -0
  28. datacook/app/protocols.py +130 -0
  29. datacook/app/settings.py +60 -0
  30. datacook/app/slots.py +145 -0
  31. datacook/app/state.py +148 -0
  32. datacook/app/style.py +277 -0
  33. datacook/app/testing.py +498 -0
  34. datacook/app/uimodules.py +67 -0
  35. datacook/app/widgets/__init__.py +1 -0
  36. datacook/app/widgets/columnchooser.py +355 -0
  37. datacook/app/widgets/memoryindicator.py +133 -0
  38. datacook/app/widgets/overlay.py +99 -0
  39. datacook/app/widgets/readerdialog.py +151 -0
  40. datacook/constants/__init__.py +0 -0
  41. datacook/constants/iconnames.py +128 -0
  42. datacook/core/__init__.py +0 -0
  43. datacook/core/application.py +42 -0
  44. datacook/engine/__init__.py +28 -0
  45. datacook/engine/cache.py +121 -0
  46. datacook/engine/categories.py +30 -0
  47. datacook/engine/codegen.py +124 -0
  48. datacook/engine/events.py +35 -0
  49. datacook/engine/formats.py +205 -0
  50. datacook/engine/frames.py +112 -0
  51. datacook/engine/node.py +39 -0
  52. datacook/engine/ops/__init__.py +38 -0
  53. datacook/engine/ops/base.py +492 -0
  54. datacook/engine/ops/categorical.py +125 -0
  55. datacook/engine/ops/code.py +73 -0
  56. datacook/engine/ops/columns.py +500 -0
  57. datacook/engine/ops/combine.py +229 -0
  58. datacook/engine/ops/dates.py +260 -0
  59. datacook/engine/ops/estimators.py +955 -0
  60. datacook/engine/ops/missing.py +331 -0
  61. datacook/engine/ops/reshape.py +228 -0
  62. datacook/engine/ops/rows.py +258 -0
  63. datacook/engine/ops/series.py +539 -0
  64. datacook/engine/ops/sources.py +258 -0
  65. datacook/engine/ops/stats.py +336 -0
  66. datacook/engine/ops/strings.py +419 -0
  67. datacook/engine/ops/timeseries.py +704 -0
  68. datacook/engine/ops/values.py +141 -0
  69. datacook/engine/parser.py +261 -0
  70. datacook/engine/project.py +75 -0
  71. datacook/engine/recipes.py +585 -0
  72. datacook/engine/registry.py +76 -0
  73. datacook/engine/restructure.py +70 -0
  74. datacook/engine/session.py +720 -0
  75. datacook/engine/timecol.py +76 -0
  76. datacook/i18n.py +78 -0
  77. datacook/locales/datacook.pot +2654 -0
  78. datacook/locales/de/LC_MESSAGES/datacook.mo +0 -0
  79. datacook/locales/de/LC_MESSAGES/datacook.po +4424 -0
  80. datacook/py.typed +0 -0
  81. datacook/resources/darktheme.qss +994 -0
  82. datacook/resources/datetime.parquet +0 -0
  83. datacook/resources/fonts/RobotoMono-Regular.ttf +0 -0
  84. datacook/resources/icon.ico +0 -0
  85. datacook/resources/icon.svg +39 -0
  86. datacook/resources/icons/128x128.png +0 -0
  87. datacook/resources/icons/16x16.png +0 -0
  88. datacook/resources/icons/24x24.png +0 -0
  89. datacook/resources/icons/256x256.png +0 -0
  90. datacook/resources/icons/32x32.png +0 -0
  91. datacook/resources/icons/48x48.png +0 -0
  92. datacook/resources/icons/64x64.png +0 -0
  93. datacook_app-2.13.0.dist-info/METADATA +141 -0
  94. datacook_app-2.13.0.dist-info/RECORD +97 -0
  95. datacook_app-2.13.0.dist-info/WHEEL +4 -0
  96. datacook_app-2.13.0.dist-info/entry_points.txt +116 -0
  97. datacook_app-2.13.0.dist-info/licenses/LICENSE +22 -0
datacook/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """DataCook: tabular data analysis that records every transformation as code."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("datacook-app")
6
+ __title__ = "DataCook"
datacook/allocator.py ADDED
@@ -0,0 +1,80 @@
1
+ """Process-wide allocator setup, so that dropped frames give their memory back to the OS.
2
+
3
+ Measured (3M x 7 frame, 4 steps, then "Free memory"; DATACOOK_PLAN.md, phase 3 memory
4
+ note): after the drop only the cached frames are alive, but with the defaults ~450 MiB of
5
+ freed memory stays resident:
6
+
7
+ - pyarrow's default pool (mimalloc; jemalloc in some builds) keeps freed pages until
8
+ `release_unused()`.
9
+ - With the system pool, glibc serves column buffers from its heaps: its mmap threshold
10
+ grows dynamically (up to 32 MiB) after the first large free, and `malloc_trim` does not
11
+ shrink the heaps of worker-thread arenas.
12
+
13
+ `configure()` makes Arrow use the system allocator and pins glibc's mmap threshold, so every
14
+ buffer from 1 MiB up is its own mapping and is unmapped as soon as its last reference dies.
15
+ `release()` returns what is left in the allocators' free lists. Cost: ~15 % slower on
16
+ allocation-heavy ops (fresh pages are faulted in again).
17
+
18
+ This module does not import pyarrow at import time: Arrow reads `ARROW_DEFAULT_MEMORY_POOL`
19
+ when pyarrow is imported, and `pa.set_memory_pool()` only covers the Python bindings (C++
20
+ internals such as the Parquet reader keep using the pool chosen at import).
21
+ """
22
+
23
+ import ctypes
24
+ import ctypes.util
25
+ import functools
26
+ import os
27
+ import sys
28
+
29
+
30
+ MMAP_THRESHOLD = 1 << 20
31
+ """glibc: allocations from 1 MiB up get their own mapping."""
32
+
33
+ POOL_ENV = "ARROW_DEFAULT_MEMORY_POOL"
34
+ _M_MMAP_THRESHOLD = -3 # glibc malloc.h
35
+
36
+
37
+ @functools.cache
38
+ def _glibc() -> ctypes.CDLL | None:
39
+ if not sys.platform.startswith("linux"):
40
+ return None
41
+ try:
42
+ libc = ctypes.CDLL(ctypes.util.find_library("c") or "libc.so.6")
43
+ libc.mallopt # noqa: B018 (musl has neither)
44
+ libc.malloc_trim # noqa: B018
45
+ except OSError, AttributeError:
46
+ return None
47
+ return libc
48
+
49
+
50
+ def configure(mmap_threshold: int = MMAP_THRESHOLD) -> None:
51
+ """Set up the allocators for a long-lived process; call before pyarrow is imported.
52
+
53
+ Explicit settings win: a set `ARROW_DEFAULT_MEMORY_POOL` keeps the chosen Arrow pool,
54
+ a set `MALLOC_MMAP_THRESHOLD_` keeps glibc's threshold. Calling it again is harmless.
55
+ """
56
+ if POOL_ENV not in os.environ:
57
+ os.environ[POOL_ENV] = "system"
58
+ if "pyarrow" in sys.modules: # too late for Arrow's C++ default: Python side only
59
+ import pyarrow as pa
60
+
61
+ pa.set_memory_pool(pa.system_memory_pool())
62
+ libc = _glibc()
63
+ if libc is not None and "MALLOC_MMAP_THRESHOLD_" not in os.environ:
64
+ libc.mallopt(_M_MMAP_THRESHOLD, mmap_threshold)
65
+
66
+
67
+ def release() -> None:
68
+ """Give memory freed by dropped frames back to the OS (Arrow pools, glibc heaps)."""
69
+ if "pyarrow" in sys.modules:
70
+ import pyarrow as pa
71
+
72
+ for get_pool in (pa.default_memory_pool, pa.mimalloc_memory_pool, pa.jemalloc_memory_pool):
73
+ try:
74
+ pool = get_pool()
75
+ except NotImplementedError: # allocator not in this build
76
+ continue
77
+ pool.release_unused()
78
+ libc = _glibc()
79
+ if libc is not None:
80
+ libc.malloc_trim(0)
datacook/app/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # datacook.app: core API for docks and widgets
2
+
3
+ Design: `DATACOOK_APP_DESIGN.md` (owner's OSS workspace). This file lists what a dock /
4
+ widget uses. Rule of thumb: **docks own widgets only**; they read the session, `AppState`
5
+ and the view slots, write `AppState` and call controllers. They never call
6
+ `Session.add/update/remove/pin/unpin` and never hold a full frame of their own.
7
+
8
+ ## Registering a dock (no shared file to edit)
9
+
10
+ `uimodules.UI_MODULES` already lists every planned module (`docks.dataview`,
11
+ `docks.nodetree`, `docks.code`, `widgets.memoryindicator`, `docks.params`, `actions`,
12
+ `controllers.project`, `docks.schema`, `docks.messages`, `docks.recipes`). Missing modules are skipped, so a
13
+ work package only creates its module. A module may define:
14
+
15
+ ```python
16
+ from datacook.app.uimodules import DockSpec
17
+ from datacook.i18n import _
18
+
19
+
20
+ def create(app: AppController, window: MainWindow) -> QWidget: ...
21
+
22
+
23
+ DOCKS = (DockSpec("nodetree", _("Steps"), "left", create),)
24
+ # area: "left" | "right" | "bottom" | "central" | "status"; tabify_with="<dock id>"
25
+
26
+
27
+ def install(app: AppController, window: MainWindow) -> None:
28
+ """Optional; runs after all docks exist: menus, toolbar, shortcuts."""
29
+ window.menu("file").addAction(...) # keys: file, edit, view, steps, help
30
+ ```
31
+
32
+ `window.docks[id]` (QDockWidget), `window.widgets[id]` (what `create` returned). Dock titles
33
+ are re-read with `str(spec.title)` on `app.state.language_changed`; a dock widget with own
34
+ texts connects to that signal itself (`retranslate()`).
35
+
36
+ ## Modules (what each WP added)
37
+
38
+ | Module | What | Hooks / API for tests and other docks |
39
+ |---|---|---|
40
+ | `docks/nodetree.py` | Steps tree (`NodeTreeModel`: ids + structure only; badges, shape, size); rename (F2), comment, branch, delete (Del), delete one step keeping the following steps (Shift+Del) | `widget.model.index_of(id)`, `widget.view`, `widget.remove_step(id)`, `widget.extra_actions` (more context menu entries) |
41
+ | `docks/dataview.py` | central data view: one `DataFrameViewer` per slot ("node", "preview"), overlays for slot states, display-only sort (permutation on the view pool), "Add as sort step" | `view.page`, `view.viewer`, `view.is_sorting()`, `view.add_sort_step()` |
42
+ | `docks/code.py` | code pane (`CodeController`: one render per event-loop turn, span of the current step highlighted, error markers) | `pane.editor` |
43
+ | `widgets/memoryindicator.py` | status bar: cache / budget / RSS, menu of cached steps, "Free memory" | — |
44
+ | `widgets/overlay.py` | translucent message panel with buttons (slot states) | — |
45
+ | `docks/params.py` | `ParamsPanel`: `PydanticForm` of the open preview (column editors from `widgets/columnchooser.py`), live preview, Apply / Cancel | `panel.form.set_value()`, `panel.apply()`, `panel.cancel()` |
46
+ | `actions.py` | `OpActions` (object name `op-actions`): one `QAction` per op (`op-<id>`), Steps menu by category, command palette (Ctrl+Shift+P), Edit step (Ctrl+E), Cancel preview (Esc) | `ops.start(op_id)`, `ops.choose_input` (second input of a merge) |
47
+ | `controllers/project.py` | `ProjectController` (`window.project`): New / Open / Save (As), recent files, Open data (`widgets/readerdialog.py`), exports (CSV / Parquet / Excel / script), unsaved-changes prompt on close, window title | dialog hooks: `ask_open_path`, `ask_save_path`, `confirm_discard`, `ask_save_changes`, `exec_dialog`, `ask_writer_params` |
48
+ | `docks/schema.py` | Columns dock: `SchemaModel` of the displayed slot, column statistics on the view pool, categories; a hint while no column is selected | `widget.profile`, `widget.hint` |
49
+ | `docks/messages.py` | Messages dock: `app.notify()`, failing steps, `datacook` log records; View > Language (`application.LanguageMenu`) | — |
50
+ | `docks/recipes.py` | Recipes dock (right, tab with Parameters) + Steps > Recipes: `RecipeController` (`window.recipes`): save a step path / subtree as recipe, apply to the current or chosen steps (required columns checked first; unknown schemas computed on the view pool, slot "recipe-check"), run an import recipe / on files, library (rename, description, delete, merge, import, export); one undo macro per apply | `controller.create()`, `apply(recipe, targets)`, `apply_to_chosen()`, `import_files()`, `library` (`engine.recipes.RecipeLibrary`); hooks `ask_text`, `ask_paths`, `ask_save_path`, `ask_targets`, `confirm` |
51
+ | `application.py` | `create_window()`, `main()` (`datacook [project \| data file]`), `set_language()` / `choose_language()` | `open_paths(window, paths)` |
52
+
53
+ The first dock of a tab group is the visible tab (Code before Messages, Parameters before
54
+ Columns). Initial dock sizes: `mainwindow.DOCK_SIZES`.
55
+
56
+ ## Language switch (`application.py`)
57
+
58
+ `set_language(app, code | None)` switches the gettext catalog, Qt's `QTranslator` (qtbase)
59
+ and `app.state.language`; `choose_language(app, code | None)` also stores the choice in the
60
+ settings file (`None` = system language). View > Language (`LanguageMenu`, installed by
61
+ `docks.messages`) calls it and `retranslate()`s every `PydanticForm` in the window; other
62
+ widgets with own texts connect to `app.state.language_changed`. Give cutepandas models /
63
+ widgets `translate=datacook.i18n.translate`.
64
+
65
+ ## `app: AppController` (`controllers/app.py`)
66
+
67
+ | Attribute | What |
68
+ |---|---|
69
+ | `app.session` | `SessionLike` (engine `Session`): `get`, `nodes`, `roots`, `children`, `ancestors`, `descendants`, `summary`, `error`, `memory`, `is_cached`, `render_code` — lock-protected, cheap on the GUI thread. Read only. |
70
+ | `app.state` | `AppState` (below) |
71
+ | `app.bridge` | `SessionBridge`: GUI-thread signals for engine events |
72
+ | `app.commands` | `CommandController`: every mutation, undoable |
73
+ | `app.nodes` | `NodeController`: `nodes.slot` = the "current" `ViewSlot`; `recompute()` |
74
+ | `app.preview` | `PreviewController`: `preview.slot` = the "preview" `ViewSlot` |
75
+ | `app.jobs` | `JobRunner`: `running_ids()`, `submit_view(slot, fn, *args, on_done=)` (view pool) |
76
+ | `app.pins` | `PinBook`: `pinned_ids()` (tree badge "pinned") |
77
+ | `app.held_ids()` | nodes whose full frame a view holds (invariant: ⊆ `pins.pinned_ids()`) |
78
+ | `app.free_memory()` | drop every unpinned cached frame (memory indicator "Free memory") |
79
+ | `app.notify(text, level, node_id)` | user message -> `message_posted(Message)` (messages dock) |
80
+ | `app.new_project()` | empty tree + undo history (project controller) |
81
+ | signals | `jobs_changed()` (job indicator, "computing" badges), `message_posted(Message)` |
82
+
83
+ ## `app.state: AppState` (`state.py`, GUI thread)
84
+
85
+ Properties with a `<name>_changed` signal, emitted only on a real change:
86
+ `current` (node id; `current_changed(old, new)`), `column`, `preview` (`PreviewSpec`: mode
87
+ `add|edit`, `op_id`, `target`, `inputs`, `params`), `display` (`"node" | "preview"`: what the
88
+ data view and schema dock show), `sort` (`SortSpec(column, descending)`: display-only sort,
89
+ reset on selection change), `settings` (`AppSettings`, `update_settings(**changes)`),
90
+ `language` (`language_changed`: retranslate).
91
+
92
+ ## `app.bridge: SessionBridge` (`bridge.py`)
93
+
94
+ Signals (tuples of ids, coalesced per event-loop turn, events of outdated generations
95
+ dropped): `nodes_added`, `nodes_removed` (incl. descendants; may name ids a view never saw),
96
+ `nodes_changed` (params / name / comment), `nodes_moved` (new parents: a middle step was
97
+ deleted or restored; `nodes_invalidated` follows), `nodes_invalidated`, `nodes_materialized`,
98
+ `nodes_evicted`, `node_error(id, exc)` (the failing step), `memory_changed()`,
99
+ `structure_reset()` (> 200 events at once: rebuild from `session.nodes()`), `drained()`.
100
+ `bridge.post(fn, *args)` runs `fn` on the GUI thread (any thread may call it).
101
+
102
+ ## View slots (`slots.py`)
103
+
104
+ `ViewSlot.holder` is a long-lived cutepandas `DataFrameHolder`: bind a viewer / models to it
105
+ once (`DataFrameViewer(app.nodes.slot.holder)`), never call `holder.set_df` yourself.
106
+ `slot.state_changed(state)`; `slot.state` (`SlotState`: `empty`, `loading`, `ready`, `stale`,
107
+ `evicted`, `error`), `node_id`, `generation`, `summary` (last known shape for overlays),
108
+ `error`, `error_node` (failing step, may be an ancestor: "Go to step"), `message` (overlay text,
109
+ e.g. "computing full result…"). The data view shows `app.nodes.slot` or `app.preview.slot`
110
+ depending on `app.state.display`.
111
+
112
+ ## `app.commands: CommandController` (`controllers/command.py`)
113
+
114
+ `add_node(record, parents=(), name=, comment=, node_id=) -> id` (root, step or branch), `remove_subtree(id)`,
115
+ `remove_step(id)` (delete one step, its children move to its parent; raises
116
+ `engine.restructure.StepError` with a translated reason for sources / merges / missing columns),
117
+ `edit_params(id, record)`, `rename(id, name)`, `set_comment(id, text)` (consecutive edits merge),
118
+ `with macro(text):` (one undo step), `undo()`, `redo()`, `clear()`, `is_clean()` / `set_clean()`
119
+ (saved state), `undo_stack` (`createUndoAction` / `createRedoAction`; the main window already
120
+ has Undo / Redo in the Edit menu). A failing command raises and is not put on the stack.
121
+ After `add_node`, select the new node with `app.state.current = id` if wanted.
122
+
123
+ ## `app.preview: PreviewController` (`controllers/preview.py`)
124
+
125
+ `start_add(op_id, inputs, params=None)` (readers: `inputs=()`), `start_edit(node_id)`,
126
+ `set_params(params | None)` from the form's (debounced) value signal, `commit() -> id`,
127
+ `cancel()`, signal `committed(id)`. The form follows `app.state.preview_changed` (e.g. reload
128
+ after undo changed the edited step). Previews are not on the undo stack.
129
+
130
+ ## Testing
131
+
132
+ `datacook.app.testing.FakeSession` (Qt-free): requests stay pending until
133
+ `fake.complete(req, frame)` / `fake.fail(req, exc, failing=)`; `fake.put(id, frame)` caches a
134
+ frame, `fake.evict(*ids)`, `fake.pending(id)`, `fake.pending_previews()`, `fake.pin_counts()`.
135
+ `tests/app/conftest.py`: `app` fixture (`AppController(FakeSession)`, debounce 0), `drain(app)`
136
+ (deliver the bridge queue), `check_invariant(app)`. Qt-free modules (`protocols`, `settings`,
137
+ `pins`, `eventqueue`, `jobs`, `testing`) are tested in `tests/test_app_core.py`, which also runs
138
+ in the free-threaded CI job. `tests/app/test_smoke.py` drives the real `MainWindow` with every
139
+ module (reader dialog, ops via actions + form, branch, preview edit, undo / redo, display sort,
140
+ script export run in a subprocess, save / open); `DATACOOK_MEMORY_SCENARIO=1` adds a 3M-row
141
+ memory scenario.
@@ -0,0 +1,23 @@
1
+ """DataCook desktop app (Qt) on top of the Qt-free engine.
2
+
3
+ Importing this package does not import Qt: `protocols`, `settings`, `pins`, `eventqueue`,
4
+ `jobs` and `testing` are Qt-free (they also run on free-threaded Python); everything else
5
+ (`state`, `bridge`, `slots`, `commands`, `controllers`, `mainwindow`, docks) needs Qt.
6
+ Start with `README.md` in this folder.
7
+ """
8
+
9
+ from typing import TYPE_CHECKING
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Sequence
14
+
15
+
16
+ def main(argv: Sequence[str] | None = None) -> int:
17
+ """GUI entry point: set up the allocators before pyarrow is imported, then start."""
18
+ from datacook import allocator
19
+
20
+ allocator.configure()
21
+ from datacook.app.application import main as run
22
+
23
+ return run(argv)
@@ -0,0 +1,7 @@
1
+ """`python -m datacook.app` (same as the `datacook` GUI script)."""
2
+
3
+ from datacook.app import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ raise SystemExit(main())
@@ -0,0 +1,273 @@
1
+ """Op actions: one `QAction` per registered op, the Steps menu and the op palette.
2
+
3
+ `OpActions` builds the actions from the op registry (title, category, icon, description);
4
+ triggering one opens a params preview (`app.preview.start_add`) for a new step on the
5
+ current node. Readers (`n_inputs == 0`) start a root; merge-like ops (`n_inputs == 2`) ask
6
+ for the second input, ops taking two or more (`variadic`, concat) for the other inputs.
7
+ The Steps menu groups the actions by category; the palette (`CommandPalette`,
8
+ Ctrl+Shift+P) lists all of them. Both follow language changes.
9
+ """
10
+
11
+ import logging
12
+ from typing import TYPE_CHECKING
13
+
14
+ from prettyqt import custom_widgets, iconprovider
15
+ from prettyqt.qt import QtCore, QtGui, QtWidgets
16
+
17
+ from datacook.engine import categories
18
+ from datacook.i18n import _
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from collections.abc import Callable
23
+
24
+ from datacook.app.controllers import AppController
25
+ from datacook.app.mainwindow import MainWindow
26
+ from datacook.engine import Node, Op
27
+
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ PALETTE_SHORTCUT = "Ctrl+Shift+P"
32
+ CATEGORY_ORDER = (
33
+ categories.SOURCE,
34
+ categories.GENERAL,
35
+ categories.COLUMNS,
36
+ categories.ROWS,
37
+ categories.FILTER,
38
+ categories.NAN,
39
+ categories.CATEGORICAL,
40
+ categories.CONVERSION,
41
+ categories.TEXT,
42
+ categories.DATETIME,
43
+ categories.TIMESERIES,
44
+ categories.RESHAPE,
45
+ categories.COMBINE,
46
+ categories.STATS,
47
+ categories.ML,
48
+ categories.CODE,
49
+ )
50
+ """Order of the category submenus of the Steps menu."""
51
+
52
+
53
+ def node_label(app: AppController, node: Node) -> str:
54
+ """`name` or op title of a node (for choosers and messages)."""
55
+ if node.name:
56
+ return node.name
57
+ op = app.session.registry.get(node.op_id) if node.op_id in app.session.registry else None
58
+ return str(op.title) if op is not None else node.op_id
59
+
60
+
61
+ class OpActions(QtCore.QObject):
62
+ """The op actions, the Steps menu content and the palette of one main window."""
63
+
64
+ def __init__(self, app: AppController, window: QtWidgets.QWidget):
65
+ super().__init__(window)
66
+ self.setObjectName("op-actions")
67
+ self.app = app
68
+ self.actions: dict[str, QtGui.QAction] = {}
69
+ """Op id -> action (registry order)."""
70
+ self.category_menus: dict[str, QtWidgets.QMenu] = {}
71
+ self.choose_input: Callable[[str, list[Node]], str | None] = self._ask_input
72
+ """`(op_id, candidates) -> node id or None`: the second input of a 2-input op."""
73
+ self.choose_inputs: Callable[[str, list[Node]], list[str] | None] = self._ask_inputs
74
+ """`(op_id, candidates) -> node ids or None`: the other inputs of a variadic op."""
75
+ for op in app.session.registry:
76
+ self.actions[op.id] = self._make_action(op)
77
+ self.palette = custom_widgets.CommandPalette()
78
+ self.palette.setObjectName("op-palette")
79
+ self.palette.install_to(window)
80
+ if (pal_layout := self.palette.layout()) is not None:
81
+ pal_layout.setContentsMargins(10, 10, 10, 10)
82
+ pal_layout.setSpacing(8)
83
+ table = self.palette._table
84
+ table.setColumnHidden(2, True) # ops don't have per-op shortcuts
85
+ table.verticalHeader().setDefaultSectionSize(24)
86
+ table.setAlternatingRowColors(True)
87
+ self.palette.set_actions(self.actions.values())
88
+ self.palette_action = QtGui.QAction(window)
89
+ self.palette_action.setObjectName("action-palette")
90
+ self.palette_action.setShortcut(PALETTE_SHORTCUT)
91
+ self.palette_action.setShortcutContext(QtCore.Qt.ShortcutContext.WindowShortcut)
92
+ self.palette_action.triggered.connect(self.show_palette)
93
+ window.addAction(self.palette_action)
94
+ self.edit_action = QtGui.QAction(window)
95
+ self.edit_action.setObjectName("action-edit-step")
96
+ self.edit_action.setShortcut("Ctrl+E") # F2 = rename in the tree
97
+ self.edit_action.triggered.connect(self.edit_current)
98
+ self.cancel_action = QtGui.QAction(window)
99
+ self.cancel_action.setObjectName("action-cancel-preview")
100
+ self.cancel_action.setShortcut("Esc") # enabled only while a preview is open
101
+ self.cancel_action.triggered.connect(app.preview.cancel)
102
+ app.state.language_changed.connect(self.retranslate)
103
+ app.state.current_changed.connect(self._update_enabled)
104
+ app.state.preview_changed.connect(self._update_enabled)
105
+ self.retranslate()
106
+
107
+ def parent_widget(self) -> QtWidgets.QWidget | None:
108
+ """The main window (not stored: no Python reference cycle with it)."""
109
+ parent = self.parent()
110
+ return parent if isinstance(parent, QtWidgets.QWidget) else None
111
+
112
+ # --- building ----------------------------------------------------------------------
113
+ def _make_action(self, op: type[Op]) -> QtGui.QAction:
114
+ action = QtGui.QAction(self)
115
+ action.setObjectName(f"op-{op.id}")
116
+ action.setData(op.id)
117
+ try:
118
+ action.setIcon(iconprovider.get_icon(op.icon))
119
+ except Exception: # noqa: BLE001 - an unknown icon name must not break the menu
120
+ logger.debug("no icon %r for op %s", op.icon, op.id)
121
+ action.setEnabled(op.available())
122
+ action.triggered.connect(lambda _checked=False, op_id=op.id: self.start(op_id))
123
+ return action
124
+
125
+ def ops_by_category(self) -> list[type[Op]]:
126
+ """Registry ops, grouped in the order of `engine.categories` (others last)."""
127
+ order = {c.id: i for i, c in enumerate(CATEGORY_ORDER)}
128
+ ops = list(self.app.session.registry)
129
+ return sorted(ops, key=lambda op: order.get(op.category.id, len(order)))
130
+
131
+ def fill_menu(self, menu: QtWidgets.QMenu) -> None:
132
+ """Steps menu: Palette, Edit step, Cancel, then one submenu per category."""
133
+ menu.addAction(self.palette_action)
134
+ menu.addAction(self.edit_action)
135
+ menu.addAction(self.cancel_action)
136
+ menu.addSeparator()
137
+ for op in self.ops_by_category():
138
+ category = op.category
139
+ sub = self.category_menus.get(category.id)
140
+ if sub is None:
141
+ sub = menu.addMenu(str(category.title))
142
+ sub.setObjectName(f"menu-category-{category.id}")
143
+ try:
144
+ sub.setIcon(iconprovider.get_icon(category.icon))
145
+ except Exception: # noqa: BLE001
146
+ logger.debug("no icon %r for category %s", category.icon, category.id)
147
+ self.category_menus[category.id] = sub
148
+ sub.addAction(self.actions[op.id])
149
+
150
+ def retranslate(self, _language: object = None) -> None:
151
+ registry = self.app.session.registry
152
+ for op_id, action in self.actions.items():
153
+ op = registry.get(op_id)
154
+ action.setText(str(op.title))
155
+ tip = f"{op.category.title}: {op.description}" if str(op.description) else ""
156
+ if not op.available():
157
+ needs = str(_("needs the extra {extra!r}")).format(extra=op.extra or "?")
158
+ tip = f"{tip} ({needs})" if tip else needs
159
+ action.setToolTip(tip or str(op.category.title))
160
+ action.setStatusTip(str(op.description))
161
+ for op in registry:
162
+ if (sub := self.category_menus.get(op.category.id)) is not None:
163
+ sub.setTitle(str(op.category.title))
164
+ self.palette_action.setText(str(_("Command palette…")))
165
+ self.edit_action.setText(str(_("Edit step…")))
166
+ self.cancel_action.setText(str(_("Cancel preview")))
167
+ self.palette._line.setPlaceholderText(str(_("Search operations…")))
168
+ self.palette.set_actions(self.actions.values())
169
+ self._update_enabled()
170
+
171
+ def _update_enabled(self, *_args: object) -> None:
172
+ current = self.app.state.current
173
+ editable = current is not None and current in self.app.session
174
+ self.edit_action.setEnabled(editable)
175
+ self.cancel_action.setEnabled(self.app.state.preview is not None)
176
+
177
+ # --- behaviour ---------------------------------------------------------------------
178
+ def show_palette(self) -> None:
179
+ self.palette.show()
180
+
181
+ def start(self, op_id: str) -> bool: # noqa: PLR0911
182
+ """Open a params preview for a new `op_id` step; False if it cannot start."""
183
+ app = self.app
184
+ op = app.session.registry.get(op_id)
185
+ if not op.available():
186
+ app.notify(
187
+ str(_("{title} needs the extra {extra!r}")).format(title=op.title, extra=op.extra),
188
+ "warning",
189
+ )
190
+ return False
191
+ if op.n_inputs == 0:
192
+ app.preview.start_add(op_id, ())
193
+ return True
194
+ current = app.state.current
195
+ if current is None or current not in app.session:
196
+ app.notify(_("Select a step first: the new step is added after it."), "warning")
197
+ return False
198
+ inputs = [current]
199
+ if op.n_inputs == 2: # noqa: PLR2004
200
+ candidates = [n for n in app.session.nodes() if n.id != current]
201
+ if not candidates:
202
+ app.notify(
203
+ str(_("{title} needs a second table.")).format(title=op.title), "warning"
204
+ )
205
+ return False
206
+ if op.variadic:
207
+ others = self.choose_inputs(op_id, candidates)
208
+ if not others:
209
+ return False
210
+ inputs.extend(others)
211
+ else:
212
+ other = self.choose_input(op_id, candidates)
213
+ if other is None:
214
+ return False
215
+ inputs.append(other)
216
+ elif op.n_inputs > 2: # noqa: PLR2004
217
+ app.notify(_("Ops with more than two inputs are not supported yet."), "warning")
218
+ return False
219
+ app.preview.start_add(op_id, inputs)
220
+ return True
221
+
222
+ def edit_current(self) -> bool:
223
+ current = self.app.state.current
224
+ if current is None or current not in self.app.session:
225
+ return False
226
+ self.app.preview.start_edit(current)
227
+ return True
228
+
229
+ def _ask_input(self, op_id: str, candidates: list[Node]) -> str | None:
230
+ op = self.app.session.registry.get(op_id)
231
+ labels = [f"{node_label(self.app, n)} [{n.id[:6]}]" for n in candidates]
232
+ label, ok = QtWidgets.QInputDialog.getItem(
233
+ self.parent_widget(),
234
+ str(op.title),
235
+ str(_("Second table (right side):")),
236
+ labels,
237
+ 0,
238
+ False,
239
+ )
240
+ if not ok:
241
+ return None
242
+ return candidates[labels.index(label)].id
243
+
244
+ def _ask_inputs(self, op_id: str, candidates: list[Node]) -> list[str] | None:
245
+ """A list of the candidates to check; the checked ones in list order."""
246
+ op = self.app.session.registry.get(op_id)
247
+ dialog = QtWidgets.QDialog(self.parent_widget())
248
+ dialog.setWindowTitle(str(op.title))
249
+ layout = QtWidgets.QVBoxLayout(dialog)
250
+ layout.addWidget(QtWidgets.QLabel(str(_("Tables to add after the current one:"))))
251
+ items = QtWidgets.QListWidget(dialog)
252
+ for node in candidates:
253
+ item = QtWidgets.QListWidgetItem(f"{node_label(self.app, node)} [{node.id[:6]}]")
254
+ item.setFlags(item.flags() | QtCore.Qt.ItemFlag.ItemIsUserCheckable)
255
+ item.setCheckState(QtCore.Qt.CheckState.Unchecked)
256
+ items.addItem(item)
257
+ layout.addWidget(items)
258
+ buttons = QtWidgets.QDialogButtonBox(
259
+ QtWidgets.QDialogButtonBox.StandardButton.Ok
260
+ | QtWidgets.QDialogButtonBox.StandardButton.Cancel
261
+ )
262
+ buttons.accepted.connect(dialog.accept)
263
+ buttons.rejected.connect(dialog.reject)
264
+ layout.addWidget(buttons)
265
+ if dialog.exec() != QtWidgets.QDialog.DialogCode.Accepted:
266
+ return None
267
+ checked = QtCore.Qt.CheckState.Checked
268
+ return [n.id for i, n in enumerate(candidates) if items.item(i).checkState() == checked]
269
+
270
+
271
+ def install(app: AppController, window: MainWindow) -> None:
272
+ actions = OpActions(app, window)
273
+ actions.fill_menu(window.menu("steps"))