tk-rt-viewer 2.3.2__tar.gz → 2.3.4__tar.gz

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 (70) hide show
  1. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/.github/workflows/ci.yml +3 -0
  2. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/CHANGELOG.md +26 -0
  3. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/PKG-INFO +23 -5
  4. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/README.md +22 -4
  5. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/__init__.py +1 -1
  6. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/event_controllers/viewer_events.py +84 -2
  7. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/io.py +2 -2
  8. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/view_axes.py +23 -1
  9. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rtstruct_io.py +36 -8
  10. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/viewer.py +9 -1
  11. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_event_controllers.py +151 -3
  12. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_rtstruct_io.py +105 -2
  13. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/.gitattributes +0 -0
  14. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/.gitignore +0 -0
  15. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/LICENSE +0 -0
  16. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/pyproject.toml +0 -0
  17. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/event_controllers/__init__.py +0 -0
  18. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/event_controllers/bbox3d_handler.py +0 -0
  19. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/event_controllers/bbox_handler.py +0 -0
  20. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/event_controllers/brush_handler.py +0 -0
  21. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/event_controllers/crosshair_handler.py +0 -0
  22. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/event_controllers/rect_drag.py +0 -0
  23. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/events.py +0 -0
  24. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/geometry.py +0 -0
  25. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/isodose_levels.py +0 -0
  26. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/protocols.py +0 -0
  27. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/py.typed +0 -0
  28. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/reg_io.py +0 -0
  29. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/registration/__init__.py +0 -0
  30. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/registration/deformable.py +0 -0
  31. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/registration/errors.py +0 -0
  32. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/registration/params.py +0 -0
  33. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/registration/rigid.py +0 -0
  34. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/registration/session.py +0 -0
  35. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/registration/template.py +0 -0
  36. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/__init__.py +0 -0
  37. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/blit_compositor.py +0 -0
  38. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/contour_overlay.py +0 -0
  39. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/drawing_manager.py +0 -0
  40. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/dvh.py +0 -0
  41. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/image_layer.py +0 -0
  42. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/isodose.py +0 -0
  43. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/layout.py +0 -0
  44. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/rendering/render.py +0 -0
  45. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/roi_operations.py +0 -0
  46. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/__init__.py +0 -0
  47. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/dose_manager.py +0 -0
  48. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/phase_manager.py +0 -0
  49. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/roi_editor.py +0 -0
  50. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/roi_manager.py +0 -0
  51. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/secondary_manager.py +0 -0
  52. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/structure_set.py +0 -0
  53. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/viewer_cache.py +0 -0
  54. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/state/viewer_state.py +0 -0
  55. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/src/tk_rt_viewer/window_level.py +0 -0
  56. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_bbox3d.py +0 -0
  57. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_bbox3d_handler.py +0 -0
  58. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_brush_handler.py +0 -0
  59. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_geometry.py +0 -0
  60. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_io.py +0 -0
  61. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_isodose_levels.py +0 -0
  62. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_performance_opt.py +0 -0
  63. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_reg_io.py +0 -0
  64. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_registration.py +0 -0
  65. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_render.py +0 -0
  66. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_rendering.py +0 -0
  67. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_roi_operations.py +0 -0
  68. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_state_extensions.py +0 -0
  69. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_state_managers.py +0 -0
  70. {tk_rt_viewer-2.3.2 → tk_rt_viewer-2.3.4}/tests/test_viewer_state.py +0 -0
@@ -5,6 +5,9 @@ on:
5
5
  branches: [main]
6
6
  pull_request:
7
7
 
8
+ permissions:
9
+ contents: read
10
+
8
11
  jobs:
9
12
  check:
10
13
  runs-on: ubuntu-latest
@@ -4,6 +4,32 @@ All notable changes to this project are documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
5
  and this project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [2.3.4]
8
+
9
+ ### Added
10
+
11
+ - **Middle-button panning.** Pressing the middle mouse button (the wheel) over
12
+ a view and dragging moves the view so that the image follows the pointer.
13
+ Each view pans independently, at any zoom, and the view cannot be moved off
14
+ the slice. It works even while the brush tool is active, like Ctrl + wheel
15
+ zoom, and does not touch `SliceViewerState`. `reset_zoom()` fits the view
16
+ again, which also undoes the pan.
17
+ - `ImageViewAxes.view_center()` returns the data coordinates of the view
18
+ centre, and `ImageViewAxes.pan_to(cx, cy)` centres the view on a point at
19
+ the current zoom (clamped to the slice).
20
+
21
+ ## [2.3.3]
22
+
23
+ ### Added
24
+
25
+ - `rtstruct_io.mask2rtstruct` and `rtstruct_io.save_structure_set` take a
26
+ keyword-only `add_roi_kwargs` mapping, forwarded to rt-utils'
27
+ `RTStruct.add_roi` for every ROI. Callers can now set
28
+ `approximate_contours`, `use_pin_hole`, `roi_generation_algorithm`,
29
+ `description`, etc. `mask`, `color` and `name` still come from the
30
+ structures and raise `ValueError` if given here. The default (`None`)
31
+ keeps the previous behaviour.
32
+
7
33
  ## [2.3.2]
8
34
 
9
35
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: tk-rt-viewer
3
- Version: 2.3.2
3
+ Version: 2.3.4
4
4
  Summary: SimpleITK-based DICOM-RT MPR viewer widget for Tkinter (CT, RT-DOSE, RT-STRUCT, DVH)
5
5
  Project-URL: Homepage, https://github.com/oki1002/DICOM_RT_Viewer
6
6
  Project-URL: Repository, https://github.com/oki1002/DICOM_RT_Viewer
@@ -59,7 +59,7 @@ The distribution name on PyPI is `tk-rt-viewer`; the import package is
59
59
  - **Observer-pattern state management** — All view state lives in `SliceViewerState`; the widget reacts to changes without polling.
60
60
  - **SimpleITK-native coordinates** — Physical LPS coordinates, origin, spacing, and direction cosines are preserved throughout; axis reordering between SimpleITK and NumPy conventions is handled internally by the library.
61
61
  - **Interactive navigation** — Crosshair drag, mouse wheel (direction reversible), and keyboard (↑ / ↓ / PageUp / PageDown).
