Repository Public License
1// ORIX Convert — App/Sources/Features/Metadata/MetadataStudioView.swift2// Description: Metadata Studio: drop or pick a file, see everything the engine really read (typed facts + grouped3// fields, searchable, copyable as text or JSON), and run the metadata operations the engines offer.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6import SwiftUI7import UniformTypeIdentifiers89struct MetadataStudioView: View {10 @Environment(AppModel.self) private var model11 @FocusState private var searchFocused: Bool12 @State private var dropTargeted = false1314 var body: some View {15 @Bindable var metadata = model.metadata16 VStack(spacing: 0) {17 HeaderBar(title: L("Metadata Studio"), subtitle: metadata.file?.url.lastPathComponent) {18 if metadata.file != nil {19 SearchField(text: $metadata.search, prompt: L("Search fields"), focus: $searchFocused).frame(maxWidth: 220)20 Menu {21 Button(L("Copy as Text")) { if let file = metadata.file { FileActions.copy(FieldGrouping.text(for: file)) } }22 Button(L("Copy as JSON")) { if let file = metadata.file { FileActions.copy(FieldGrouping.json(for: file)) } }23 } label: { Label(L("Copy All"), systemImage: "doc.on.doc") }24 .menuStyle(.button).buttonStyle(SecondaryButtonStyle()).fixedSize()25 }26 Button { metadata.choose() } label: { Label(L("Inspect File…"), systemImage: "doc.viewfinder") }.buttonStyle(SecondaryButtonStyle())27 }28 if metadata.isLoading {29 VStack(spacing: ORIX.Space.m) {30 ORIXProgressRing(fraction: nil, size: 28, lineWidth: 3, label: L("Reading the file"))31 Text(L("Reading the file…")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)32 }33 .frame(maxWidth: .infinity, maxHeight: .infinity)34 } else if let file = metadata.file {35 content(file)36 } else {37 EmptyState(symbol: "list.bullet.rectangle", title: L("Inspect any file"),38 message: L("Drop a file here to see what it really contains: detected format, dimensions, codecs, pages, tags and every field its engine can read. Values that cannot be read are shown as “—”, never guessed."),39 actionTitle: L("Inspect File…")) { metadata.choose() }40 }41 }42 // A drop on this section inspects the file instead of staging it for conversion.43 .onDrop(of: [.fileURL], isTargeted: $dropTargeted) { providers in44 DropLoader.load(providers) { urls in if let first = urls.first { Task { await metadata.load(first) } } }45 return true46 }47 .overlay { if dropTargeted { RoundedRectangle(cornerRadius: ORIX.Radius.l).strokeBorder(ORIX.Palette.transformationDiagonal, lineWidth: 3).padding(6).allowsHitTesting(false) } }48 .onChange(of: model.searchRequest) { searchFocused = true }49 .sheet(item: $metadata.activeAction) { action in MetadataActionSheet(action: action) }50 }5152 private func content(_ file: InspectedFile) -> some View {53 let metadata = model.metadata54 return ScrollView {55 VStack(alignment: .leading, spacing: ORIX.Space.l) {56 Card {57 HStack(spacing: ORIX.Space.l) {58 FormatBadge(format: file.detection.format, size: .large)59 VStack(alignment: .leading, spacing: 3) {60 Text(file.url.lastPathComponent).font(.title3.weight(.semibold)).lineLimit(2).truncationMode(.middle).textSelection(.enabled)61 Text(file.url.deletingLastPathComponent().path).font(.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).truncationMode(.head)62 HStack(spacing: 6) {63 Pill(text: file.detection.format?.displayName ?? L("Unknown format"), symbol: file.detection.format?.category.symbol, color: file.detection.format?.category.color ?? ORIX.Palette.textSecondary)64 Pill(text: file.detection.confidence.title, symbol: file.detection.confidence.symbol, color: ORIX.Palette.textSecondary)65 .help(file.detection.evidence)66 if file.detection.mismatch { Pill(text: L("Wrong extension"), symbol: "exclamationmark.triangle.fill", color: ORIX.Palette.caution) }67 Text(Fmt.bytes(file.facts.size)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary)68 }69 }70 Spacer(minLength: ORIX.Space.s)71 VStack(alignment: .trailing, spacing: ORIX.Space.s) {72 ForEach(metadata.actions) { action in73 Button(action.title) { metadata.activeAction = action }.buttonStyle(SecondaryButtonStyle(prominent: true))74 }75 HStack(spacing: 2) {76 IconButton(symbol: "eye", label: L("Quick Look")) { QuickLook.show([file.url]) }77 IconButton(symbol: "magnifyingglass", label: L("Reveal in Finder")) { FileActions.reveal([file.url]) }78 IconButton(symbol: "arrow.triangle.2.circlepath", label: L("Convert This File")) { model.ingest(urls: [file.url]) }79 }80 }81 }82 }83 if file.detection.mismatch {84 Banner(kind: .caution, text: L("The name says .%@, but the content is %@.", file.detection.fileExtension, file.detection.format?.displayName ?? "?"), detail: file.detection.evidence)85 }86 if let error = file.engineError { Banner(kind: .caution, text: L("The content could not be fully read."), detail: LE(error)) }87 if file.engineID == nil && file.engineError == nil {88 Banner(kind: .info, text: L("No engine of this build reads the content of this format. Only file-system facts are shown."))89 }90 if metadata.actions.isEmpty && file.engineID != nil {91 Text(L("No metadata editing or removal is available for this format in this build.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)92 }93 if let notice = metadata.notice { Banner(kind: .info, text: notice) }94 if metadata.preview.phase != .idle {95 Card {96 VStack(alignment: .leading, spacing: ORIX.Space.m) {97 SectionLabel(L("Preview"))98 FilePreviewView(preview: metadata.preview, height: 340)99 }100 .frame(maxWidth: .infinity, alignment: .leading)101 }102 }103 InspectionContent(file: file, search: metadata.search, columns: true)104 }105 .padding(ORIX.Space.xl)106 }107 }108}109110extension DetectionResult.Confidence {111 var title: String {112 switch self {113 case .certain: L("Identified by content")114 case .likely: L("Likely, from content")115 case .extensionOnly: L("From the name only")116 }117 }118119 var symbol: String {120 switch self {121 case .certain: "checkmark.seal"122 case .likely: "seal"123 case .extensionOnly: "textformat.abc"124 }125 }126}127128/// Typed facts and grouped fields of an inspected file. Used by Metadata Studio and the queue inspector.129struct InspectionContent: View {130 let file: InspectedFile131 let search: String132 /// Lay the groups out in two columns when there is room.133 var columns = false134135 var body: some View {136 let facts = FieldGrouping.typedFacts(file.inspection).filter { row in137 let needle = search.trimmingCharacters(in: .whitespaces).lowercased()138 return needle.isEmpty || row.key.lowercased().contains(needle) || (row.value ?? "").lowercased().contains(needle)139 }140 let groups = FieldGrouping.groups(file.inspection.fields.filter { $0.group != "File" }, matching: search)141 let fileRows = FieldGrouping.fileRows(file).filter { row in142 let needle = search.trimmingCharacters(in: .whitespaces).lowercased()143 return needle.isEmpty || row.key.lowercased().contains(needle) || (row.value ?? "").lowercased().contains(needle)144 }145 VStack(alignment: .leading, spacing: ORIX.Space.l) {146 if !facts.isEmpty {147 FieldCard(title: L("Summary"), rows: facts.map { FieldCard.Row(key: $0.key, value: $0.value) })148 }149 if columns {150 AdaptiveColumns(minColumnWidth: 380, spacing: ORIX.Space.l) {151 if !fileRows.isEmpty { FieldCard(title: L("File"), rows: fileRows.map { FieldCard.Row(key: $0.key, value: $0.value) }) }152 ForEach(groups) { group in FieldCard(title: LE(group.name), rows: group.fields.map { FieldCard.Row(key: LE($0.key), value: LEValue($0.value)) }) }153 }154 } else {155 if !fileRows.isEmpty { FieldCard(title: L("File"), rows: fileRows.map { FieldCard.Row(key: $0.key, value: $0.value) }) }156 ForEach(groups) { group in FieldCard(title: LE(group.name), rows: group.fields.map { FieldCard.Row(key: LE($0.key), value: LEValue($0.value)) }) }157 }158 if !file.inspection.notes.isEmpty {159 VStack(alignment: .leading, spacing: 6) {160 SectionLabel(L("Notes"))161 ForEach(file.inspection.notes, id: \.self) { Text("• " + LE($0)).font(.callout).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true) }162 }163 }164 if facts.isEmpty && groups.isEmpty && fileRows.isEmpty {165 Text(L("No field matches “%@”.", search)).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)166 }167 }168 }169}170171/// One group of fields. Each row can be copied; the whole group too.172struct FieldCard: View {173 struct Row: Identifiable { let key: String; let value: String?; var id: String { key } }174 let title: String175 let rows: [Row]176177 var body: some View {178 VStack(alignment: .leading, spacing: 0) {179 HStack {180 SectionLabel(title)181 Spacer()182 IconButton(symbol: "doc.on.doc", label: L("Copy the group “%@”", title), tint: ORIX.Palette.textTertiary) {183 FileActions.copy(rows.map { "\($0.key): \($0.value ?? "—")" }.joined(separator: "\n"))184 }185 }186 .padding(.bottom, 2)187 ForEach(Array(rows.enumerated()), id: \.offset) { index, row in188 if index > 0 { ORIX.Palette.hairline.frame(height: 1) }189 KeyValueRow(key: row.key, value: row.value)190 .padding(.vertical, 6)191 .contextMenu {192 Button(L("Copy Value")) { FileActions.copy(row.value ?? "") }.disabled(row.value == nil)193 Button(L("Copy Row")) { FileActions.copy("\(row.key): \(row.value ?? "—")") }194 }195 }196 }197 .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.m)198 .frame(maxWidth: .infinity, alignment: .leading)199 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous))200 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))201 }202}203204/// Places its children in as many equal columns as fit (masonry by shortest column).205struct AdaptiveColumns: Layout {206 var minColumnWidth: CGFloat207 var spacing: CGFloat208209 private func frames(width: CGFloat, subviews: Subviews) -> (CGSize, [CGRect]) {210 let count = max(1, min(3, Int((width + spacing) / (minColumnWidth + spacing))))211 let columnWidth = (width - spacing * CGFloat(count - 1)) / CGFloat(count)212 var heights = [CGFloat](repeating: 0, count: count)213 var frames: [CGRect] = []214 for subview in subviews {215 let column = heights.enumerated().min { $0.element < $1.element }?.offset ?? 0216 let size = subview.sizeThatFits(ProposedViewSize(width: columnWidth, height: nil))217 frames.append(CGRect(x: CGFloat(column) * (columnWidth + spacing), y: heights[column], width: columnWidth, height: size.height))218 heights[column] += size.height + spacing219 }220 return (CGSize(width: width, height: max(0, (heights.max() ?? 0) - spacing)), frames)221 }222223 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {224 frames(width: proposal.width ?? 800, subviews: subviews).0225 }226227 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {228 let result = frames(width: bounds.width, subviews: subviews).1229 for (index, frame) in result.enumerated() {230 subviews[index].place(at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY), proposal: ProposedViewSize(width: frame.width, height: frame.height))231 }232 }233}234235/// Sheet for a discovered metadata operation: its real options, then a real conversion job.236struct MetadataActionSheet: View {237 @Environment(AppModel.self) private var model238 @Environment(\.dismiss) private var dismiss239 let action: MetadataAction240 @State private var values: [String: OptionValue] = [:]241242 var body: some View {243 VStack(alignment: .leading, spacing: 0) {244 VStack(alignment: .leading, spacing: 4) {245 Text(action.kind == .remove ? L("Remove Metadata") : L("Edit Metadata")).font(.title3.weight(.semibold))246 Text(L("%@ — a new file is written next to the original, which is left untouched.", model.metadata.file?.url.lastPathComponent ?? ""))247 .font(.callout).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)248 }249 .padding(ORIX.Space.l)250 ORIX.Palette.hairline.frame(height: 1)251 ScrollView {252 VStack(alignment: .leading, spacing: ORIX.Space.l) {253 OptionsForm(descriptors: action.descriptors, values: action.presetValues.merging(values) { _, new in new }) { key, value in values[key] = value }254 if !action.path.limitations.isEmpty {255 VStack(alignment: .leading, spacing: 6) {256 SectionLabel(L("Before you convert"))257 ForEach(action.path.limitations, id: \.self) { Banner(kind: .info, text: LE($0)) }258 }259 }260 }261 .padding(ORIX.Space.l)262 }263 ORIX.Palette.hairline.frame(height: 1)264 HStack {265 Spacer()266 Button(L("Cancel")) { dismiss() }.keyboardShortcut(.cancelAction).buttonStyle(SecondaryButtonStyle())267 Button(action.kind == .remove ? L("Remove Metadata") : L("Apply")) {268 model.metadata.run(action, values: values)269 dismiss()270 }271 .keyboardShortcut(.defaultAction).buttonStyle(PrimaryButtonStyle())272 }273 .padding(ORIX.Space.l)274 }275 .frame(width: 480, height: 560)276 .background(ORIX.Palette.surface)277 }278}279