Repository Public License
1// ORIX Convert — App/Sources/Features/Queue/QueueView.swift2// Description: The Queue pane: toolbar (pause / resume the queue, clear), pending decisions, batch summary, the job3// list (selection, reorder, keyboard) and the inspector of the selected job.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6import SwiftUI78struct QueueView: View {9 @Environment(AppModel.self) private var model1011 var body: some View {12 @Bindable var queue = model.queue13 GeometryReader { geo in14 let inline = geo.size.width >= ORIX.Metric.sidePanelBreakpoint15 let selected = queue.selectedJobs.count == 1 ? queue.selectedJobs.first : nil16 let showPanel = selected != nil17 HStack(spacing: 0) {18 VStack(spacing: 0) {19 QueueToolbar()20 if !queue.awaitingDecision.isEmpty { DecisionBanner().padding(.horizontal, ORIX.Space.xl).padding(.top, ORIX.Space.m) }21 if let summary = queue.lastSummary, !queue.isRunning { SummaryCard(summary: summary).padding(.horizontal, ORIX.Space.xl).padding(.top, ORIX.Space.m) }22 if queue.isEmpty {23 EmptyState(symbol: "tray", title: L("The queue is empty"), message: L("Conversions you start appear here with their measured progress, warnings and results."),24 actionTitle: L("Add Files…")) { model.addFiles() }25 } else {26 jobList27 }28 }29 if showPanel && inline && model.showSidePanel, let selected {30 ORIX.Palette.hairline.frame(width: 1)31 JobInspector(item: selected).frame(width: ORIX.Metric.sidePanelWidth)32 }33 }34 .overlay(alignment: .trailing) {35 if showPanel && !inline && model.overlayPanelRequested, let selected {36 JobInspector(item: selected)37 .frame(width: min(ORIX.Metric.sidePanelWidth, geo.size.width - 40))38 .overlay(alignment: .leading) { ORIX.Palette.hairlineStrong.frame(width: 1) }39 .shadow(color: .black.opacity(0.18), radius: 16, x: -4)40 }41 }42 }43 .onGeometryChange(for: Bool.self) { $0.size.width >= ORIX.Metric.sidePanelBreakpoint } action: { model.sidePanelInline = $0 }44 .sheet(item: Binding(get: { queue.logJobID.flatMap { queue.items[$0] } }, set: { queue.logJobID = $0?.id })) { item in45 JobLogSheet(item: item)46 }47 }4849 private var jobList: some View {50 @Bindable var queue = model.queue51 return List(selection: $queue.selection) {52 ForEach(queue.jobs) { item in53 JobRow(item: item)54 .listRowInsets(EdgeInsets(top: 0, leading: ORIX.Space.m, bottom: 0, trailing: ORIX.Space.m))55 .listRowSeparatorTint(ORIX.Palette.hairline)56 }57 .onMove { queue.move(from: $0, to: $1) }58 }59 .listStyle(.plain)60 .scrollContentBackground(.hidden)61 .padding(.horizontal, ORIX.Space.s)62 .onDeleteCommand { queue.remove(Array(queue.selection)) }63 .onKeyPress(.space) {64 let urls = queue.selectedJobs.flatMap { $0.job.writtenOutputs.isEmpty ? $0.job.request.sources : $0.job.writtenOutputs }65 guard !urls.isEmpty else { return .ignored }66 QuickLook.toggle(urls)67 return .handled68 }69 .contextMenu(forSelectionType: UUID.self) { ids in70 JobMenu(ids: Array(ids))71 } primaryAction: { ids in72 if let id = ids.first, let job = queue.items[id]?.job {73 if let output = job.writtenOutputs.first { FileActions.open(output) } else { queue.logJobID = id }74 }75 }76 .accessibilityLabel(L("Conversion queue"))77 }78}7980private struct QueueToolbar: View {81 @Environment(AppModel.self) private var model82 var body: some View {83 let queue = model.queue84 HStack(spacing: ORIX.Space.s) {85 Button { queue.togglePause() } label: {86 Label(queue.isPaused ? L("Resume Queue") : L("Pause Queue"), systemImage: queue.isPaused ? "play.fill" : "pause.fill")87 }88 .buttonStyle(SecondaryButtonStyle(prominent: queue.isPaused))89 .disabled(queue.isEmpty)90 .help(L("Pausing stops new conversions from starting. Conversions already running finish: an engine cannot be suspended."))91 if queue.hasUnfinishedWork {92 Button { queue.cancelAll() } label: { Label(L("Cancel All"), systemImage: "xmark") }.buttonStyle(SecondaryButtonStyle())93 }94 Spacer(minLength: ORIX.Space.s)95 if let status = queue.status {96 if let reason = status.limits.reason {97 Label(LE(reason), systemImage: "thermometer.medium").font(.caption).foregroundStyle(ORIX.Palette.caution).lineLimit(1)98 }99 Text(L("%lld running · %lld waiting", queue.activeCount, queue.waitingCount)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary)100 .help(L("Up to %lld conversions at once, %lld heavy", status.limits.total, status.limits.heavy))101 }102 Button(L("Clear Completed")) { queue.clearSettled() }.buttonStyle(SecondaryButtonStyle()).disabled(queue.settledCount == 0)103 IconButton(symbol: "sidebar.trailing", label: model.isSidePanelVisible ? L("Hide Side Panel") : L("Show Side Panel"),104 tint: model.isSidePanelVisible ? ORIX.Palette.accent : ORIX.Palette.textSecondary) { model.setSidePanel(visible: !model.isSidePanelVisible) }105 }106 .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.m)107 }108}109110/// Jobs waiting for a decision about an existing destination.111private struct DecisionBanner: View {112 @Environment(AppModel.self) private var model113 var body: some View {114 let queue = model.queue115 let pending = queue.awaitingDecision116 let touchesSource = pending.contains { $0.job.conflict?.isSource == true }117 HStack(spacing: ORIX.Space.m) {118 Image(systemName: "questionmark.diamond.fill").font(.title3).foregroundStyle(ORIX.Palette.caution).accessibilityHidden(true)119 VStack(alignment: .leading, spacing: 2) {120 Text(pending.count == 1 ? L("1 conversion needs a decision") : L("%lld conversions need a decision", pending.count)).font(.callout.weight(.semibold))121 Text(touchesSource ? L("A file with the same name already exists — in some cases it is the original file itself.") : L("A file with the same name already exists at the destination."))122 .font(.caption).foregroundStyle(ORIX.Palette.textSecondary)123 }124 Spacer(minLength: ORIX.Space.s)125 Button(L("Keep Both")) { queue.resolveAll(policy: .rename) }.buttonStyle(SecondaryButtonStyle(prominent: true))126 Button(L("Skip")) { queue.resolveAll(policy: .skip) }.buttonStyle(SecondaryButtonStyle())127 Button(L("Replace…")) { ConflictActions.confirmReplace(pending.map(\.job), queue: queue) }.buttonStyle(SecondaryButtonStyle())128 }129 .padding(ORIX.Space.m)130 .background(ORIX.Palette.caution.opacity(0.09), in: RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous))131 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous).strokeBorder(ORIX.Palette.caution.opacity(0.35), lineWidth: 1))132 .accessibilityElement(children: .contain)133 }134}135136enum ConflictActions {137 /// Replacing needs an explicit confirmation; replacing an original file needs a second, separate one.138 static func confirmReplace(_ jobs: [ConversionJob], queue: QueueModel) {139 let sources = jobs.filter { $0.conflict?.isSource == true }140 let alert = NSAlert()141 alert.alertStyle = .warning142 alert.messageText = jobs.count == 1 ? L("Replace the existing file?") : L("Replace %lld existing files?", jobs.count)143 alert.informativeText = jobs.prefix(4).compactMap { $0.conflict?.existing.lastPathComponent }.joined(separator: "\n") + (jobs.count > 4 ? "\n…" : "")144 + "\n\n" + L("This cannot be undone.")145 alert.addButton(withTitle: L("Replace"))146 alert.addButton(withTitle: L("Cancel"))147 alert.buttons.first?.hasDestructiveAction = true148 if !sources.isEmpty {149 alert.showsSuppressionButton = true150 alert.suppressionButton?.title = sources.count == 1 ? L("Also replace the original file (1 conversion would overwrite its own source)")151 : L("Also replace the original files (%lld conversions would overwrite their own source)", sources.count)152 alert.suppressionButton?.state = .off153 }154 guard alert.runModal() == .alertFirstButtonReturn else { return }155 let allowSource = alert.suppressionButton?.state == .on156 for job in jobs {157 if job.conflict?.isSource == true {158 // Without the explicit tick, an original is never overwritten: the result is kept next to it.159 queue.resolve(job.id, policy: allowSource ? .replace : .rename, allowReplacingSource: allowSource)160 } else {161 queue.resolve(job.id, policy: .replace)162 }163 }164 }165}166167/// Totals of the last run. Every number is counted or measured.168private struct SummaryCard: View {169 @Environment(AppModel.self) private var model170 let summary: RunSummary171 var body: some View {172 let failed = summary.failed > 0173 HStack(spacing: ORIX.Space.l) {174 Image(systemName: failed ? "exclamationmark.triangle.fill" : "checkmark.circle.fill").font(.title2)175 .foregroundStyle(failed ? ORIX.Palette.caution : ORIX.Palette.success).accessibilityHidden(true)176 stat(L("Done"), Fmt.count(summary.finished))177 if summary.failed > 0 { stat(L("Failed"), Fmt.count(summary.failed), color: ORIX.Palette.danger) }178 if summary.skipped > 0 { stat(L("Skipped"), Fmt.count(summary.skipped)) }179 if summary.cancelled > 0 { stat(L("Cancelled"), Fmt.count(summary.cancelled)) }180 if summary.finished > 0 {181 stat(L("Size"), "\(Fmt.bytes(summary.bytesBefore)) → \(Fmt.bytes(summary.bytesAfter))", detail: Fmt.change(before: summary.bytesBefore, after: summary.bytesAfter))182 }183 stat(L("Time"), Fmt.duration(summary.elapsed))184 Spacer(minLength: 0)185 if !summary.outputs.isEmpty {186 Button(L("Reveal Results")) { FileActions.reveal(Array(summary.outputs.prefix(100))) }.buttonStyle(SecondaryButtonStyle(prominent: true))187 }188 IconButton(symbol: "xmark", label: L("Dismiss summary")) { model.queue.lastSummary = nil }189 }190 .padding(ORIX.Space.m)191 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous))192 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))193 .accessibilityElement(children: .contain)194 .accessibilityLabel(L("Batch summary"))195 }196197 private func stat(_ label: String, _ value: String, detail: String? = nil, color: Color = ORIX.Palette.textPrimary) -> some View {198 VStack(alignment: .leading, spacing: 1) {199 Text(label).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary)200 HStack(alignment: .firstTextBaseline, spacing: 5) {201 Text(value).font(.callout.weight(.semibold).monospacedDigit()).foregroundStyle(color)202 if let detail { Text(detail).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary) }203 }204 }205 .lineLimit(1)206 .accessibilityElement(children: .ignore)207 .accessibilityLabel(label)208 .accessibilityValue(value + (detail.map { ", " + $0 } ?? ""))209 }210}211212/// Context menu for one or several jobs: only actions that can really be performed are enabled.213struct JobMenu: View {214 @Environment(AppModel.self) private var model215 let ids: [UUID]216217 var body: some View {218 let queue = model.queue219 let jobs = ids.compactMap { queue.items[$0]?.job }220 let outputs = jobs.flatMap(\.writtenOutputs)221 let sources = jobs.flatMap(\.request.sources)222 if !outputs.isEmpty {223 Button(L("Open Result")) { outputs.prefix(10).forEach { FileActions.open($0) } }224 Button(L("Reveal Result in Finder")) { FileActions.reveal(outputs) }225 }226 Button(L("Quick Look")) { QuickLook.show(outputs.isEmpty ? sources : outputs) }227 Button(L("Reveal Source in Finder")) { FileActions.reveal(sources) }228 Divider()229 if jobs.contains(where: { $0.state == .queued }) { Button(L("Pause")) { queue.pauseJobs(ids) } }230 if jobs.contains(where: { $0.state == .paused }) { Button(L("Resume")) { queue.resumeJobs(ids) } }231 if jobs.contains(where: { $0.state == .queued || $0.state == .paused }) {232 Menu(L("Priority")) {233 ForEach(JobPriority.allCases.reversed(), id: \.self) { priority in234 Button(priority.title) { queue.setPriority(priority, for: ids) }235 }236 }237 Button(L("Move to Top")) { queue.moveToTop(ids) }238 }239 if jobs.contains(where: { !$0.state.isTerminal }) { Button(L("Cancel")) { queue.cancel(ids) } }240 if jobs.contains(where: { $0.state == .failed || $0.state == .cancelled }) { Button(L("Retry")) { queue.retry(ids) } }241 Divider()242 if jobs.count == 1, let job = jobs.first {243 Button(L("Show Log")) { queue.logJobID = job.id }244 Button(L("Copy Details")) { FileActions.copy(job.detailsText) }245 if let source = job.primarySource {246 Button(L("Inspect in Metadata Studio")) { model.section = .metadata; Task { await model.metadata.load(job.writtenOutputs.first ?? source) } }247 }248 }249 if jobs.contains(where: { $0.state.isTerminal }) { Button(L("Remove from List")) { queue.remove(ids) } }250 }251}252