62
- - **Per-view zoom** — Ctrl + mouse wheel zooms the view under the pointer about the pointer; each view keeps its own zoom factor. The views fill their layout cells, so a zoomed slice uses the whole cell.
62
+ - **Per-view zoom and pan** — Ctrl + mouse wheel zooms the view under the pointer about the pointer, and dragging with the middle button (the wheel pressed) pans it; each view keeps its own zoom factor and position. The views fill their layout cells, so a zoomed slice uses the whole cell.
63
63
  - **Independent window / level per image** — The primary and secondary images each carry their own display window, so a PET, MR, or dose overlay can be windowed without disturbing the CT underneath. The secondary follows the primary until an override is set. Right-click drag adjusts whichever image is targeted: horizontal → window width (WW), vertical → window centre (WL).
64
64
  - **RT-STRUCT support** — ROI masks stored in `StructureSet` (keyed by integer ROI number); contour overlay with optional semi-transparent fill; brush tool for mask editing.
65
65
  - **ROI operations** — Shape-based inter-slice interpolation, true Euclidean margins (uniform or 6-direction anisotropic), Gaussian smoothing, and boolean operations (union / intersection / subtraction).
@@ -134,7 +134,7 @@ tk_rt_viewer/
134
134
  │ ├── isodose.py # IsoDoseOverlay (fill bands + contour lines)
135
135
  │ ├── dvh.py # DvhPanel (cumulative DVH panel)
136
136
  │ ├── layout.py # LayoutManager (single / mpr / mpr_wide layouts)
137
- │ └── view_axes.py # ImageViewAxes (fills its cell, 1:1 aspect, zoom)
137
+ │ └── view_axes.py # ImageViewAxes (fills its cell, 1:1 aspect, zoom, pan)
138
138
  ├── registration/
139
139
  │ ├── session.py # RegistrationSession, cropping, resampling
140
140
  │ ├── params.py # RigidParams <-> transforms (Vert/Lat/Long/...)
@@ -374,6 +374,11 @@ written = save_structure_set(
374
374
  )
375
375
  ```
376
376
 
377
+ Pass `add_roi_kwargs` to forward options to rt-utils' `RTStruct.add_roi`
378
+ for every ROI, e.g. `add_roi_kwargs={"approximate_contours": False}` to
379
+ keep every contour vertex instead of the simplified outline. `mask2rtstruct`
380
+ accepts the same keyword.
381
+
377
382
  `rt_utils.RTStruct.save` silently appends `.dcm` to a path that does not
378
383
  already end with it, with no way to opt out; `mask2rtstruct` resolves
379
384
  against that internally so its `exists()` check, its log messages, and its
@@ -754,7 +759,7 @@ box tool, crosshair, contours, isodose) works unchanged in `"single"` mode
754
759
  against the `"axial"` key — host code does not need a separate code path
755
760
  for it.
756
761
 
757
- ## Zoom and wheel direction
762
+ ## Zoom, pan and wheel direction
758
763
 
759
764
  Ctrl + mouse wheel zooms the view under the pointer, keeping the point under
760
765
  the pointer in place. Each view is zoomed independently, from 1× (the whole
@@ -763,11 +768,24 @@ the slice. A figure resize keeps each view's zoom and centre; loading a new
763
768
  primary image or switching the layout starts fitted again. Ctrl + wheel zooms
764
769
  even while the brush tool is active (the plain wheel still resizes the brush).
765
770
 
771
+ Dragging with the middle button (the wheel pressed) pans the view under the
772
+ pointer: the image follows the pointer, at any zoom, and the view cannot be
773
+ moved off the slice. Each view pans independently, and panning also works
774
+ while the brush tool is active. `reset_zoom()` fits the view again, which
775
+ undoes the pan as well. A view keeps its position across a figure resize and
776
+ starts fitted when a new primary image is loaded or the layout is switched.
777
+
766
778
  ```python
767
779
  viewer.set_zoom("axial", 2.5) # about the view centre
768
780
  viewer.set_zoom("coronal", 4.0, anchor=(x, z)) # keep (x, z) in place
769
781
  viewer.get_zoom("axial") # -> 2.5
770
- viewer.reset_zoom() # fit every view again
782
+ viewer.reset_zoom() # fit every view again (and undo any pan)
783
+
784
+ # Pan programmatically through the view's Axes
785
+ ax = viewer.axs["axial"]
786
+ ax.view_center() # -> (x, y) in data coordinates
787
+ ax.pan_to(x, y) # centre on (x, y), clamped to the slice
788
+ viewer.canvas.draw_idle()
771
789
 
772
790
  # Reverse the wheel for slice scrolling (brush size and zoom are unaffected)
773
791
  viewer = DicomViewer(parent, state=state, invert_scroll=True)
@@ -22,7 +22,7 @@ The distribution name on PyPI is `tk-rt-viewer`; the import package is
22
22
  - **Observer-pattern state management** — All view state lives in `SliceViewerState`; the widget reacts to changes without polling.
23
23
  - **SimpleITK-native coordinates** — Physical LPS coordinates, origin, spacing, and direction cosines are preserved throughout; axis reordering between SimpleITK and NumPy conventions is handled internally by the library.
24
24
  - **Interactive navigation** — Crosshair drag, mouse wheel (direction reversible), and keyboard (↑ / ↓ / PageUp / PageDown).
25
- - **Per-view zoom** — Ctrl + mouse wheel zooms the view under the pointer about the pointer; each view keeps its own zoom factor. The views fill their layout cells, so a zoomed slice uses the whole cell.
25
+ - **Per-view zoom and pan** — Ctrl + mouse wheel zooms the view under the pointer about the pointer, and dragging with the middle button (the wheel pressed) pans it; each view keeps its own zoom factor and position. The views fill their layout cells, so a zoomed slice uses the whole cell.
26
26
  - **Independent window / level per image** — The primary and secondary images each carry their own display window, so a PET, MR, or dose overlay can be windowed without disturbing the CT underneath. The secondary follows the primary until an override is set. Right-click drag adjusts whichever image is targeted: horizontal → window width (WW), vertical → window centre (WL).
27
27
  - **RT-STRUCT support** — ROI masks stored in `StructureSet` (keyed by integer ROI number); contour overlay with optional semi-transparent fill; brush tool for mask editing.
28
28
  - **ROI operations** — Shape-based inter-slice interpolation, true Euclidean margins (uniform or 6-direction anisotropic), Gaussian smoothing, and boolean operations (union / intersection / subtraction).
@@ -97,7 +97,7 @@ tk_rt_viewer/
97
97
  │ ├── isodose.py # IsoDoseOverlay (fill bands + contour lines)
98
98
  │ ├── dvh.py # DvhPanel (cumulative DVH panel)
99
99
  │ ├── layout.py # LayoutManager (single / mpr / mpr_wide layouts)
