Files
ezDent-MacOS/Sources/EzDent/DICOMViewer.swift
T

191 lines
7.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import AppKit
import SwiftUI
struct DICOMViewer: View {
let urls: [URL]
let name: String
@State private var volume: DICOMVolume?
@State private var error: String?
@State private var exportError: String?
@State private var plane = DICOMVolume.Plane.slices
@State private var index = 0.0
@State private var center = 0.0
@State private var width = 1.0
@State private var renderer: VolumeRenderer?
@State private var show3D = false
@State private var surface = true
@State private var rotation = SIMD2<Float>(0.4, -0.3)
@State private var dragOrigin: SIMD2<Float>?
@State private var zoom = 1.0
var body: some View {
Group {
if let volume {
viewer(volume)
} else if let error {
Text(error).padding()
} else {
ProgressView("Загрузка DICOM…")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.alert("Не удалось экспортировать DICOM", isPresented: Binding(
get: { exportError != nil },
set: { if !$0 { exportError = nil } }
)) {
Button("Закрыть", role: .cancel) {}
} message: {
Text(exportError ?? "")
}
.task {
do {
let urls = self.urls
let loaded = try await Task.detached(priority: .userInitiated) {
try DICOMVolume(urls: urls)
}.value
guard !Task.isCancelled else { return }
resetWindow(loaded)
index = Double(loaded.size.z / 2)
volume = loaded
} catch {
self.error = error.localizedDescription
}
}
}
private func viewer(_ volume: DICOMVolume) -> some View {
VStack(spacing: 0) {
HStack {
if volume.spacing != nil {
Picker("Режим", selection: $show3D) {
Text("Срезы").tag(false)
Text("3D").tag(true)
}
.pickerStyle(.segmented)
.frame(width: 145)
.onChange(of: show3D) { is3D in
if is3D && renderer == nil { renderer = VolumeRenderer(volume: volume) }
}
if !show3D {
Picker("Плоскость", selection: $plane) {
ForEach(DICOMVolume.Plane.allCases) { Text($0.rawValue).tag($0) }
}
.onChange(of: plane) { index = Double(volume.count($0) / 2) }
} else {
Picker("Проекция", selection: $surface) {
Text("Поверхность").tag(true)
Text("Максимум (MIP)").tag(false)
}
Button("Сбросить ракурс") {
zoom = 1
rotation = SIMD2(0.4, -0.3)
}
}
}
Spacer()
Text("DICOM • \(volume.size.x) × \(volume.size.y) × \(volume.size.z)")
.font(.caption)
.foregroundStyle(.secondary)
Button {
exportOriginals()
} label: {
Label("Экспорт DICOM…", systemImage: "square.and.arrow.up")
.labelStyle(.iconOnly)
}
.help("Экспортировать исходные файлы DICOM")
}
.padding(10)
ZStack {
Color.black
if show3D {
if let renderer {
VolumeProjection(renderer: renderer, rotation: rotation, zoom: Float(zoom),
window: SIMD2(Float(center), Float(width)), surface: surface)
.overlay {
Color.clear.contentShape(Rectangle())
.gesture(DragGesture()
.onChanged {
let start = dragOrigin ?? rotation
dragOrigin = start
rotation = start + SIMD2(Float($0.translation.width), Float($0.translation.height)) * 0.01
}
.onEnded { _ in dragOrigin = nil })
}
} else {
Text("3D недоступно на этом Mac").foregroundStyle(.white)
}
} else if let (image, aspect) = volume.image(plane, index: min(Int(index), volume.count(plane) - 1),
center: Float(center), span: Float(width)) {
Image(decorative: image, scale: 1)
.resizable()
.aspectRatio(aspect, contentMode: .fit)
.accessibilityLabel("Срез DICOM")
.padding(12)
}
}
VStack(spacing: 6) {
if show3D {
Slider(value: $zoom, in: 0.5...3) { Text("Масштаб 3D") }
} else if volume.count(plane) > 1 {
Slider(value: $index, in: 0...Double(volume.count(plane) - 1), step: 1) {
Text("Срез \(min(Int(index) + 1, volume.count(plane))) из \(volume.count(plane))")
}
}
if volume.rgb == nil {
HStack {
Slider(value: $center, in: centerRange(volume)) { Text(show3D && surface ? "Порог" : "Уровень") }
if !show3D || !surface {
Slider(value: $width, in: 1...windowLimit(volume)) { Text("Окно") }
}
Button("Сбросить окно") { resetWindow(volume) }
}
}
}
.padding(10)
}
}
private func exportOriginals() {
let panel = NSSavePanel()
panel.nameFieldStringValue = urls.count == 1 ? name : "Серия DICOM"
guard panel.runModal() == .OK, let destination = panel.url else { return }
do {
if urls.count == 1 {
try Data(contentsOf: urls[0], options: .mappedIfSafe).write(to: destination, options: .atomic)
return
}
let manager = FileManager.default
try manager.createDirectory(at: destination, withIntermediateDirectories: false)
do {
for source in urls {
try manager.copyItem(at: source, to: destination.appendingPathComponent(source.lastPathComponent))
}
} catch {
try? manager.removeItem(at: destination)
throw error
}
} catch {
exportError = error.localizedDescription
}
}
private func centerRange(_ volume: DICOMVolume) -> ClosedRange<Double> {
let preset = volume.window?.x ?? volume.minimum
return Double(min(volume.minimum, preset))...Double(max(volume.minimum + 1, volume.maximum, preset))
}
private func resetWindow(_ volume: DICOMVolume) {
let span = max(2, Double(volume.maximum - volume.minimum))
center = volume.window.map { Double($0.x) } ?? (Double(volume.minimum) + span / 2)
width = volume.window.map { Double($0.y) } ?? span
}
private func windowLimit(_ volume: DICOMVolume) -> Double {
max(2, Double(volume.maximum - volume.minimum), Double(volume.window?.y ?? 1))
}
}