SPB Git

Repository Public License

QualityLabView.swift 31.4 KB 544 lines swift

1// ORIX Convert — App/Sources/Features/QualityLab/QualityLabView.swift2// Description: Quality Lab: a trial conversion compared with its source — pictures in a synchronized, zoomable3//              canvas (side by side, split, difference), stacked waveforms for audio, and a table of facts read4//              from both files. Every number shown is read or measured; nothing is scored.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import EngineImage8import SwiftUI910struct QualityLabView: View {11    @Environment(AppModel.self) private var model1213    var body: some View {14        let lab = model.qualityLab15        VStack(spacing: 0) {16            HeaderBar(title: L("Quality Lab"), subtitle: subtitle(lab)) {17                if lab.visual == .picture {18                    LabModePicker(lab: lab)19                    ZoomControls(viewport: lab.viewport)20                }21                Button { lab.choose() } label: { Label(lab.source == nil ? L("Choose File…") : L("Change File…"), systemImage: "doc.badge.plus") }22                    .buttonStyle(SecondaryButtonStyle())23            }24            if lab.source == nil {25                EmptyState(symbol: "slider.horizontal.below.square.and.square.filled", title: L("Compare before you convert"),26                           message: L("Drop a file here or choose one. Quality Lab converts it into a temporary folder with the settings you pick, then shows the original and the result side by side with what was really measured. Nothing is written next to your file."),27                           actionTitle: L("Choose File…")) { lab.choose() }28            } else {29                GeometryReader { geo in30                    let panelWidth: CGFloat = geo.size.width < 980 ? 300 : ORIX.Metric.sidePanelWidth31                    HStack(spacing: 0) {32                        VStack(spacing: 0) {33                            LabStage(lab: lab)34                            LabBottomBar(lab: lab, narrow: geo.size.width - panelWidth < 620)35                        }36                        ORIX.Palette.hairline.frame(width: 1)37                        LabPanel(lab: lab).frame(width: panelWidth)38                    }39                }40            }41        }42    }4344    private func subtitle(_ lab: QualityLabModel) -> String? {45        guard let source = lab.source else { return L("Trial conversions with measured before / after") }46        if let choice = lab.choice { return "\(source.lastPathComponent) → \(choice.title)" }47        return source.lastPathComponent48    }49}5051private struct LabModePicker: View {52    let lab: QualityLabModel53    var body: some View {54        HStack(spacing: 2) {55            ForEach(LabViewMode.allCases) { mode in56                let selected = lab.viewMode == mode57                Button { lab.viewMode = mode } label: {58                    Image(systemName: mode.symbol).font(.system(size: 12, weight: selected ? .semibold : .regular))59                        .foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textSecondary)60                        .frame(width: 30, height: 24)61                        .background(selected ? ORIX.Palette.surface : .clear, in: RoundedRectangle(cornerRadius: 7, style: .continuous))62                        .overlay(RoundedRectangle(cornerRadius: 7, style: .continuous).strokeBorder(selected ? ORIX.Palette.hairlineStrong : .clear, lineWidth: 1))63                        .contentShape(Rectangle())64                }65                .buttonStyle(.plain)66                .help(mode.title)67                .accessibilityLabel(mode.title)68                .accessibilityAddTraits(selected ? [.isSelected] : [])69            }70        }71        .padding(2)72        .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: 9, style: .continuous))73        .overlay(RoundedRectangle(cornerRadius: 9, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))74        .accessibilityElement(children: .contain)75        .accessibilityLabel(L("Comparison view"))76    }77}7879// MARK: - Stage8081private struct LabStage: View {82    let lab: QualityLabModel8384    var body: some View {85        ZStack {86            ORIX.Palette.surfaceSunken87            switch lab.visual {88            case .picture: picture89            case .waveform: waveform90            case .unavailable(let text):91                EmptyState(symbol: "eye.slash", title: L("No visual comparison"), message: text)92            case .none: waiting93            }94            if lab.phase == .converting, lab.visual != .none {95                // A newer run is converting: the previous comparison stays visible underneath.96                VStack { Spacer(); ConvertingChip(lab: lab).padding(.bottom, ORIX.Space.l) }97            }98        }99        .frame(maxWidth: .infinity, maxHeight: .infinity)100    }101102    @ViewBuilder private var picture: some View {103        if let left = lab.leftPreview, let right = lab.rightPreview {104            let resultLabel = lab.resultFile?.detection.format?.shortLabel ?? L("Result")105            let difference = lab.viewMode == .difference106            let rightLayer: CanvasLayer = difference ? .image(preview: lab.differenceImage ?? right, detail: nil) : .image(preview: right, detail: lab.rightDetail)107            let mode: CanvasMode = switch lab.viewMode {108            case .sideBySide: .sideBySide109            case .split: .split110            case .original: .original111            case .result, .difference: .result112            }113            CompareCanvas(left: .image(preview: left, detail: lab.leftDetail), right: rightLayer, leftLabel: L("Original"),114                          rightLabel: difference ? L("Difference × %lld", lab.differenceGain) : resultLabel, mode: mode, imageSize: lab.imageSize,115                          viewport: lab.viewport, checkerboard: !difference) { lab.hover($0) }116                .accessibilityElement(children: .ignore)117                .accessibilityLabel(L("Comparison of the original and the converted picture"))118                .accessibilityValue(canvasValue)119                .accessibilityAdjustableAction { direction in120                    guard lab.viewMode == .split else { return }121                    lab.viewport.split = min(1, max(0, lab.viewport.split + (direction == .increment ? 0.05 : -0.05)))122                }123                .accessibilityHint(lab.viewMode == .split ? L("Adjust to move the split between the original and the result.") : "")124        } else {125            waiting126        }127    }128129    private var canvasValue: String {130        var parts = [lab.viewMode.title, L("zoom %@", lab.viewport.percentText)]131        if lab.viewMode == .split { parts.append(L("split at %@", Fmt.percent(lab.viewport.split))) }132        return parts.joined(separator: ", ")133    }134135    @ViewBuilder private var waveform: some View {136        if lab.leftWave != nil || lab.rightWave != nil {137            WaveformCompare(top: lab.leftWave, bottom: lab.rightWave, topLabel: L("Original"), bottomLabel: lab.resultFile?.detection.format?.shortLabel ?? L("Result"),138                            viewport: lab.waveViewport)139                .padding(ORIX.Space.l)140                .accessibilityElement(children: .ignore)141                .accessibilityLabel(L("Waveforms of the original and the result, on the same time axis"))142                .accessibilityValue(waveValue)143                .accessibilityAdjustableAction { direction in lab.waveViewport.scroll(by: direction == .increment ? 0.25 : -0.25) }144        } else {145            waiting146        }147    }148149    private var waveValue: String {150        guard let duration = lab.leftWave?.durationSeconds ?? lab.rightWave?.durationSeconds else { return "" }151        let start = lab.waveViewport.start * duration, length = duration / lab.waveViewport.zoom152        return L("Showing %@ to %@ of %@", Fmt.duration(start), Fmt.duration(start + length), Fmt.duration(duration))153    }154155    private var waiting: some View {156        VStack(spacing: ORIX.Space.m) {157            switch lab.phase {158            case .failed(let message):159                Image(systemName: "xmark.octagon").font(.system(size: 34, weight: .light)).foregroundStyle(ORIX.Palette.danger).accessibilityHidden(true)160                Text(L("The trial conversion failed")).font(.title3.weight(.semibold))161                Text(message).font(.callout).foregroundStyle(ORIX.Palette.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 440).textSelection(.enabled)162                Button(L("Try Again")) { lab.rerun() }.buttonStyle(SecondaryButtonStyle(prominent: true))163            case .converting:164                ORIXProgressRing(fraction: lab.progress?.fraction, size: 34, lineWidth: 3.5, label: L("Trial conversion"))165                Text(L("Converting a trial copy…")).font(.title3.weight(.semibold))166                Text(lab.progress?.message.map { LE($0) } ?? L("The result goes to a temporary folder.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)167                Button(L("Cancel")) { lab.cancelTrial() }.buttonStyle(SecondaryButtonStyle())168            case .analysing:169                ORIXProgressRing(fraction: nil, size: 28, lineWidth: 3, label: L("Analysing"))170                Text(L("Reading the file…")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)171            default:172                if lab.isLoadingPictures {173                    ORIXProgressRing(fraction: nil, size: 28, lineWidth: 3, label: L("Decoding"))174                    Text(L("Decoding both files…")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)175                } else {176                    Image(systemName: "arrow.right.circle").font(.system(size: 34, weight: .light)).foregroundStyle(ORIX.Palette.transformationDiagonal).accessibilityHidden(true)177                    Text(L("Choose a destination to start the trial")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)178                }179            }180        }181        .padding(ORIX.Space.xxl)182    }183}184185private struct ConvertingChip: View {186    let lab: QualityLabModel187    var body: some View {188        HStack(spacing: 8) {189            ORIXProgressRing(fraction: lab.progress?.fraction, size: 14, lineWidth: 2, label: L("Trial conversion"))190            Text(L("Converting with the new settings…")).font(.caption.weight(.medium)).foregroundStyle(ORIX.Palette.textPrimary)191            Button(L("Cancel")) { lab.cancelTrial() }.buttonStyle(.plain).font(.caption.weight(.semibold)).foregroundStyle(ORIX.Palette.accent)192        }193        .padding(.horizontal, 12).padding(.vertical, 7)194        .background(ORIX.Palette.surfaceRaised, in: Capsule())195        .overlay(Capsule().strokeBorder(ORIX.Palette.hairlineStrong, lineWidth: 1))196        .shadow(color: .black.opacity(0.15), radius: 8, y: 2)197    }198}199200// MARK: - Bottom bar (pixel inspector, page, time)201202private struct LabBottomBar: View {203    let lab: QualityLabModel204    let narrow: Bool205206    var body: some View {207        if lab.visual == .picture || lab.visual == .waveform {208            HStack(spacing: ORIX.Space.l) {209                if lab.visual == .picture {210                    PixelInspector(lab: lab, compact: narrow)211                    Spacer(minLength: ORIX.Space.s)212                    if lab.viewMode == .difference {213                        Picker(L("Amplification"), selection: Binding(get: { lab.differenceGain }, set: { lab.differenceGain = $0 })) {214                            ForEach([1, 4, 16, 64], id: \.self) { Text("× \($0)").tag($0) }215                        }216                        .pickerStyle(.menu).fixedSize().controlSize(.small)217                        .help(L("The absolute difference of each channel is multiplied by this factor."))218                    }219                    if let duration = lab.duration {220                        HStack(spacing: 6) {221                            Image(systemName: "timer").font(.caption).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)222                            Slider(value: Binding(get: { lab.time }, set: { lab.time = $0 }), in: 0...max(0.01, duration - 0.01))223                                .frame(minWidth: 90, maxWidth: 220).controlSize(.small)224                                .accessibilityLabel(L("Frame time"))225                                .accessibilityValue(Fmt.duration(lab.time))226                            Text(WaveformNSView.timeText(lab.time, step: 0.01)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary).frame(minWidth: 52, alignment: .trailing)227                        }228                    }229                    if lab.pageCount > 1 {230                        HStack(spacing: 2) {231                            IconButton(symbol: "chevron.left", label: L("Previous page")) { lab.page = max(0, lab.page - 1) }.disabled(lab.page == 0)232                            Text(L("Page %lld of %lld", lab.page + 1, lab.pageCount)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary)233                            IconButton(symbol: "chevron.right", label: L("Next page")) { lab.page = min(lab.pageCount - 1, lab.page + 1) }.disabled(lab.page >= lab.pageCount - 1)234                        }235                    }236                } else {237                    Label(L("Peaks (lowest and highest sample) measured by the media engine, both files on one time axis."), systemImage: "waveform")238                        .font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2)239                    Spacer(minLength: ORIX.Space.s)240                    HStack(spacing: 2) {241                        IconButton(symbol: "minus.magnifyingglass", label: L("Zoom Out")) { lab.waveViewport.zoomOut() }242                        Text("× " + lab.waveViewport.zoom.formatted(.number.precision(.fractionLength(0...1)))).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textPrimary).frame(minWidth: 44)243                            .accessibilityLabel(L("Time zoom"))244                        IconButton(symbol: "plus.magnifyingglass", label: L("Zoom In")) { lab.waveViewport.zoomIn() }245                        IconButton(symbol: "arrow.left.and.right", label: L("Fit")) { lab.waveViewport.fit() }246                    }247                }248            }249            .padding(.horizontal, ORIX.Space.l)250            .frame(height: 46)251            .background(ORIX.Palette.canvas)252            .overlay(alignment: .top) { ORIX.Palette.hairline.frame(height: 1) }253        }254    }255}256257/// Coordinates and RGBA values of the pixel under the pointer, in both pictures.258private struct PixelInspector: View {259    let lab: QualityLabModel260    let compact: Bool261262    var body: some View {263        HStack(spacing: ORIX.Space.m) {264            Image(systemName: "eyedropper").font(.caption).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)265            if let pixel = lab.pixel {266                Text("x \(pixel.x)  y \(pixel.y)").font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textPrimary).frame(minWidth: 92, alignment: .leading)267                sample(L("Original"), pixel.original)268                sample(lab.viewMode == .difference ? L("Result") : (lab.resultFile?.detection.format?.shortLabel ?? L("Result")), pixel.result)269                if lab.inspectorIsReduced, !compact {270                    Image(systemName: "info.circle").font(.caption).foregroundStyle(ORIX.Palette.info)271                        .help(L("Values are read from bitmaps reduced to %lld pixels on their longest side.", PictureSource.detailLimit))272                        .accessibilityLabel(L("Values are read from bitmaps reduced to %lld pixels on their longest side.", PictureSource.detailLimit))273                }274            } else {275                Text(L("Move the pointer over the picture to read a pixel")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)276            }277        }278        .accessibilityElement(children: .ignore)279        .accessibilityLabel(L("Pixel inspector"))280        .accessibilityValue(lab.pixel.map { pixel in281            "x \(pixel.x), y \(pixel.y). " + L("Original") + " " + (pixel.original?.text ?? "—") + ". " + L("Result") + " " + (pixel.result?.text ?? "—")282        } ?? L("No pixel under the pointer"))283    }284285    private func sample(_ title: String, _ value: PixelProbe.Sample?) -> some View {286        HStack(spacing: 5) {287            RoundedRectangle(cornerRadius: 3).fill(value.map { Color(.sRGB, red: Double($0.red) / 255, green: Double($0.green) / 255, blue: Double($0.blue) / 255, opacity: Double($0.alpha) / 255) } ?? .clear)288                .frame(width: 14, height: 14)289                .overlay(RoundedRectangle(cornerRadius: 3).strokeBorder(ORIX.Palette.hairlineStrong, lineWidth: 1))290            if !compact { Text(title).font(.caption2.weight(.semibold)).foregroundStyle(ORIX.Palette.textTertiary) }291            Text(value.map { "R \($0.red) G \($0.green) B \($0.blue) A \($0.alpha)" } ?? "—").font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)292        }293        .fixedSize()294    }295}296297// MARK: - Side panel298299private struct LabPanel: View {300    @Environment(AppModel.self) private var model301    let lab: QualityLabModel302    @State private var tab = 0303    @State private var presetName = ""304    @State private var showSavePreset = false305306    var body: some View {307        VStack(spacing: 0) {308            ScrollView {309                VStack(alignment: .leading, spacing: ORIX.Space.l) {310                    sourceRow311                    VStack(alignment: .leading, spacing: ORIX.Space.s) {312                        SectionLabel(L("Convert to"))313                        TargetButton(entries: lab.entries, current: lab.currentEntry) { lab.select(destination: $0.destination, operation: $0.operation) }314                        if let choice = lab.choice {315                            FlowLayout(spacing: 6, lineSpacing: 6) {316                                FidelityBadge(fidelity: choice.plan.fidelity)317                                if choice.plan.status == .experimental { ExperimentalBadge() }318                                if choice.plan.isChained {319                                    Pill(text: L("2 steps via %@", choice.plan.intermediates.map(\.displayName).joined(separator: ", ")), symbol: "arrow.triangle.branch", color: ORIX.Palette.info)320                                }321                            }322                        }323                    }324                    if let notice = lab.notice { Banner(kind: .success, text: notice).onTapGesture { lab.dismissNotice() } }325                    SizeCard(lab: lab)326                    HStack {327                        SegmentedPicker(selection: $tab, options: [(0, L("Settings"), lab.optionValues.count), (1, L("Facts"), 0)])328                        Spacer(minLength: 0)329                    }330                    if tab == 0 { settings } else { LabFacts(lab: lab) }331                }332                .padding(ORIX.Space.l)333            }334            ORIX.Palette.hairline.frame(height: 1)335            HStack(spacing: ORIX.Space.s) {336                Button { lab.useSettings() } label: { Text(L("Use These Settings")).frame(maxWidth: .infinity) }337                    .buttonStyle(PrimaryButtonStyle()).disabled(lab.choice == nil)338                    .help(L("Sends this file with the destination and settings to the Convert workspace."))339                Button { presetName = lab.defaultPresetName(); showSavePreset = true } label: { Image(systemName: "bookmark").frame(height: 18) }340                    .buttonStyle(SecondaryButtonStyle()).disabled(lab.choice == nil)341                    .help(L("Save as Preset…")).accessibilityLabel(L("Save as Preset…"))342                    .popover(isPresented: $showSavePreset, arrowEdge: .top) { savePopover }343            }344            .padding(ORIX.Space.m)345        }346        .background(ORIX.Palette.surface)347        .onAppear { if model.launch.panel == "facts" { tab = 1 } }348        .accessibilityElement(children: .contain)349        .accessibilityLabel(L("Trial settings and facts"))350    }351352    private var sourceRow: some View {353        HStack(spacing: ORIX.Space.m) {354            FormatBadge(format: lab.sourceFormat, size: .regular)355            VStack(alignment: .leading, spacing: 2) {356                Text(lab.source?.lastPathComponent ?? "").font(.headline).lineLimit(1).truncationMode(.middle)357                Text(Fmt.bytes(lab.bytesBefore)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary)358            }359            Spacer(minLength: 0)360            IconButton(symbol: "xmark", label: L("Close this file")) { lab.clear() }361        }362    }363364    @ViewBuilder private var settings: some View {365        if lab.descriptors.isEmpty {366            Text(L("This conversion has no settings.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)367        } else {368            OptionsForm(descriptors: lab.descriptors, values: lab.optionValues) { key, value in lab.setOption(key, value) }369            if !lab.optionValues.isEmpty { Button(L("Reset to Defaults")) { lab.resetOptions() }.buttonStyle(SecondaryButtonStyle()) }370        }371        Label(L("The trial is converted again a moment after each change."), systemImage: "arrow.triangle.2.circlepath").font(.caption).foregroundStyle(ORIX.Palette.textTertiary)372    }373374    private var savePopover: some View {375        VStack(alignment: .leading, spacing: ORIX.Space.m) {376            Text(L("Save as Preset")).font(.headline)377            TextField(L("Preset name"), text: $presetName).textFieldStyle(.roundedBorder).frame(width: 240)378            if !lab.options.secretKeys.isEmpty {379                Label(L("Passwords are not saved in presets."), systemImage: "lock").font(.caption).foregroundStyle(ORIX.Palette.textSecondary)380            }381            HStack {382                Spacer()383                Button(L("Cancel")) { showSavePreset = false }.keyboardShortcut(.cancelAction)384                Button(L("Save")) {385                    let name = presetName.trimmingCharacters(in: .whitespaces)386                    showSavePreset = false387                    Task { await lab.savePreset(named: name) }388                }389                .keyboardShortcut(.defaultAction).disabled(presetName.trimmingCharacters(in: .whitespaces).isEmpty)390            }391        }392        .padding(ORIX.Space.l)393    }394}395396/// File size before → after and the measured ratio.397private struct SizeCard: View {398    let lab: QualityLabModel399    var body: some View {400        VStack(alignment: .leading, spacing: 6) {401            HStack(alignment: .firstTextBaseline, spacing: 8) {402                Text(Fmt.bytes(lab.bytesBefore)).font(.title3.weight(.semibold).monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary)403                Image(systemName: "arrow.right").font(.caption.weight(.bold)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)404                if lab.bytesAfter != nil {405                    Text(Fmt.bytes(lab.bytesAfter)).font(.title3.weight(.semibold).monospacedDigit()).foregroundStyle(ORIX.Palette.transformation)406                } else if lab.phase == .converting {407                    ORIXProgressRing(fraction: lab.progress?.fraction, size: 15, lineWidth: 2, label: L("Trial conversion"))408                } else {409                    Text("—").font(.title3.weight(.semibold)).foregroundStyle(ORIX.Palette.textTertiary)410                }411                Spacer(minLength: 0)412                if let change = Fmt.change(before: lab.bytesBefore, after: lab.bytesAfter) {413                    Text(change).font(.callout.weight(.semibold).monospacedDigit())414                        .foregroundStyle((lab.sizeRatio ?? 1) <= 1 ? ORIX.Palette.success : ORIX.Palette.caution)415                }416            }417            if let ratio = lab.sizeRatio {418                Text(L("The result is %@ of the original size", ratio.formatted(.percent.precision(.fractionLength(0...1)))) + (lab.outputs.count > 1 ? " · " + L("%lld files", lab.outputs.count) : ""))419                    .font(.caption).foregroundStyle(ORIX.Palette.textSecondary)420            } else {421                Text(L("File size, before and after")).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)422            }423            if lab.isStale { Label(L("These numbers belong to the previous settings."), systemImage: "clock.arrow.circlepath").font(.caption).foregroundStyle(ORIX.Palette.caution) }424        }425        .padding(ORIX.Space.m)426        .frame(maxWidth: .infinity, alignment: .leading)427        .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))428        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))429        .accessibilityElement(children: .ignore)430        .accessibilityLabel(L("File size, before and after"))431        .accessibilityValue("\(Fmt.bytes(lab.bytesBefore)) → \(Fmt.bytes(lab.bytesAfter))" + (Fmt.change(before: lab.bytesBefore, after: lab.bytesAfter).map { ", " + $0 } ?? ""))432    }433}434435/// One fact of both files. `nil` means the engine did not read it.436struct FactRow: Identifiable {437    let label: String438    let before: String?439    let after: String?440    var id: String { label }441    var changed: Bool { before != after }442}443444enum LabFactRows {445    static func field(_ inspection: FileInspection?, _ keys: [String]) -> String? {446        guard let inspection else { return nil }447        return inspection.fields.first { field in keys.contains { field.key.caseInsensitiveCompare($0) == .orderedSame } }?.value448    }449450    static func rows(before: InspectedFile?, after: InspectedFile?, bytesBefore: Int64?, bytesAfter: Int64?) -> [FactRow] {451        let a = before?.inspection, b = after?.inspection452        func yesNo(_ value: Bool?) -> String? { value.map { $0 ? L("Yes") : L("No") } }453        func each(_ label: String, _ read: (FileInspection) -> String?) -> FactRow { FactRow(label: label, before: a.flatMap(read), after: b.flatMap(read)) }454        var rows: [FactRow] = [455            FactRow(label: L("Format"), before: before?.detection.format?.displayName, after: after?.detection.format?.displayName),456            FactRow(label: L("File size"), before: bytesBefore.map { Fmt.bytes($0) }, after: bytesAfter.map { Fmt.bytes($0) }),457            each(L("Dimensions")) { i in i.pixelWidth.flatMap { w in i.pixelHeight.map { "\(Fmt.count(w)) × \(Fmt.count($0)) px" } } },458            each(L("Colour space")) { $0.colorSpace },459            FactRow(label: L("ICC profile"), before: field(a, ["ICC profile"]), after: field(b, ["ICC profile"])),460            each(L("Bit depth")) { $0.bitDepth.map { Fmt.count($0) } },461            each(L("Transparency")) { yesNo($0.hasAlpha) },462            each(L("Frames")) { $0.frameCount.map { Fmt.count($0) } },463            each(L("Pages")) { $0.pageCount.map { Fmt.count($0) } },464            each(L("Duration")) { $0.durationSeconds.map { Fmt.duration($0) } },465            each(L("Video codec")) { $0.videoCodec },466            each(L("Frame rate")) { $0.frameRate.map { $0.formatted(.number.precision(.fractionLength(0...3))) + " fps" } },467            each(L("Bit rate")) { $0.bitRate.map { L("%@ kbit/s", Fmt.count($0 / 1000)) } },468            each(L("Audio codec")) { $0.audioCodec },469            each(L("Sample rate")) { $0.sampleRate.map { L("%@ Hz", Fmt.count(Int($0))) } },470            each(L("Channels")) { $0.channels.map { Fmt.count($0) } },471        ]472        rows.removeAll { $0.before == nil && $0.after == nil }473        return rows474    }475}476477private struct LabFacts: View {478    let lab: QualityLabModel479480    var body: some View {481        let rows = LabFactRows.rows(before: lab.sourceFile, after: lab.resultFile, bytesBefore: lab.bytesBefore, bytesAfter: lab.bytesAfter)482        VStack(alignment: .leading, spacing: ORIX.Space.l) {483            VStack(alignment: .leading, spacing: 0) {484                HStack(spacing: ORIX.Space.s) {485                    Text("").frame(maxWidth: .infinity, alignment: .leading)486                    Text(L("Original")).frame(width: 88, alignment: .trailing)487                    Text(L("Result")).frame(width: 88, alignment: .trailing)488                }489                .font(.caption2.weight(.semibold)).foregroundStyle(ORIX.Palette.textTertiary).padding(.bottom, 4)490                ForEach(rows) { row in491                    HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.s) {492                        Text(row.label).foregroundStyle(ORIX.Palette.textSecondary).frame(maxWidth: .infinity, alignment: .leading)493                        Text(row.before ?? "—").foregroundStyle(row.before == nil ? ORIX.Palette.textTertiary : ORIX.Palette.textPrimary).frame(width: 88, alignment: .trailing)494                        Text(row.after ?? "—").fontWeight(row.changed && row.after != nil ? .semibold : .regular)495                            .foregroundStyle(row.after == nil ? ORIX.Palette.textTertiary : ORIX.Palette.textPrimary).frame(width: 88, alignment: .trailing)496                    }497                    .font(.caption.monospacedDigit()).multilineTextAlignment(.trailing).lineLimit(3)498                    .padding(.vertical, 4)499                    .overlay(alignment: .top) { ORIX.Palette.hairline.frame(height: 1) }500                    .accessibilityElement(children: .ignore)501                    .accessibilityLabel(row.label)502                    .accessibilityValue(L("Original") + ": " + (row.before ?? L("Not available")) + ". " + L("Result") + ": " + (row.after ?? L("Not available")))503                }504            }505            measured506            if let job = lab.job, !job.facts.isEmpty {507                VStack(alignment: .leading, spacing: ORIX.Space.s) {508                    SectionLabel(L("Reported by the engine"))509                    ForEach(job.facts.sorted { $0.key < $1.key }, id: \.key) { KeyValueRow(key: KeyLabels.fact($0.key), value: LEValue($0.value)) }510                }511            }512            if !lab.warnings.isEmpty || !(lab.job?.warnings.isEmpty ?? true) {513                VStack(alignment: .leading, spacing: ORIX.Space.s) {514                    SectionLabel(L("Warnings"))515                    let all = lab.warnings + (lab.job?.warnings ?? []).filter { !lab.warnings.contains($0) }516                    ForEach(all, id: \.self) { warning in517                        Banner(kind: warning.severity == .dataLoss ? .danger : (warning.severity == .caution ? .caution : .info), text: LE(warning.message))518                    }519                }520            }521            if let job = lab.job, !job.checks.isEmpty { ChecksList(checks: job.checks) }522        }523    }524525    @ViewBuilder private var measured: some View {526        if lab.visual == .picture {527            VStack(alignment: .leading, spacing: ORIX.Space.s) {528                SectionLabel(L("Measured on the decoded pictures"))529                if let difference = lab.comparison {530                    KeyValueRow(key: L("PSNR"), value: difference.identical ? L("Identical (no difference)") : difference.psnr.map { $0.formatted(.number.precision(.fractionLength(2))) + " dB" })531                    KeyValueRow(key: L("Largest sample difference"), value: difference.maxDifference.formatted(.percent.precision(.fractionLength(0...2))))532                    KeyValueRow(key: L("Differing pixels"), value: difference.differingFraction.formatted(.percent.precision(.fractionLength(0...2))))533                    Text(L("Compared at %@ pixels, after converting the result to the colour space of the original.", "\(Fmt.count(difference.width)) × \(Fmt.count(difference.height))"))534                        .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)535                } else if let note = lab.comparisonNote {536                    Text(note).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)537                } else {538                    Text(L("Measuring…")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)539                }540            }541        }542    }543}544
Files main
Menu

Theme