100
- │ └── view_axes.py # ImageViewAxes (fills its cell, 1:1 aspect, zoom)
100
+ │ └── view_axes.py # ImageViewAxes (fills its cell, 1:1 aspect, zoom, pan)
101
101
  ├── registration/
102
102
  │ ├── session.py # RegistrationSession, cropping, resampling
103
103
  │ ├── params.py # RigidParams <-> transforms (Vert/Lat/Long/...)
@@ -337,6 +337,11 @@ written = save_structure_set(
337
337
  )
338
338
  ```
339
339
 
340
+ Pass `add_roi_kwargs` to forward options to rt-utils' `RTStruct.add_roi`
341
+ for every ROI, e.g. `add_roi_kwargs={"approximate_contours": False}` to
342
+ keep every contour vertex instead of the simplified outline. `mask2rtstruct`
343
+ accepts the same keyword.
344
+
340
345
  `rt_utils.RTStruct.save` silently appends `.dcm` to a path that does not
341
346
  already end with it, with no way to opt out; `mask2rtstruct` resolves
342
347
  against that internally so its `exists()` check, its log messages, and its
@@ -717,7 +722,7 @@ box tool, crosshair, contours, isodose) works unchanged in `"single"` mode
717
722
  against the `"axial"` key — host code does not need a separate code path
718
723
  for it.
719
724
 
720
- ## Zoom and wheel direction
725
+ ## Zoom, pan and wheel direction
721
726
 
722
727
  Ctrl + mouse wheel zooms the view under the pointer, keeping the point under
723
728
  the pointer in place. Each view is zoomed independently, from 1× (the whole
@@ -726,11 +731,24 @@ the slice. A figure resize keeps each view's zoom and centre; loading a new
726
731
  primary image or switching the layout starts fitted again. Ctrl + wheel zooms
727
732
  even while the brush tool is active (the plain wheel still resizes the brush).
728
733
 
734
+ Dragging with the middle button (the wheel pressed) pans the view under the
735
+ pointer: the image follows the pointer, at any zoom, and the view cannot be
736
+ moved off the slice. Each view pans independently, and panning also works
737
+ while the brush tool is active. `reset_zoom()` fits the view again, which
738
+ undoes the pan as well. A view keeps its position across a figure resize and
739
+ starts fitted when a new primary image is loaded or the layout is switched.
740
+
729
741
  ```python
730
742
  viewer.set_zoom("axial", 2.5) # about the view centre
731
743
  viewer.set_zoom("coronal", 4.0, anchor=(x, z)) # keep (x, z) in place
732
744
  viewer.get_zoom("axial") # -> 2.5
733
- viewer.reset_zoom() # fit every view again
745
+ viewer.reset_zoom() # fit every view again (and undo any pan)
746
+
747
+ # Pan programmatically through the view's Axes
748
+ ax = viewer.axs["axial"]
749
+ ax.view_center() # -> (x, y) in data coordinates
750
+ ax.pan_to(x, y) # centre on (x, y), clamped to the slice
751
+ viewer.canvas.draw_idle()
734
752
 
735
753
  # Reverse the wheel for slice scrolling (brush size and zoom are unaffected)
736
754
  viewer = DicomViewer(parent, state=state, invert_scroll=True)
@@ -104,7 +104,7 @@ __all__ = [
104
104
  "StructureSet",
105
105
  "to_gy_pairs",
106
106
  ]
107
- __version__ = "2.3.2"
107
+ __version__ = "2.3.4"
108
108
 
109
109
 
110
110
  def __getattr__(name: str) -> Any:
@@ -4,8 +4,10 @@ Responsibilities:
4
4
  - Track which view the pointer is inside.
5
5
  - Route canvas events to the appropriate sub-handler.
6
6
  - Implement right-click-drag window / level adjustment directly.
7
+ - Implement middle-button-drag panning directly.
7
8
 
8
9
  Event priority for ``on_press`` / ``on_motion``:
10
+ 0. Pan (middle-button drag; works even while the brush is active)
9
11
  1. Brush tool (exclusive when active)
10
12
  2. Crosshair drag
11
13
  3. Window / level adjustment (right-click drag)
@@ -28,6 +30,13 @@ Wheel priority:
28
30
  the brush is active
29
31
  2. Brush tool: resize the brush
30
32
  3. Otherwise: scroll slices; ``invert_scroll`` flips the direction
