Repository Public License
1// ORIX Convert — App/Sources/Features/Preview/FilePreviewView.swift2// Description: The "Preview" area of Metadata Studio and of the Convert inspector: one view per kind of content3// loaded by FilePreviewModel (picture, PDF pages, 3D scene, table, archive listing, font specimen,4// subtitle cues, map, waveform). Everything shown was read from the file; bounds are stated.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import EngineArchive8import EngineData9import EngineFont10import EngineGeo11import EngineMedia12import EngineModel3D13import EngineSubtitle14import SceneKit15import SwiftUI1617struct FilePreviewView: View {18 let preview: FilePreviewModel19 /// Height of the visual part (the inspector uses a smaller one).20 var height: CGFloat = 3202122 var body: some View {23 VStack(alignment: .leading, spacing: ORIX.Space.s) {24 switch preview.phase {25 case .idle:26 EmptyView()27 case .loading:28 HStack(spacing: ORIX.Space.s) {29 ORIXProgressRing(fraction: nil, size: 18, lineWidth: 2, label: L("Loading the preview"))30 Text(L("Loading the preview…")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)31 }32 .frame(maxWidth: .infinity, minHeight: 80)33 case .failed(let message):34 Label(L("No preview: %@", message), systemImage: "eye.slash").font(.callout).foregroundStyle(ORIX.Palette.textSecondary)35 .fixedSize(horizontal: false, vertical: true)36 case .ready:37 if let content = preview.content { body(for: content) }38 }39 }40 .accessibilityElement(children: .contain)41 .accessibilityLabel(L("Preview"))42 }4344 @ViewBuilder private func body(for content: FilePreviewContent) -> some View {45 switch content {46 case .picture(let image, let caption):47 PictureFrame(image: image, height: height)48 Text("\(image.width) × \(image.height) px · \(caption)").font(.caption).foregroundStyle(ORIX.Palette.textTertiary)49 case .pages(let pages, let total):50 ScrollView(.horizontal) {51 HStack(alignment: .top, spacing: ORIX.Space.m) {52 ForEach(Array(pages.enumerated()), id: \.offset) { index, page in53 VStack(spacing: 4) {54 Image(decorative: page, scale: 2).resizable().aspectRatio(contentMode: .fit).frame(height: height - 24)55 .overlay(Rectangle().strokeBorder(ORIX.Palette.hairlineStrong, lineWidth: 1))56 Text(L("Page %lld", index + 1)).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)57 }58 .accessibilityElement(children: .ignore).accessibilityLabel(L("Page %lld", index + 1))59 }60 }61 .padding(.vertical, 2)62 }63 Text(total > pages.count ? L("First %lld of %lld pages", pages.count, total) : (total == 1 ? L("1 page") : L("%lld pages", total)))64 .font(.caption).foregroundStyle(ORIX.Palette.textTertiary)65 case .model(let model):66 ModelPreview(model: model, height: height)67 case .table(let table):68 TablePreview(result: table, preview: preview, height: height)69 case .archive(let listing):70 ArchivePreview(listing: listing, preview: preview, height: height)71 case .font(let specimen):72 FontPreviewPane(specimen: specimen, height: height)73 case .subtitles(let listing):74 SubtitlePreview(listing: listing, height: height)75 case .map(let result):76 MapPreview(result: result, height: height)77 case .waveform(let waveform):78 WaveformStrip(waveform: waveform).frame(height: min(height, 140))79 .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: ORIX.Radius.s))80 Text(L("%@ · %lld channel(s) · %@ Hz · minimum and maximum of %lld samples per column", Fmt.duration(waveform.durationSeconds), waveform.channels, Fmt.count(Int(waveform.sampleRate)), waveform.samplesPerBucket))81 .font(.caption).foregroundStyle(ORIX.Palette.textTertiary)82 case .none(let message):83 Label(message, systemImage: "eye.slash").font(.callout).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)84 }85 }86}8788// MARK: - Picture8990private struct PictureFrame: View {91 let image: CGImage92 let height: CGFloat93 var body: some View {94 Image(decorative: image, scale: 1).resizable().interpolation(.high).aspectRatio(contentMode: .fit)95 .frame(maxWidth: .infinity, maxHeight: height)96 .background(Checkerboard().opacity(image.alphaInfo == .none || image.alphaInfo == .noneSkipLast || image.alphaInfo == .noneSkipFirst ? 0 : 1))97 .background(ORIX.Palette.surfaceSunken)98 .clipShape(RoundedRectangle(cornerRadius: ORIX.Radius.s))99 }100}101102/// Shows that a picture has transparent areas.103private struct Checkerboard: View {104 var body: some View {105 Canvas { context, size in106 let cell: CGFloat = 8107 for row in 0..<Int(ceil(size.height / cell)) {108 for column in 0..<Int(ceil(size.width / cell)) where (row + column) % 2 == 0 {109 context.fill(Path(CGRect(x: CGFloat(column) * cell, y: CGFloat(row) * cell, width: cell, height: cell)), with: .color(ORIX.Palette.hairline))110 }111 }112 }113 }114}115116// MARK: - 3D117118private struct ModelPreview: View {119 let model: Model3DPreview120 let height: CGFloat121 @State private var wireframe = false122123 var body: some View {124 let s = model.summary125 SceneContainer(scene: model.scene, wireframe: wireframe)126 .frame(maxWidth: .infinity).frame(height: height)127 .clipShape(RoundedRectangle(cornerRadius: ORIX.Radius.s))128 .accessibilityLabel(L("3D model, %lld triangles. Drag to orbit, scroll to zoom.", s.triangleCount))129 HStack(spacing: ORIX.Space.m) {130 Toggle(L("Wireframe"), isOn: $wireframe).toggleStyle(.checkbox)131 Spacer()132 Text(statistics(s)).font(.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled)133 }134 Text(s.isolated ? L("Parsed in a separate process (%@). Drag to orbit, scroll or pinch to zoom.", s.importer) : L("Parsed by %@. Drag to orbit, scroll or pinch to zoom.", s.importer))135 .font(.caption).foregroundStyle(ORIX.Palette.textTertiary)136 }137138 private func statistics(_ s: Model3DSummary) -> String {139 var parts = [L("%@ triangles", Fmt.count(s.triangleCount)), L("%@ vertices", Fmt.count(s.vertexCount)), L("%lld mesh(es)", s.meshCount), L("%lld material(s)", s.materialCount)]140 if let box = s.boundingBox {141 let size = box.size142 parts.append([size.x, size.y, size.z].map { $0.formatted(.number.precision(.significantDigits(3))) }.joined(separator: " × ") + (s.unit.map { " × " + L("%@ m per unit", $0.metersPerUnit.formatted(.number.precision(.significantDigits(1...4)))) } ?? ""))143 }144 return parts.joined(separator: " · ")145 }146}147148private struct SceneContainer: NSViewRepresentable {149 let scene: Scene3D150 let wireframe: Bool151152 private static func configure(_ view: SCNView, scene: Scene3D) {153 view.allowsCameraControl = true // orbit, pan, zoom154 view.autoenablesDefaultLighting = true155 view.antialiasingMode = .multisampling4X156 view.backgroundColor = NSColor(white: 0.5, alpha: 0.08)157 view.scene = Model3DPreviewLoader.makeSCNScene(from: scene)158 }159160 func makeNSView(context: Context) -> NSView {161 // Self-screenshots draw the window with `cacheDisplay`, which does not capture a Metal layer: in that mode162 // only, the same scene is rendered once by SceneKit into a bitmap (`SCNView.snapshot()`).163 if AppRuntime.model.launch.shot != nil {164 let offscreen = SCNView(frame: CGRect(x: 0, y: 0, width: 1100, height: 680))165 Self.configure(offscreen, scene: scene)166 let image = NSImageView(image: offscreen.snapshot())167 image.imageScaling = .scaleProportionallyUpOrDown168 // The bitmap must not impose its own size on the layout.169 for axis in [NSLayoutConstraint.Orientation.horizontal, .vertical] {170 image.setContentCompressionResistancePriority(.init(1), for: axis)171 image.setContentHuggingPriority(.init(1), for: axis)172 }173 return image174 }175 let view = SCNView()176 Self.configure(view, scene: scene)177 return view178 }179180 func updateNSView(_ view: NSView, context: Context) {181 (view as? SCNView)?.debugOptions = wireframe ? [.renderAsWireframe] : []182 }183}184185// MARK: - Table186187private struct TablePreview: View {188 let result: DataPreviewResult189 let preview: FilePreviewModel190 let height: CGFloat191 private static let columnLimit = 40192 private static let columnWidth: CGFloat = 132193194 var body: some View {195 let columns = Array(result.columns.prefix(Self.columnLimit))196 if result.tableNames.count > 1 {197 Picker(L("Sheet or table"), selection: Binding(get: { result.table }, set: { name in198 if let url = preview.url { preview.load(url, format: preview.format, table: name) }199 })) {200 ForEach(result.tableNames, id: \.self) { Text($0).tag($0) }201 }202 .frame(maxWidth: 320)203 }204 ScrollView([.horizontal, .vertical]) {205 LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {206 Section {207 ForEach(Array(result.rows.enumerated()), id: \.offset) { index, row in208 HStack(spacing: 0) {209 ForEach(Array(columns.enumerated()), id: \.offset) { column, _ in210 let value = column < row.count ? row[column] : nil211 Text(value ?? "NULL").font(.caption.monospacedDigit()).lineLimit(1).truncationMode(.tail)212 .foregroundStyle(value == nil ? ORIX.Palette.textTertiary : ORIX.Palette.textPrimary)213 .frame(width: Self.columnWidth - 12, alignment: Self.isNumeric(columns[column].kind) ? .trailing : .leading)214 .padding(.horizontal, 6).padding(.vertical, 3)215 }216 }217 .background(index % 2 == 1 ? ORIX.Palette.surfaceSunken : Color.clear)218 }219 } header: {220 HStack(spacing: 0) {221 ForEach(Array(columns.enumerated()), id: \.offset) { _, column in222 VStack(alignment: .leading, spacing: 1) {223 Text(column.name).font(.caption.weight(.semibold)).lineLimit(1)224 Text(LE(column.kind.rawValue) + " · " + column.type).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)225 }226 .frame(width: Self.columnWidth - 12, alignment: .leading).padding(.horizontal, 6).padding(.vertical, 4)227 }228 }229 .background(ORIX.Palette.surfaceRaised)230 .overlay(alignment: .bottom) { ORIX.Palette.hairlineStrong.frame(height: 1) }231 }232 }233 }234 .frame(maxWidth: .infinity, maxHeight: height, alignment: .topLeading)235 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.s))236 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))237 Text(caption(columns.count)).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)238 ForEach(result.notes.prefix(3), id: \.self) { note in239 Label(LE(note.message), systemImage: "info.circle").font(.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)240 }241 }242243 private static func isNumeric(_ kind: ColumnKind) -> Bool { kind == .integer || kind == .decimal || kind == .double }244245 private func caption(_ shownColumns: Int) -> String {246 var parts = [result.totalRows.map { L("First %lld of %@ rows", result.rows.count, Fmt.count(Int($0))) } ?? L("First %lld rows (the total is not known without reading the whole file)", result.rows.count)]247 parts.append(shownColumns < result.columns.count ? L("%lld of %lld columns shown", shownColumns, result.columns.count) : L("%lld columns, types as detected", result.columns.count))248 if !result.hiddenTableNames.isEmpty { parts.append(L("%lld hidden sheet(s)", result.hiddenTableNames.count)) }249 return parts.joined(separator: " · ")250 }251}252253// MARK: - Archive254255private struct ArchivePreview: View {256 let listing: ArchiveListing257 let preview: FilePreviewModel258 let height: CGFloat259 @State private var search = ""260261 private var visible: [ArchiveEntryInfo] {262 let needle = search.trimmingCharacters(in: .whitespaces).lowercased()263 return needle.isEmpty ? listing.entries : listing.entries.filter { $0.path.lowercased().contains(needle) }264 }265266 var body: some View {267 let s = listing.summary268 HStack(spacing: ORIX.Space.m) {269 Text(summaryLine(s)).font(.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled)270 Spacer()271 TextField(L("Filter entries"), text: $search).textFieldStyle(.roundedBorder).frame(maxWidth: 200).accessibilityLabel(L("Filter entries"))272 }273 if s.hasEncryptedEntries { Label(L("Some entries are protected by a password. Their names are listed; their contents are not read."), systemImage: "lock.fill").font(.caption).foregroundStyle(ORIX.Palette.caution) }274 ScrollView {275 LazyVStack(alignment: .leading, spacing: 0) {276 ForEach(visible, id: \.index) { entry in277 HStack(spacing: ORIX.Space.s) {278 Image(systemName: symbol(entry)).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 16)279 Text(entry.path).font(.caption).lineLimit(1).truncationMode(.middle)280 if entry.isEncrypted { Image(systemName: "lock.fill").font(.caption2).foregroundStyle(ORIX.Palette.caution).accessibilityLabel(L("Protected")) }281 if !entry.hasSafeName { Image(systemName: "exclamationmark.triangle.fill").font(.caption2).foregroundStyle(ORIX.Palette.caution).accessibilityLabel(L("Unsafe name: cleaned or left out when extracting")) }282 if let target = entry.linkTarget { Text("→ " + target).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1) }283 Spacer(minLength: ORIX.Space.s)284 if let compressed = entry.compressedSize, entry.kind == .file { Text(Fmt.bytes(compressed)).font(.caption2.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary) }285 Text(entry.kind == .directory ? "—" : (entry.size.map { Fmt.bytes($0) } ?? "?")).font(.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 78, alignment: .trailing)286 }287 .padding(.horizontal, ORIX.Space.s).padding(.vertical, 3)288 .accessibilityElement(children: .combine)289 }290 if listing.canLoadMore {291 Button(preview.isLoadingMore ? L("Listing…") : L("List %lld more", min(FilePreviewModel.Bounds.archivePage, s.entryCount - listing.entries.count))) { preview.loadMoreEntries() }292 .buttonStyle(.link).disabled(preview.isLoadingMore).padding(ORIX.Space.s)293 }294 }295 }296 .frame(maxWidth: .infinity, maxHeight: height, alignment: .topLeading)297 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.s))298 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))299 Text(L("%lld of %lld entries listed. Listing reads names and sizes only: nothing is extracted.", listing.entries.count, s.entryCount) + (s.isComplete ? "" : " " + L("The scan stopped at its limit: totals are partial.")))300 .font(.caption).foregroundStyle(ORIX.Palette.textTertiary)301 }302303 private func symbol(_ entry: ArchiveEntryInfo) -> String {304 switch entry.kind {305 case .directory: "folder"306 case .symlink, .hardlink: "link"307 case .file: "doc"308 case .other: "questionmark.square.dashed"309 }310 }311312 private func summaryLine(_ s: ArchiveSummary) -> String {313 var parts = [s.format + (s.filters.isEmpty ? "" : " (" + s.filters.joined(separator: ", ") + ")"), L("%lld files", s.fileCount), L("%lld folders", s.directoryCount)]314 parts.append(s.sizesKnown ? L("%@ uncompressed", Fmt.bytes(s.totalSize)) : L("uncompressed size unknown"))315 parts.append(L("%@ archive", Fmt.bytes(s.archiveSize)))316 // The engine's ratio is uncompressed size over archive size.317 if let ratio = s.compressionRatio { parts.append(ratio.formatted(.number.precision(.fractionLength(1))) + " : 1") }318 return parts.joined(separator: " · ")319 }320}321322// MARK: - Font323324private struct FontPreviewPane: View {325 let specimen: FontSpecimen326 let height: CGFloat327 @State private var page = 0328 @Environment(\.colorScheme) private var scheme329330 private var pageCount: Int { max(1, Int(ceil(Double(specimen.glyphCount) / Double(FilePreviewModel.Bounds.glyphPage)))) }331332 var body: some View {333 VStack(alignment: .leading, spacing: ORIX.Space.s) {334 ForEach(specimen.lines, id: \.pointSize) { line in335 HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.s) {336 Text("\(line.pointSize)").font(.caption2.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 22, alignment: .trailing)337 Image(decorative: line.image, scale: 2).renderingMode(.template).foregroundStyle(ORIX.Palette.textPrimary)338 .frame(maxWidth: .infinity, alignment: .leading).clipped()339 }340 }341 }342 .padding(ORIX.Space.s)343 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.s))344 .accessibilityElement(children: .ignore)345 .accessibilityLabel(L("Specimen of %@ at %lld sizes", specimen.fullName ?? L("the font"), specimen.lines.count))346 Text(L("Drawn with this font's own glyphs, without ligatures, kerning or fallback fonts: a missing character shows the font's “not defined” glyph."))347 .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)348 if let embedding = specimen.embedding {349 Label(L("Embedding permission stated by the font: %@", LE(embedding)), systemImage: specimen.isRestricted ? "exclamationmark.shield.fill" : "checkmark.shield")350 .font(.caption).foregroundStyle(specimen.isRestricted ? ORIX.Palette.caution : ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)351 } else {352 Label(L("The font states no embedding permission (no OS/2 table)."), systemImage: "questionmark.circle").font(.caption).foregroundStyle(ORIX.Palette.textSecondary)353 }354 let glyphs = specimen.font.glyphs(in: (page * FilePreviewModel.Bounds.glyphPage)..<min(specimen.glyphCount, (page + 1) * FilePreviewModel.Bounds.glyphPage))355 LazyVGrid(columns: [GridItem(.adaptive(minimum: 44, maximum: 56), spacing: 4)], spacing: 4) {356 ForEach(glyphs, id: \.index) { glyph in357 GlyphCell(glyph: glyph, unitsPerEm: specimen.unitsPerEm)358 }359 }360 HStack {361 Button { page = max(0, page - 1) } label: { Image(systemName: "chevron.left") }.disabled(page == 0).accessibilityLabel(L("Previous glyphs"))362 Text(L("Glyphs %lld–%lld of %@", page * FilePreviewModel.Bounds.glyphPage, min(specimen.glyphCount, (page + 1) * FilePreviewModel.Bounds.glyphPage) - 1, Fmt.count(specimen.glyphCount)))363 .font(.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary)364 Button { page = min(pageCount - 1, page + 1) } label: { Image(systemName: "chevron.right") }.disabled(page >= pageCount - 1).accessibilityLabel(L("Next glyphs"))365 if specimen.memberCount > 1 { Text(L("First of %lld fonts in the collection", specimen.memberCount)).font(.caption).foregroundStyle(ORIX.Palette.textTertiary) }366 }367 .buttonStyle(.borderless)368 }369}370371private struct GlyphCell: View {372 let glyph: GlyphInfo373 let unitsPerEm: Int374375 var body: some View {376 VStack(spacing: 1) {377 Canvas { context, size in378 guard let outline = glyph.outline else { return }379 // Font units, y up → the cell, with the em box fitted and the baseline at 78 % of the height.380 let scale = size.height * 0.7 / CGFloat(max(1, unitsPerEm))381 let advance = CGFloat(glyph.advance) * scale382 var transform = CGAffineTransform(translationX: max(1, (size.width - advance) / 2), y: size.height * 0.78).scaledBy(x: scale, y: -scale)383 if let placed = outline.copy(using: &transform) { context.fill(Path(placed), with: .color(ORIX.Palette.textPrimary)) }384 }385 .frame(height: 40)386 Text(label).font(.system(size: 8).monospaced()).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)387 }388 .frame(maxWidth: .infinity)389 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: 4))390 .accessibilityElement(children: .ignore)391 .accessibilityLabel(L("Glyph %lld%@", glyph.index, glyph.name.map { ", " + $0 } ?? ""))392 .help(glyph.name ?? "")393 }394395 private var label: String {396 if let first = glyph.codePoints.first { return String(format: "U+%04X", first) }397 return "#\(glyph.index)"398 }399}400401// MARK: - Subtitles402403private struct SubtitlePreview: View {404 let listing: SubtitleListing405 let height: CGFloat406407 var body: some View {408 ScrollView {409 LazyVStack(alignment: .leading, spacing: 0) {410 ForEach(Array(listing.cues.enumerated()), id: \.offset) { index, cue in411 HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.m) {412 Text("\(index + 1)").font(.caption2.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 34, alignment: .trailing)413 Text(Self.time(cue.startMs) + " → " + Self.time(cue.endMs)).font(.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary)414 Text(cue.plainText).font(.callout).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)415 Spacer(minLength: 0)416 }417 .padding(.horizontal, ORIX.Space.s).padding(.vertical, 4)418 .background(index % 2 == 1 ? ORIX.Palette.surfaceSunken : Color.clear)419 }420 }421 }422 .frame(maxWidth: .infinity, maxHeight: height, alignment: .topLeading)423 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.s))424 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))425 Text((listing.total > listing.cues.count ? L("First %lld of %lld cues", listing.cues.count, listing.total) : L("%lld cues", listing.total)) + " · " + L("text read as %@", listing.encoding))426 .font(.caption).foregroundStyle(ORIX.Palette.textTertiary)427 }428429 static func time(_ milliseconds: Int) -> String {430 let ms = max(0, milliseconds)431 return String(format: "%02d:%02d:%02d.%03d", ms / 3_600_000, (ms / 60_000) % 60, (ms / 1000) % 60, ms % 1000)432 }433}434435// MARK: - Map436437private struct MapPreview: View {438 let result: GeoPreviewResult439 let height: CGFloat440 @State private var layerIndex = 0441442 var body: some View {443 let layer = result.layers.indices.contains(layerIndex) ? result.layers[layerIndex] : result.layers.first444 if result.layers.count > 1 {445 Picker(L("Layer"), selection: $layerIndex) { ForEach(Array(result.layers.enumerated()), id: \.offset) { index, layer in Text(layer.name).tag(index) } }.frame(maxWidth: 320)446 }447 if let layer {448 GeometryPlot(layer: layer).frame(maxWidth: .infinity).frame(height: min(height, 300))449 .background(ORIX.Palette.surfaceSunken, in: RoundedRectangle(cornerRadius: ORIX.Radius.s))450 .accessibilityLabel(L("Plot of %lld features of layer %@", layer.features.count, layer.name))451 Text(L("%lld of %lld features drawn in the file's own coordinates (%@), no map background. Extent: %@", layer.features.count, layer.featureCount, layer.crs.summary, layer.boundingBox.text))452 .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)453 attributes(layer)454 } else {455 Text(L("The file holds no layer.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)456 }457 }458459 @ViewBuilder private func attributes(_ layer: GeoLayerPreview) -> some View {460 let fields = Array(layer.fields.prefix(12))461 if !fields.isEmpty {462 ScrollView([.horizontal, .vertical]) {463 Grid(alignment: .leading, horizontalSpacing: ORIX.Space.m, verticalSpacing: 3) {464 GridRow {465 Text(L("Geometry")).font(.caption.weight(.semibold))466 ForEach(fields, id: \.name) { field in Text(field.name).font(.caption.weight(.semibold)).lineLimit(1) }467 }468 ForEach(Array(layer.features.prefix(25).enumerated()), id: \.offset) { _, feature in469 GridRow {470 Text(feature.geometryType ?? "—").font(.caption).foregroundStyle(ORIX.Palette.textSecondary)471 ForEach(fields, id: \.name) { field in472 Text(Self.text(feature.attributes.first { $0.name == field.name }?.value)).font(.caption.monospacedDigit()).lineLimit(1).frame(maxWidth: 180, alignment: .leading)473 }474 }475 }476 }477 .padding(ORIX.Space.s)478 }479 .frame(maxWidth: .infinity, maxHeight: 180, alignment: .topLeading)480 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.s))481 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))482 }483 }484485 static func text(_ value: AttributeValue?) -> String {486 switch value {487 case nil, .null?: "—"488 case .string(let s)?: s489 case .integer(let i)?: String(i)490 case .real(let d)?: d.formatted(.number.precision(.significantDigits(1...8)))491 case .bool(let b)?: b ? "true" : "false"492 case .date(let s)?, .dateTime(let s)?: s493 default: "…"494 }495 }496}497498/// Core Graphics plot of the features of a layer inside the layer's bounding box (y up, aspect kept).499private struct GeometryPlot: View {500 let layer: GeoLayerPreview501502 var body: some View {503 Canvas { context, size in504 let box = layer.boundingBox505 guard !box.isEmpty else { return }506 let inset: CGFloat = 12507 let width = max(box.maxX - box.minX, 1e-9), height = max(box.maxY - box.minY, 1e-9)508 let scale = min((size.width - 2 * inset) / width, (size.height - 2 * inset) / height)509 let offsetX = (size.width - width * scale) / 2, offsetY = (size.height - height * scale) / 2510 func point(_ c: Coordinate) -> CGPoint { CGPoint(x: offsetX + (c.x - box.minX) * scale, y: size.height - offsetY - (c.y - box.minY) * scale) }511 let stroke = ORIX.Palette.accent, fill = ORIX.Palette.accent.opacity(0.18)512 func line(_ coordinates: [Coordinate], close: Bool) -> Path {513 var path = Path()514 guard let first = coordinates.first else { return path }515 path.move(to: point(first))516 for c in coordinates.dropFirst() { path.addLine(to: point(c)) }517 if close { path.closeSubpath() }518 return path519 }520 func dot(_ c: Coordinate) { let p = point(c); context.fill(Path(ellipseIn: CGRect(x: p.x - 2.5, y: p.y - 2.5, width: 5, height: 5)), with: .color(stroke)) }521 func draw(_ geometry: Geometry) {522 switch geometry {523 case .point(let c): dot(c)524 case .multiPoint(let cs): cs.forEach(dot)525 case .lineString(let cs): context.stroke(line(cs, close: false), with: .color(stroke), lineWidth: 1.2)526 case .multiLineString(let lines): for cs in lines { context.stroke(line(cs, close: false), with: .color(stroke), lineWidth: 1.2) }527 case .polygon(let rings):528 var path = Path()529 for ring in rings { path.addPath(line(ring, close: true)) }530 context.fill(path, with: .color(fill), style: FillStyle(eoFill: true))531 context.stroke(path, with: .color(stroke), lineWidth: 1)532 case .multiPolygon(let polygons): for rings in polygons { draw(.polygon(rings)) }533 case .collection(let members): members.forEach(draw)534 }535 }536 // The layer's extent, then each feature (its bounding box when the geometry is too large to hand over).537 context.stroke(Path(CGRect(x: offsetX, y: offsetY, width: width * scale, height: height * scale)), with: .color(ORIX.Palette.hairlineStrong), style: StrokeStyle(lineWidth: 1, dash: [3, 3]))538 for feature in layer.features {539 if let geometry = feature.geometry { draw(geometry) } else if !feature.boundingBox.isEmpty {540 let b = feature.boundingBox541 let a = point(Coordinate(b.minX, b.maxY)), z = point(Coordinate(b.maxX, b.minY))542 context.stroke(Path(CGRect(x: a.x, y: a.y, width: max(1, z.x - a.x), height: max(1, z.y - a.y))), with: .color(stroke.opacity(0.6)), lineWidth: 1)543 }544 }545 }546 }547}548549// MARK: - Waveform550551/// One audio file as a min / max envelope (the buckets measured by the media engine).552private struct WaveformStrip: View {553 let waveform: AudioWaveform554555 var body: some View {556 Canvas { context, size in557 let count = min(waveform.minimums.count, waveform.maximums.count)558 guard count > 0 else { return }559 let middle = size.height / 2, step = size.width / CGFloat(count)560 var path = Path()561 for index in 0..<count {562 let x = CGFloat(index) * step563 let top = middle - CGFloat(max(-1, min(1, waveform.maximums[index]))) * (middle - 2)564 let bottom = middle - CGFloat(max(-1, min(1, waveform.minimums[index]))) * (middle - 2)565 path.addRect(CGRect(x: x, y: min(top, bottom), width: max(0.6, step), height: max(0.6, abs(bottom - top))))566 }567 context.fill(path, with: .color(ORIX.Palette.accent))568 context.stroke(Path { $0.move(to: CGPoint(x: 0, y: middle)); $0.addLine(to: CGPoint(x: size.width, y: middle)) }, with: .color(ORIX.Palette.hairlineStrong), lineWidth: 0.5)569 }570 .accessibilityLabel(L("Waveform, %@", Fmt.duration(waveform.durationSeconds)))571 }572}573