SPB Git

Repository Public License

JobInspector.swift 14.0 KB 262 lines swift

1// ORIX Convert — App/Sources/Features/Queue/JobInspector.swift2// Description: Side inspector of the selected job (plan, warnings, validation, facts, results, error) with the file3//              metadata of its source or result, and the detailed log sheet.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6import SwiftUI78struct JobInspector: View {9    @Environment(AppModel.self) private var model10    let item: JobItem11    @State private var tab = 012    @State private var inspected: InspectedFile?13    @State private var inspectedURL: URL?1415    var body: some View {16        let job = item.job17        VStack(spacing: 0) {18            HStack(spacing: ORIX.Space.s) {19                ConversionPairBadge(source: job.sourceFormat, destination: job.request.destinationFormat)20                VStack(alignment: .leading, spacing: 1) {21                    Text(job.displayName).font(.headline).lineLimit(1).truncationMode(.middle)22                    Label(job.state.title, systemImage: job.state.symbol).font(.caption).foregroundStyle(job.state.color)23                }24                Spacer(minLength: 4)25                IconButton(symbol: "sidebar.trailing", label: L("Hide Side Panel")) { model.setSidePanel(visible: false) }26            }27            .padding(.horizontal, ORIX.Space.l).frame(height: 54)28            HStack {29                SegmentedPicker(selection: $tab, options: [(0, L("Conversion"), 0), (1, L("Metadata"), 0)])30                Spacer()31            }32            .padding(.horizontal, ORIX.Space.l).padding(.bottom, ORIX.Space.s)33            ORIX.Palette.hairline.frame(height: 1)34            ScrollView {35                if tab == 0 { details(job).padding(ORIX.Space.l) } else { metadata(job).padding(ORIX.Space.l) }36            }37        }38        .background(ORIX.Palette.surface)39        .task(id: "\(item.id)-\(tab)-\(job.state.isTerminal)") { await loadMetadata(job) }40        .accessibilityElement(children: .contain)41        .accessibilityLabel(L("Conversion inspector"))42    }4344    private func details(_ job: ConversionJob) -> some View {45        VStack(alignment: .leading, spacing: ORIX.Space.xl) {46            if let error = job.error {47                VStack(alignment: .leading, spacing: ORIX.Space.s) {48                    Banner(kind: .danger, text: LE(error))49                    Button(L("Copy Details")) { FileActions.copy(job.detailsText) }.buttonStyle(SecondaryButtonStyle())50                }51            }52            if let conflict = job.conflict {53                Banner(kind: .caution, text: L("“%@” already exists", conflict.existing.lastPathComponent),54                       detail: conflict.isSource ? L("It is the original file itself.") : (conflict.conversionDone ? L("The conversion is done; only the save is waiting.") : L("The conversion starts once you decide.")))55            }56            VStack(alignment: .leading, spacing: ORIX.Space.s) {57                SectionLabel(L("Conversion"))58                KeyValueRow(key: L("From"), value: job.sourceFormat?.displayName)59                KeyValueRow(key: L("To"), value: job.targetTitle)60                KeyValueRow(key: L("Engine"), value: job.plan.map { $0.engines.compactMap { id in model.registry.engine(id: id).map { LE($0.displayName) } }.joined(separator: " → ") })61                KeyValueRow(key: L("Fidelity"), value: job.plan?.fidelity.title)62                KeyValueRow(key: L("Size"), value: job.bytesBefore.map { before in job.bytesAfter.map { "\(Fmt.bytes(before)) → \(Fmt.bytes($0))" } ?? Fmt.bytes(before) })63                KeyValueRow(key: L("Duration"), value: job.duration.map { Fmt.duration($0) })64                KeyValueRow(key: L("Attempt"), value: job.attempt > 1 ? Fmt.count(job.attempt) : nil)65            }66            let options = job.request.options.redactingSecrets().values.sorted { $0.key < $1.key }67            if !options.isEmpty {68                VStack(alignment: .leading, spacing: ORIX.Space.s) {69                    SectionLabel(L("Options used"))70                    ForEach(options, id: \.key) { KeyValueRow(key: $0.key, value: $0.value.plainText, monospaced: true) }71                    if !job.request.options.secretKeys.isEmpty {72                        Label(L("A password was supplied; it is not shown or saved."), systemImage: "lock").font(.caption).foregroundStyle(ORIX.Palette.textTertiary)73                    }74                }75            }76            if !job.warnings.isEmpty {77                VStack(alignment: .leading, spacing: ORIX.Space.s) {78                    SectionLabel(L("Warnings"))79                    ForEach(job.warnings, id: \.self) { warning in80                        Banner(kind: warning.severity == .dataLoss ? .danger : (warning.severity == .caution ? .caution : .info), text: LE(warning.message))81                    }82                }83            }84            if !job.checks.isEmpty { ChecksList(checks: job.checks) }85            if !job.facts.isEmpty {86                VStack(alignment: .leading, spacing: ORIX.Space.s) {87                    SectionLabel(L("Measured on the result"))88                    ForEach(job.facts.sorted { $0.key < $1.key }, id: \.key) { KeyValueRow(key: KeyLabels.fact($0.key), value: LEValue($0.value)) }89                }90            }91            if !job.outputs.isEmpty {92                VStack(alignment: .leading, spacing: ORIX.Space.s) {93                    SectionLabel(L("Results"))94                    ForEach(job.outputs, id: \.self) { output in95                        HStack(spacing: ORIX.Space.s) {96                            DragOutHandle(urls: [output.url], label: output.url.lastPathComponent)97                            VStack(alignment: .leading, spacing: 1) {98                                Text(output.url.lastPathComponent).font(.callout).lineLimit(1).truncationMode(.middle)99                                Text(FileActions.exists(output.url) ? output.outcome.title : L("No longer at this location")).font(.caption)100                                    .foregroundStyle(FileActions.exists(output.url) ? ORIX.Palette.textSecondary : ORIX.Palette.caution)101                            }102                            Spacer(minLength: 0)103                            IconButton(symbol: "eye", label: L("Quick Look")) { QuickLook.show([output.url]) }104                            IconButton(symbol: "magnifyingglass", label: L("Reveal in Finder")) { FileActions.reveal([output.url]) }105                        }106                    }107                }108            }109            Button { model.queue.logJobID = job.id } label: { Label(L("Show Log"), systemImage: "doc.text.magnifyingglass") }.buttonStyle(SecondaryButtonStyle())110        }111    }112113    @ViewBuilder private func metadata(_ job: ConversionJob) -> some View {114        if let inspected {115            VStack(alignment: .leading, spacing: ORIX.Space.l) {116                Text(inspected.url.lastPathComponent).font(.callout.weight(.medium)).lineLimit(1).truncationMode(.middle)117                InspectionContent(file: inspected, search: "")118                Button(L("Open in Metadata Studio")) { model.section = .metadata; Task { await model.metadata.load(inspected.url) } }.buttonStyle(SecondaryButtonStyle())119            }120        } else {121            HStack(spacing: 8) { ORIXProgressRing(fraction: nil, size: 14, lineWidth: 2, label: L("Reading metadata")); Text(L("Reading the file…")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary) }122        }123    }124125    /// Inspects the result when there is one, otherwise the source.126    private func loadMetadata(_ job: ConversionJob) async {127        guard tab == 1 else { return }128        guard let url = job.writtenOutputs.first(where: FileActions.exists) ?? job.primarySource else { return }129        if url == inspectedURL, inspected != nil { return }130        inspected = nil131        inspectedURL = url132        let inspector = model.manager.inspector133        inspected = await Task.detached { await inspector.inspect(url) }.value134    }135}136137extension CommittedOutput.Outcome {138    var title: String {139        switch self {140        case .written: L("Written")141        case .renamed: L("Written under a new name (kept both)")142        case .replaced: L("Replaced the existing file")143        case .skipped: L("Existing file kept")144        }145    }146}147148struct ChecksList: View {149    let checks: [ValidationCheck]150    var body: some View {151        VStack(alignment: .leading, spacing: ORIX.Space.s) {152            SectionLabel(L("Verification"))153            ForEach(Array(checks.enumerated()), id: \.offset) { _, check in154                HStack(alignment: .firstTextBaseline, spacing: 7) {155                    Image(systemName: check.passed ? "checkmark.circle.fill" : "xmark.octagon.fill").font(.caption)156                        .foregroundStyle(check.passed ? ORIX.Palette.success : ORIX.Palette.danger).accessibilityHidden(true)157                    VStack(alignment: .leading, spacing: 1) {158                        Text(KeyLabels.check(check.name)).font(.callout).foregroundStyle(ORIX.Palette.textPrimary)159                        if !check.detail.isEmpty { Text(LE(check.detail)).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true) }160                    }161                }162                .accessibilityElement(children: .ignore)163                .accessibilityLabel((check.passed ? L("Passed") : L("Failed")) + ": " + KeyLabels.check(check.name))164                .accessibilityValue(check.detail)165            }166        }167    }168}169170/// Detailed log of one job: timestamped lines, warnings, validation checks, measured facts.171struct JobLogSheet: View {172    @Environment(\.dismiss) private var dismiss173    let item: JobItem174    @State private var onlyProblems = false175176    var body: some View {177        let job = item.job178        let lines = onlyProblems ? job.log.filter { $0.level == .warning || $0.level == .error } : job.log179        VStack(spacing: 0) {180            HStack(spacing: ORIX.Space.m) {181                ConversionPairBadge(source: job.sourceFormat, destination: job.request.destinationFormat)182                VStack(alignment: .leading, spacing: 1) {183                    Text(L("Log — %@", job.displayName)).font(.headline).lineLimit(1).truncationMode(.middle)184                    Label(job.state.title, systemImage: job.state.symbol).font(.caption).foregroundStyle(job.state.color)185                }186                Spacer()187                Toggle(L("Warnings and errors only"), isOn: $onlyProblems).toggleStyle(.checkbox)188            }189            .padding(ORIX.Space.l)190            ORIX.Palette.hairline.frame(height: 1)191            ScrollView {192                LazyVStack(alignment: .leading, spacing: 0) {193                    ForEach(Array(lines.enumerated()), id: \.offset) { _, line in194                        HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.s) {195                            Text(Fmt.time(line.date)).font(.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 92, alignment: .leading)196                            Image(systemName: line.level.symbol).font(.caption2).foregroundStyle(line.level.color).frame(width: 14).accessibilityLabel(line.level.title)197                            Text(LE(line.message)).font(.callout.monospaced()).foregroundStyle(line.level == .error ? ORIX.Palette.danger : ORIX.Palette.textPrimary)198                                .textSelection(.enabled).fixedSize(horizontal: false, vertical: true)199                            Spacer(minLength: 0)200                        }201                        .padding(.vertical, 3)202                    }203                    if lines.isEmpty { Text(L("No line to show.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary).padding(.vertical, ORIX.Space.m) }204                    if !job.warnings.isEmpty {205                        SectionLabel(L("Warnings")).padding(.top, ORIX.Space.l).padding(.bottom, ORIX.Space.s)206                        ForEach(job.warnings, id: \.self) { warning in207                            Banner(kind: warning.severity == .dataLoss ? .danger : (warning.severity == .caution ? .caution : .info), text: LE(warning.message), detail: warning.code)208                                .padding(.bottom, 6)209                        }210                    }211                    if !job.checks.isEmpty { ChecksList(checks: job.checks).padding(.top, ORIX.Space.l) }212                    if !job.facts.isEmpty {213                        SectionLabel(L("Measured on the result")).padding(.top, ORIX.Space.l).padding(.bottom, ORIX.Space.s)214                        ForEach(job.facts.sorted { $0.key < $1.key }, id: \.key) { KeyValueRow(key: KeyLabels.fact($0.key), value: LEValue($0.value)).padding(.vertical, 2) }215                    }216                }217                .padding(ORIX.Space.l)218            }219            .background(ORIX.Palette.surfaceSunken)220            ORIX.Palette.hairline.frame(height: 1)221            HStack {222                Button(L("Copy Details")) { FileActions.copy(job.detailsText) }.buttonStyle(SecondaryButtonStyle())223                Text(L("%lld lines", job.log.count)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textTertiary)224                Spacer()225                Button(L("Done")) { dismiss() }.keyboardShortcut(.defaultAction).buttonStyle(SecondaryButtonStyle(prominent: true))226            }227            .padding(ORIX.Space.l)228        }229        .frame(minWidth: 620, idealWidth: 760, minHeight: 440, idealHeight: 560)230        .background(ORIX.Palette.surface)231    }232}233234extension LogLevel {235    var symbol: String {236        switch self {237        case .debug: "ant"238        case .info: "circle.fill"239        case .warning: "exclamationmark.triangle.fill"240        case .error: "xmark.octagon.fill"241        }242    }243244    var color: Color {245        switch self {246        case .debug: ORIX.Palette.textTertiary247        case .info: ORIX.Palette.textTertiary248        case .warning: ORIX.Palette.caution249        case .error: ORIX.Palette.danger250        }251    }252253    var title: String {254        switch self {255        case .debug: L("Debug")256        case .info: L("Information")257        case .warning: L("Warning")258        case .error: L("Error")259        }260    }261}262
Files main
Menu

Theme