33
+
34
+ Pan:
35
+ Pressing the middle button (the wheel) over a view and dragging moves the
36
+ view so that the image follows the pointer. The drag is measured from the
37
+ press, so the image tracks the pointer exactly until the view reaches the
38
+ edge of the slice. Panning only changes the view limits; it does not
39
+ touch the state.
31
40
  """
32
41
 
33
42
  import numpy as np
@@ -42,7 +51,7 @@ from .brush_handler import BrushEventHandler
42
51
  from .crosshair_handler import CrosshairEventHandler
43
52
 
44
53
  #: Zoom ratio per Ctrl + wheel notch.
45
- ZOOM_STEP: float = 1.25
54
+ ZOOM_STEP: float = 1.1
46
55
 
47
56
  #: Debounce window (ms) for batching scroll events; short enough to feel
48
57
  #: immediate, long enough to coalesce a wheel flick.
@@ -54,6 +63,9 @@ _KEY_STEPS: dict[str, int] = {"up": 1, "down": -1, "pageup": 10, "pagedown": -10
54
63
  # Right mouse button drives the window/level drag
55
64
  _WL_BUTTON: int = 3
56
65
 
66
+ # Middle mouse button (wheel press) drives the pan drag
67
+ _PAN_BUTTON: int = 2
68
+
57
69
  # Window/level drag sensitivity (display units per pixel) at the reference
58
70
  # width; scaled by the window at drag start so a 400 HU and a 4 Gy window
59
71
  # feel alike
@@ -95,6 +107,13 @@ class ViewerEventHandler:
95
107
  self._wl_initial: tuple[float, float] | None = None
96
108
  self._wl_target: str = "primary"
97
109
 
110
+ # Pan drag state: the view being panned and the pointer position
111
+ # (display pixels) and view limits at the press. ``None`` when idle.
112
+ self._pan_axis: str = ""
113
+ self._pan_start: (
114
+ tuple[float, float, tuple[float, float], tuple[float, float]] | None
115
+ ) = None
116
+
98
117
  # Scroll debounce state (Tk main thread only)
99
118
  self._scroll_handle: str | None = None
100
119
  self._scroll_accum: int = 0
@@ -117,6 +136,7 @@ class ViewerEventHandler:
117
136
  self.brush_handler.activate()
118
137
  # The brush claims the mouse: abandon every other drag
119
138
  self._reset_wl_drag()
139
+ self._end_pan()
120
140
  self.crosshair_handler.cancel()
121
141
  self.bbox_handler.cancel()
122
142
  self.bbox_3d_handler.cancel()
@@ -256,6 +276,11 @@ class ViewerEventHandler:
256
276
  if self._any_drag_in_progress():
257
277
  self._recover_lost_drag(event)
258
278
 
279
+ # Priority 0: pan, even while the brush is active
280
+ if event.button == _PAN_BUTTON:
281
+ self._begin_pan(event)
282
+ return
283
+
259
284
  # Priority 1: brush tool (exclusive)
260
285
  if self.state.brush_tool_active:
261
286
  self.brush_handler.handle_press(event)
@@ -276,6 +301,53 @@ class ViewerEventHandler:
276
301
  return
277
302
  self.bbox_handler.handle_press(event)
278
303
 
304
+ # ------------------------------------------------------------------
305
+ # Pan
306
+ # ------------------------------------------------------------------
307
+ def _begin_pan(self, event) -> None:
308
+ """Start panning the view under the pointer, if it can be panned."""
309
+ ax = self.viewer.axes_map.get(self._current_axis)
310
+ if (
311
+ not isinstance(ax, ImageViewAxes)
312
+ or self.state.primary_image is None
313
+ or event.x is None
314
+ or event.y is None
315
+ ):
316
+ return
317
+ self._pan_axis = self._current_axis
318
+ self._pan_start = (event.x, event.y, ax.get_xlim(), ax.get_ylim())
319
+
320
+ def _apply_pan(self, event) -> None:
321
+ """Move the view so the image follows the pointer since the press.
322
+
323
+ The shift is converted from display pixels to data units with the
324
+ limits at the press, so it keeps its sign on an inverted axis.
325
+ """
326
+ ax = self.viewer.axes_map.get(self._pan_axis)
327
+ if (
328
+ self._pan_start is None
329
+ or not isinstance(ax, ImageViewAxes)
330
+ or event.x is None
331
+ or event.y is None
332
+ ):
333
+ return
334
+ width, height = ax.bbox.width, ax.bbox.height
335
+ if width <= 0 or height <= 0:
336
+ return
337
+ start_x, start_y, xlim, ylim = self._pan_start
338
+ shift_x = (event.x - start_x) / width * (xlim[1] - xlim[0])
339
+ shift_y = (event.y - start_y) / height * (ylim[1] - ylim[0])
340
+ ax.pan_to(
341
+ (xlim[0] + xlim[1]) / 2 - shift_x,
342
+ (ylim[0] + ylim[1]) / 2 - shift_y,
343
+ )
344
+ self.viewer.refresh_canvas()
345
+
346
+ def _end_pan(self) -> None:
347
+ """Clear all pan drag state."""
348
+ self._pan_axis = ""
349
+ self._pan_start = None
350
+
279
351
  def _begin_wl_drag(self, event) -> None:
280
352
  """Start a window/level drag, resolving its target image once.
281
353
 
@@ -311,6 +383,9 @@ class ViewerEventHandler:
311
383
  self._recover_lost_drag(event)
312
384
  return
313
385
 
386
+ if self._pan_start is not None:
387
+ self._apply_pan(event)
388
+ return
314
389
  if self.state.brush_tool_active:
315
390
  self.brush_handler.handle_motion(event)
316
391
  return
@@ -341,11 +416,12 @@ class ViewerEventHandler:
341
416
  return event.button is None
342
417
 
343
418
  def _any_drag_in_progress(self) -> bool:
344
- """``True`` if any sub-handler (or the W/L drag) is mid-drag."""
419
+ """``True`` if any sub-handler (or the W/L or pan drag) is mid-drag."""
345
420
  return (
346
421
  self.brush_handler.is_dragging
347
422
  or self.crosshair_handler.is_dragging
348
423
  or self._dragging_wl
424
+ or self._pan_start is not None
349
425
  or self.bbox_handler.is_dragging
350
426
  or self.bbox_3d_handler.is_dragging
351
427
  )
@@ -366,6 +442,8 @@ class ViewerEventHandler:
366
442
  self.bbox_3d_handler.cancel()
367
443
  if self._dragging_wl:
368
444
  self._reset_wl_drag()
445
+ if self._pan_start is not None:
446
+ self._end_pan()
369
447
 
370
448
  def _apply_wl_drag(self, event) -> None:
371
449
  """Translate a right-drag into a window/level change.
@@ -395,6 +473,10 @@ class ViewerEventHandler:
395
473
  # ------------------------------------------------------------------
396
474
  def on_release(self, event) -> None:
397
475
  """Release all in-progress drag operations."""
476
+ if event.button == _PAN_BUTTON and self._pan_start is not None:
477
+ self._end_pan()
478
+ return
479
+
398
480
  if self.state.brush_tool_active:
399
481
  self.brush_handler.handle_release(event)
400
482
  return
@@ -55,7 +55,7 @@ import re
55
55
  from collections.abc import Iterable, Iterator, Sequence
56
56
  from concurrent.futures import ThreadPoolExecutor
57
57
  from dataclasses import dataclass, field, replace
58
- from typing import TypedDict
58
+ from typing import TypedDict, cast
59
59
 
60
60
  import numpy as np
61
61
  import pydicom
@@ -672,7 +672,7 @@ def _read_files(
672
672
  """Read *file_names* as one series, keeping per-slice metadata on *reader*."""
673
673
  reader.SetFileNames(file_names)
674
674
  reader.MetaDataDictionaryArrayUpdateOn()
675
- image = reader.Execute()
675
+ image = cast(sitk.Image, reader.Execute())
676
676
  logger.info(f"Series '{series_id}' loaded with {len(file_names)} files.")
677
677
  return image
678
678
 
@@ -1,4 +1,4 @@
1
- """view_axes.py — Axes for an image view: fills its cell, keeps 1:1, zooms.
1
+ """view_axes.py — Axes for an image view: fills its cell, keeps 1:1, zooms, pans.
2
2
 
3
3
  Matplotlib keeps an equal data aspect either by shrinking the Axes box
4
4
  (``adjustable="box"``, which leaves empty bands in the layout cell) or by
@@ -10,6 +10,9 @@ conformed to the box on every draw.
10
10
  Zoom is relative to the "fit" view, in which the whole slice just fits the
11
11
  box. It is read back from the limits, so a Matplotlib toolbar zoom or pan is
12
12
  picked up as well; after a resize the zoom factor and centre are kept.
13
+
14
+ Panning (:meth:`ImageViewAxes.pan_to`) moves the view centre at a fixed zoom;
15
+ like zooming, it never moves the view off the slice.
13
16
  """
14
17
 
15
18
  from matplotlib.axes import Axes
@@ -87,6 +90,25 @@ class ImageViewAxes(Axes):
87
90
  cy = anchor[1] + (cy - anchor[1]) * new_y / old_y
88
91
  self._set_view(cx, cy, new_x, new_y)
89
92
 
93
+ def view_center(self) -> tuple[float, float]:
94
+ """Return the data coordinates of the centre of the current view."""
95
+ return self._center()
96
+
97
+ def pan_to(self, cx: float, cy: float) -> None:
98
+ """Centre the view on ``(cx, cy)`` without changing the zoom.
99
+
100
+ The centre is clamped so that the view stays on the slice; a view at
101
+ least as wide as the slice along an axis stays centred on it there.
102
+
103
+ Args:
104
+ cx: Target centre, x in data coordinates.
105
+ cy: Target centre, y in data coordinates.
106
+ """
107
+ span_x, span_y = self._spans()
108
+ if span_x <= 0 or span_y <= 0:
109
+ return
110
+ self._set_view(cx, cy, span_x, span_y)
111
+
90
112
  # ------------------------------------------------------------------
91
113
  # Internals
92
114
  # ------------------------------------------------------------------
@@ -8,13 +8,15 @@ load_rt_struct(ct_dir, rtstruct_path, progress_callback=None, max_workers=1)
8
8
  and display metadata. Raises RtStructLoadError if the file itself
9
9
  cannot be parsed.
10
10
 
11
- mask2rtstruct(ct_dir, rtss_path, structures) -> pathlib.Path
11
+ mask2rtstruct(ct_dir, rtss_path, structures, *, replace_existing=True,
12
+ add_roi_kwargs=None) -> pathlib.Path
12
13
  Convert NumPy mask arrays to an RT-STRUCT DICOM file, creating or
13
14
  updating as appropriate. Returns the path actually written to (rt-utils
14
- appends ".dcm" to a path that lacks it).
15
+ appends ".dcm" to a path that lacks it). add_roi_kwargs is forwarded to
16
+ rt-utils' RTStruct.add_roi (e.g. approximate_contours).
15
17
 
16
18
  save_structure_set(structure_set, ct_dir, rtss_path, lps_image,
17
- original_image=None) -> int
19
+ original_image=None, *, add_roi_kwargs=None) -> int
18
20
  Write every ROI of a StructureSet to an RT-STRUCT file, resampling
19
21
  each mask back to the original DICOM geometry first.
20
22
 
@@ -29,7 +31,7 @@ random_hex_color() -> str
29
31
  import logging
30
32
  import pathlib
31
33
  from collections import Counter
32
- from collections.abc import Callable
34
+ from collections.abc import Callable, Mapping
33
35
  from concurrent.futures import ThreadPoolExecutor, as_completed
34
36
  from typing import TYPE_CHECKING, Any, TypedDict
35
37
 
@@ -63,6 +65,9 @@ _COLOR_RNG: np.random.Generator = np.random.default_rng()
63
65
  #: Suffix rt-utils' ``RTStruct.save()`` silently appends to any path lacking it.
64
66
  _RTSTRUCT_SUFFIX = ".dcm"
65
67
 
68
+ #: add_roi keywords mask2rtstruct fills in itself from *structures*
69
+ _RESERVED_ADD_ROI_KEYS = frozenset({"mask", "color", "name"})
70
+
66
71
 
67
72
  def _resolved_rtss_path(rtss_path: pathlib.Path) -> pathlib.Path:
68
73
  """Return the path rt-utils will actually write *rtss_path* to.
@@ -97,6 +102,8 @@ def save_structure_set(
97
102
  rtss_path: str | pathlib.Path,
98
103
  lps_image: sitk.Image,
99
104
  original_image: sitk.Image | None = None,
105
+ *,
106
+ add_roi_kwargs: Mapping[str, Any] | None = None,
100
107
  ) -> int:
101
108
  """Write every ROI of *structure_set* to an RT-STRUCT file.
102
109
 
@@ -115,13 +122,15 @@ def save_structure_set(
115
122
  original_image: The CT before LPS alignment
116
123
  (``SeriesInfo["original_sitk_image"]``). ``None`` when the series
117
124
  needed no reorientation; the masks are then written as they are.
125
+ add_roi_kwargs: Forwarded to :func:`mask2rtstruct`.
118
126
 
119
127
  Returns:
120
128
  The number of ROIs written.
121
129
 
122
130
  Raises:
123
131
  ValueError: If *structure_set* contains no ROI with a usable mask,
124
- since that would write an RT-STRUCT with no structures at all.
132
+ since that would write an RT-STRUCT with no structures at all,
133
+ or if *add_roi_kwargs* contains a reserved key.
125
134
  RuntimeError: If rt-utils rejects an ROI (propagated from
126
135
  :func:`mask2rtstruct`).
127
136
  """
@@ -146,7 +155,9 @@ def save_structure_set(
146
155
  if not structures:
147
156
  raise ValueError("Structure set contains no ROI with a mask to save.")
148
157
 
149
- written_path = mask2rtstruct(ct_dir, rtss_path, structures)
158
+ written_path = mask2rtstruct(
159
+ ct_dir, rtss_path, structures, add_roi_kwargs=add_roi_kwargs
160
+ )
150
161
  logger.info(f"Structure set saved to '{written_path}' ({len(structures)} ROIs).")
151
162
  return len(structures)
152
163
 
@@ -333,6 +344,7 @@ def mask2rtstruct(
333
344
  structures: dict[int, dict[str, Any]],
334
345
  *,
335
346
  replace_existing: bool = True,
347
+ add_roi_kwargs: Mapping[str, Any] | None = None,
336
348
  ) -> pathlib.Path:
337
349
  """Write ``(D, H, W)`` mask arrays to an RT-STRUCT DICOM file.
338
350
 
@@ -346,17 +358,32 @@ def mask2rtstruct(
346
358
  rebuilt so it holds exactly *structures*. ``False`` appends to the
347
359
  existing file instead; rt-utils cannot remove ROIs, so saving the
348
360
  same ROIs twice that way duplicates them.
361
+ add_roi_kwargs: Extra keyword arguments forwarded to rt-utils'
362
+ ``RTStruct.add_roi`` for every ROI, e.g.
363
+ ``{"approximate_contours": False, "use_pin_hole": True}``.
364
+ ``mask``, ``color`` and ``name`` are taken from *structures*
365
+ and must not be given here.
349
366
 
350
367
  Returns:
351
368
  The path actually written.
352
369
 
353
370
  Raises:
354
- ValueError: If *rtss_path* is ``None``.
355
- RuntimeError: If any ROI cannot be added to the RT-STRUCT builder.
371
+ ValueError: If *rtss_path* is ``None`` or *add_roi_kwargs* contains
372
+ a reserved key.
373
+ RuntimeError: If any ROI cannot be added to the RT-STRUCT builder
374
+ (including unknown keys in *add_roi_kwargs*).
356
375
  """
357
376
  if rtss_path is None:
358
377
  raise ValueError("rtss_path must not be None; provide a concrete output path.")
359
378
 
379
+ roi_options = dict(add_roi_kwargs or {})
380
+ reserved = _RESERVED_ADD_ROI_KEYS & roi_options.keys()
381
+ if reserved:
382
+ raise ValueError(
383
+ f"add_roi_kwargs must not contain {sorted(reserved)}; "
384
+ "they are taken from structures."
385
+ )
386
+
360
387
  ct_dir = pathlib.Path(ct_dir)
361
388
  rtss_path = _resolved_rtss_path(pathlib.Path(rtss_path))
362
389
 
@@ -382,6 +409,7 @@ def mask2rtstruct(
382
409
  mask=np.transpose(roi_data["mask"], (1, 2, 0)).astype(bool, copy=False),
383
410
  color=roi_data["color"],
384
411
  name=roi_name,
412
+ **roi_options,
385
413
  )
386
414
  except Exception as exc:
387
415
  logger.error(f"Failed to add ROI '{roi_name}': {exc}")
@@ -29,6 +29,11 @@ Zoom:
29
29
  each view independently (``set_zoom`` / ``get_zoom`` / ``reset_zoom``).
30
30
  The views fill their layout cells; a new image or layout starts fitted.
31
31
 
32
+ Pan:
33
+ Dragging with the middle button (the wheel pressed) moves the view under
34
+ the pointer, each view independently and at any zoom, even while the brush
35
+ is active. The view cannot leave the slice; ``reset_zoom`` fits it again.
36
+
32
37
  Window / level:
33
38
  Right-click drag: horizontal -> width, vertical -> centre, applied to
34
39
  ``state.window_level_target``; Shift targets the other image for that
@@ -879,7 +884,10 @@ class DicomViewer(ttk.Frame):
879
884
  self.canvas.draw_idle()
880
885
 
881
886
  def reset_zoom(self, axis: str | None = None) -> None:
882
- """Fit the whole slice into *axis*, or into every view when ``None``."""
887
+ """Fit the whole slice into *axis*, or into every view when ``None``.
888
+
889
+ This also undoes any pan: a fitted view is centred on the slice.
890
+ """
883
891
  for name in [axis] if axis is not None else list(self.axs):
884
892
  self.set_zoom(name, 1.0)
885
893
 
@@ -18,7 +18,7 @@ import SimpleITK as sitk
18
18
  from matplotlib.backends.backend_agg import FigureCanvasAgg
19
19
  from matplotlib.figure import Figure
20
20
 
21
- from tk_rt_viewer.event_controllers.viewer_events import ViewerEventHandler
21
+ from tk_rt_viewer.event_controllers.viewer_events import ZOOM_STEP, ViewerEventHandler
22
22
  from tk_rt_viewer.protocols import ViewerHost
23
23
  from tk_rt_viewer.rendering.view_axes import ImageViewAxes
24
24
  from tk_rt_viewer.state.viewer_state import SliceViewerState
@@ -365,7 +365,7 @@ class TestZoom:
365
365
  ScrollEvent(step=1, xdata=anchor[0], ydata=anchor[1], modifiers={"ctrl"})
366
366
  )
367
367
  axial.apply_aspect()
368
- assert axial.zoom_factor() == pytest.approx(1.25)
368
+ assert axial.zoom_factor() == pytest.approx(ZOOM_STEP)
369
369
  assert x_fraction(axial, anchor[0]) == pytest.approx(frac)
370
370
  assert dict(state.indices) == before # no slice scroll
371
371
  assert axial.yaxis_inverted() # radiological orientation kept
@@ -390,7 +390,7 @@ class TestZoom:
390
390
  state, handler, axial, _coronal = self._setup()
391
391
  state.set_brush_tool_active(True)
392
392
  handler.on_scroll(ScrollEvent(step=1, xdata=8.0, ydata=4.0, modifiers={"ctrl"}))
393
- assert axial.zoom_factor() == pytest.approx(1.25)
393
+ assert axial.zoom_factor() == pytest.approx(ZOOM_STEP)
394
394
 
395
395
  def test_a_resize_keeps_the_zoom_and_the_centre(self) -> None:
396
396
  _state, _handler, axial, _coronal = self._setup()
@@ -418,6 +418,154 @@ class TestZoom:
418
418
  assert "aspect" not in caplog.text
419
419
 
420
420
 
421
+ class TestPan:
422
+ def _setup(self, zoom: float = 3.0):
423
+ state = loaded_state((8, 16, 32))
424
+ axial = zoomable_axes(state, "axial")
425
+ handler, viewer = handler_for(state, FakeViewer({"axial": axial}))
426
+ handler.on_enter_axes(Event(inaxes=axial))
427
+ axial.zoom_to(zoom, anchor=(16.0, 8.0))
428
+ return state, handler, axial
429
+
430
+ @staticmethod
431
+ def _display_of(ax, point) -> np.ndarray:
432
+ return ax.transData.transform(point)
433
+
434
+ def test_the_image_follows_the_pointer(self) -> None:
435
+ _state, handler, axial = self._setup()
436
+ start = (200.0, 120.0)
437
+ grabbed = axial.transData.inverted().transform(start)
438
+ handler.on_press(Event(button=2, x=start[0], y=start[1]))
439
+ handler.on_motion(Event(button=2, x=start[0] + 15, y=start[1] + 9))
440
+ # The data point under the pointer at the press is still under it
441
+ assert self._display_of(axial, grabbed) == pytest.approx(
442
+ (start[0] + 15, start[1] + 9)
443
+ )
444
+ assert axial.zoom_factor() == pytest.approx(3.0)
445
+ assert axial.yaxis_inverted() # radiological orientation kept
446
+
447
+ def test_the_drag_is_measured_from_the_press(self) -> None:
448
+ _state, handler, axial = self._setup()
449
+ handler.on_press(Event(button=2, x=200, y=120))
450
+ handler.on_motion(Event(button=2, x=215, y=129))
451
+ handler.on_motion(Event(button=2, x=170, y=100))
452
+ handler.on_motion(Event(button=2, x=215, y=129))
453
+ grabbed_after_a = axial.view_center()
454
+ handler.on_motion(Event(button=2, x=170, y=100))
455
+ handler.on_motion(Event(button=2, x=215, y=129))
456
+ assert axial.view_center() == pytest.approx(grabbed_after_a)
457
+
458
+ def test_the_view_stays_on_the_slice(self) -> None:
459
+ state, handler, axial = self._setup()
460
+ x0, x1, y0, y1 = state.get_extent("axial")
461
+ handler.on_press(Event(button=2, x=200, y=120))
462
+ for dx, dy in [(10_000, 10_000), (-10_000, -10_000)]:
463
+ handler.on_motion(Event(button=2, x=200 + dx, y=120 + dy))
464
+ assert min(axial.get_xlim()) >= x0 - 1e-9
465
+ assert max(axial.get_xlim()) <= x1 + 1e-9
466
+ assert min(axial.get_ylim()) >= min(y0, y1) - 1e-9
467
+ assert max(axial.get_ylim()) <= max(y0, y1) + 1e-9
468
+
469
+ def test_a_fitted_view_does_not_move(self) -> None:
470
+ _state, handler, axial = self._setup(zoom=1.0)
471
+ before = [*axial.get_xlim(), *axial.get_ylim()]
472
+ handler.on_press(Event(button=2, x=200, y=120))
473
+ handler.on_motion(Event(button=2, x=260, y=60))
474
+ assert [*axial.get_xlim(), *axial.get_ylim()] == pytest.approx(before)
475
+
476
+ def test_release_ends_the_drag(self) -> None:
477
+ _state, handler, axial = self._setup()
478
+ handler.on_press(Event(button=2, x=200, y=120))
479
+ handler.on_motion(Event(button=2, x=215, y=129))
480
+ handler.on_release(Event(button=2, x=215, y=129))
481
+ centre = axial.view_center()
482
+ handler.on_motion(Event(button=2, x=300, y=200))
483
+ assert axial.view_center() == centre
484
+
485
+ def test_a_lost_release_ends_the_drag(self) -> None:
486
+ _state, handler, axial = self._setup()
487
+ handler.on_press(Event(button=2, x=200, y=120))
488
+ handler.on_motion(Event(button=2, x=215, y=129))
489
+ centre = axial.view_center()
490
+ handler.on_motion(Event(button=None, x=300, y=200)) # no button held
491
+ assert axial.view_center() == centre
492
+ handler.on_motion(Event(button=2, x=320, y=220))
493
+ assert axial.view_center() == centre
494
+
495
+ def test_pan_works_with_the_brush_active(self) -> None:
496
+ state, handler, axial = self._setup()
497
+ state.set_brush_tool_active(True)
498
+ centre = axial.view_center()
499
+ handler.on_press(Event(button=2, x=200, y=120))
500
+ handler.on_motion(Event(button=2, x=215, y=129))
501
+ handler.on_release(Event(button=2, x=215, y=129))
502
+ assert axial.view_center() != centre
503
+ assert not handler.brush_handler.is_dragging
504
+
505
+ def test_other_buttons_do_not_pan(self) -> None:
506
+ state, handler, axial = self._setup()
507
+ centre = axial.view_center()
508
+ window_level = state.window_level
509
+ handler.on_press(Event(button=1, x=200, y=120))
510
+ handler.on_motion(Event(button=1, x=215, y=129))
511
+ handler.on_release(Event(button=1, x=215, y=129))
512
+ assert axial.view_center() == centre
513
+ assert state.window_level == window_level
514
+
515
+ def test_the_toolbar_owns_the_mouse(self) -> None:
516
+ _state, handler, axial = self._setup()
517
+ handler.viewer.toolbar_mode = "pan/zoom"
518
+ centre = axial.view_center()
519
+ handler.on_press(Event(button=2, x=200, y=120))
520
+ handler.on_motion(Event(button=2, x=215, y=129))
521
+ assert axial.view_center() == centre
522
+
523
+ def test_a_press_outside_every_view_is_ignored(self) -> None:
524
+ _state, handler, axial = self._setup()
525
+ handler.on_leave_axes(Event(inaxes=None))
526
+ centre = axial.view_center()
527
+ handler.on_press(Event(button=2, x=200, y=120))
528
+ handler.on_motion(Event(button=2, x=215, y=129))
529
+ assert axial.view_center() == centre
530
+
531
+ def test_activating_the_brush_cancels_a_pan(self) -> None:
532
+ state, handler, axial = self._setup()
533
+ handler.on_press(Event(button=2, x=200, y=120))
534
+ state.set_brush_tool_active(True)
535
+ centre = axial.view_center()
536
+ handler.on_motion(Event(button=2, x=215, y=129))
537
+ assert axial.view_center() == centre
538
+
539
+
540
+ class TestImageViewAxesPan:
541
+ def test_pan_to_moves_the_centre_and_keeps_the_zoom(self) -> None:
542
+ state = loaded_state((8, 16, 32))
543
+ axial = zoomable_axes(state, "axial")
544
+ axial.zoom_to(4.0)
545
+ axial.pan_to(5.0, 3.0)
546
+ assert axial.view_center() == pytest.approx((5.0, 3.0))
547
+ assert axial.zoom_factor() == pytest.approx(4.0)
548
+
549
+ def test_pan_to_is_clamped_to_the_slice(self) -> None:
550
+ state = loaded_state((8, 16, 32))
551
+ axial = zoomable_axes(state, "axial")
552
+ x0, x1, _y0, _y1 = state.get_extent("axial")
553
+ axial.zoom_to(4.0)
554
+ axial.pan_to(1e6, 1e6)
555
+ assert max(axial.get_xlim()) == pytest.approx(x1)
556
+ axial.pan_to(-1e6, -1e6)
557
+ assert min(axial.get_xlim()) == pytest.approx(x0)
558
+
559
+ def test_fitting_again_undoes_the_pan(self) -> None:
560
+ state = loaded_state((8, 16, 32))
561
+ axial = zoomable_axes(state, "axial")
562
+ fitted = axial.view_center()
563
+ axial.zoom_to(4.0)
564
+ axial.pan_to(5.0, 3.0)
565
+ axial.zoom_to(1.0)
566
+ assert axial.view_center() == pytest.approx(fitted)
567
+
568
+
421
569
  class TestKeyboardNavigation:
422
570
  @pytest.mark.parametrize(
423
571
  "key,expected", [("up", 5), ("down", 3), ("pageup", 7), ("pagedown", 0)]
@@ -22,16 +22,17 @@ from tk_rt_viewer.state.viewer_state import StructureSet
22
22
 
23
23
  @pytest.fixture()
24
24
  def captured_structures(monkeypatch) -> dict:
25
- """Capture the structures dict (and replace_existing) passed to mask2rtstruct."""
25
+ """Capture the arguments passed to mask2rtstruct."""
26
26
  captured: dict = {}
27
27
 
28
28
  def fake_mask2rtstruct(
29
- ct_dir, rtss_path, structures, *, replace_existing=True
29
+ ct_dir, rtss_path, structures, *, replace_existing=True, add_roi_kwargs=None
30
30
  ) -> pathlib.Path:
31
31
  captured["ct_dir"] = ct_dir
32
32
  captured["rtss_path"] = rtss_path
33
33
  captured["structures"] = structures
34
34
  captured["replace_existing"] = replace_existing
35
+ captured["add_roi_kwargs"] = add_roi_kwargs
35
36
  return pathlib.Path(rtss_path)
36
37
 
37
38
  monkeypatch.setattr(rtstruct_io, "mask2rtstruct", fake_mask2rtstruct)
@@ -142,6 +143,22 @@ class TestSaveStructureSet:
142
143
 
143
144
  assert captured_structures["replace_existing"] is True
144
145
 
146
+ def test_add_roi_kwargs_is_forwarded(self, captured_structures) -> None:
147
+ lps = _image()
148
+ structure_set = StructureSet()
149
+ structure_set.add("PTV", _mask(lps), "#ff0000")
150
+ options = {"approximate_contours": False}
151
+
152
+ rtstruct_io.save_structure_set(
153
+ structure_set,
154
+ "/ct",
155
+ "/out/rs.dcm",
156
+ lps_image=lps,
157
+ add_roi_kwargs=options,
158
+ )
159
+
160
+ assert captured_structures["add_roi_kwargs"] == options
161
+
145
162
 
146
163
  class TestSaveStructureSetResampling:
147
164
  """Resampling must happen only when there is a different geometry to reach."""
@@ -344,6 +361,92 @@ class TestMask2RtStructImplicitDcmSuffix:
344
361
  assert written == out
345
362
 
346
363
 
364
+ class TestMask2RtStructAddRoiKwargs:
365
+ """``add_roi_kwargs`` reaches ``RTStruct.add_roi`` for every ROI."""
366
+
367
+ @staticmethod
368
+ def _structures() -> dict:
369
+ mask = np.zeros((4, 8, 8), dtype=bool)
370
+ mask[1:3, 2:6, 2:6] = True
371
+ return {
372
+ 1: {"name": "PTV", "mask": mask, "color": "#ff0000"},
373
+ 2: {"name": "CTV", "mask": mask.copy(), "color": "#00ff00"},
374
+ }
375
+
376
+ @staticmethod
377
+ def _ct_dir(tmp_path) -> pathlib.Path:
378
+ ct_dir = tmp_path / "ct"
379
+ ct_dir.mkdir()
380
+ _write_minimal_ct_series(ct_dir)
381
+ return ct_dir
382
+
383
+ def test_options_are_passed_to_every_add_roi_call(
384
+ self, tmp_path, monkeypatch
385
+ ) -> None:
386
+ from rt_utils import RTStruct
387
+
388
+ calls: list[dict] = []
389
+ real_add_roi = RTStruct.add_roi
390
+
391
+ def spy(self, **kwargs):
392
+ calls.append(kwargs)
393
+ return real_add_roi(self, **kwargs)
394
+
395
+ monkeypatch.setattr(RTStruct, "add_roi", spy)
396
+
397
+ rtstruct_io.mask2rtstruct(
398
+ self._ct_dir(tmp_path),
399
+ tmp_path / "rs.dcm",
400
+ self._structures(),
401
+ add_roi_kwargs={"approximate_contours": False, "description": "auto"},
402
+ )
403
+
404
+ assert len(calls) == 2
405
+ assert all(c["approximate_contours"] is False for c in calls)
406
+ assert all(c["description"] == "auto" for c in calls)
407
+
408
+ def test_none_keeps_the_rt_utils_defaults(self, tmp_path, monkeypatch) -> None:
409
+ from rt_utils import RTStruct
410
+
411
+ calls: list[dict] = []
412
+ real_add_roi = RTStruct.add_roi
413
+
414
+ def spy(self, **kwargs):
415
+ calls.append(kwargs)
416
+ return real_add_roi(self, **kwargs)
417
+
418
+ monkeypatch.setattr(RTStruct, "add_roi", spy)
419
+
420
+ rtstruct_io.mask2rtstruct(
421
+ self._ct_dir(tmp_path), tmp_path / "rs.dcm", self._structures()
422
+ )
423
+
424
+ assert all(set(c) == {"mask", "color", "name"} for c in calls)
425
+
426
+ @pytest.mark.parametrize("key", ["mask", "color", "name"])
427
+ def test_reserved_keys_are_rejected_before_writing(self, tmp_path, key) -> None:
428
+ out = tmp_path / "rs.dcm"
429
+
430
+ with pytest.raises(ValueError, match=key):
431
+ rtstruct_io.mask2rtstruct(
432
+ tmp_path / "missing_ct",
433
+ out,
434
+ self._structures(),
435
+ add_roi_kwargs={key: None},
436
+ )
437
+
438
+ assert not out.exists()
439
+
440
+ def test_an_unknown_option_raises_runtime_error(self, tmp_path) -> None:
441
+ with pytest.raises(RuntimeError, match="PTV"):
442
+ rtstruct_io.mask2rtstruct(
443
+ self._ct_dir(tmp_path),
444
+ tmp_path / "rs.dcm",
445
+ self._structures(),
446
+ add_roi_kwargs={"no_such_option": True},
447
+ )
448
+
449
+
347
450
  class TestLoadRtStructDuplicateNames:
348
451
  """Pins a 2.0.1 fix: two ROIs sharing a name must not collapse onto one mask.
349
452
 
File without changes
File without changes