Repository Public
1// ORIX Docs2// File: App/Sources/Inspector/PublishInspector.swift3// Description: The Publishing Studio tab: document metadata, typography presets (real style-sheet and page-setup transformations),4// page template actions, a print preview, export profiles and the fonts the document uses.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import DocModel11import DocContainer12import DocLayout13import DocReferences1415/// A typography preset: a theme plus body-text settings and margins, applied as one undoable step.16struct TypographyPreset: Identifiable {17 let id: String18 let title: String19 let summary: String20 let symbol: String21 let theme: Theme22 let body: ParaProps23 let margins: Insets24 var paper: PaperSize?2526 static var all: [TypographyPreset] {27 var compact = Theme.technical28 compact.bodySize = 1029 var book = Theme.academic30 book.bodySize = 1131 return [32 TypographyPreset(id: "book", title: String(localized: "Book"),33 summary: String(localized: "Charter 11 pt, justified with first-line indents and hyphenation, on a 6 × 9 in trade page."), symbol: "book.closed",34 theme: book, body: ParaProps(alignment: .justified, firstLineIndent: 14, spaceAfter: 0, lineSpacing: .multiple(1.3), hyphenate: true),35 margins: Insets(top: 54, left: 54, bottom: 60, right: 54), paper: .trade6x9),36 TypographyPreset(id: "report", title: String(localized: "Report"),37 summary: String(localized: "Helvetica Neue 11 pt, left-aligned block paragraphs, 1-inch margins."), symbol: "doc.text",38 theme: .modern, body: ParaProps(alignment: .left, firstLineIndent: 0, spaceAfter: 8, lineSpacing: .multiple(1.25), hyphenate: false),39 margins: Insets(all: 72)),40 TypographyPreset(id: "manuscript", title: String(localized: "Manuscript (double-spaced)"),41 summary: String(localized: "Times New Roman 12 pt, double-spaced, half-inch indents, 1-inch margins."), symbol: "text.alignleft",42 theme: .classic, body: ParaProps(alignment: .left, firstLineIndent: 36, spaceAfter: 0, lineSpacing: .multiple(2.0), hyphenate: false),43 margins: Insets(all: 72)),44 TypographyPreset(id: "compact", title: String(localized: "Compact"),45 summary: String(localized: "Avenir Next 10 pt, justified with tight leading and hyphenation, ¾-inch margins."), symbol: "arrow.down.right.and.arrow.up.left",46 theme: compact, body: ParaProps(alignment: .justified, firstLineIndent: 0, spaceAfter: 4, lineSpacing: .multiple(1.12), hyphenate: true),47 margins: Insets(all: 54)),48 ]49 }5051 /// Applies the preset to the style sheet and to the page setup of every section.52 func apply(to doc: inout DocumentModel) {53 doc.styles.applyTheme(theme)54 if var normal = doc.styles.style(StyleID.normal) {55 normal.para.apply(body)56 doc.styles.upsert(normal)57 }58 // Styles based on Body that say nothing about these properties must not inherit a first-line indent or justification by accident.59 for i in doc.styles.styles.indices where doc.styles.styles[i].kind == .paragraph && doc.styles.styles[i].id != StyleID.normal {60 if doc.styles.styles[i].para.firstLineIndent == nil { doc.styles.styles[i].para.firstLineIndent = 0 }61 }62 for id in [StyleID.title, StyleID.subtitle, StyleID.tocHeading] {63 if var s = doc.styles.style(id), s.para.alignment == nil { s.para.alignment = .left; doc.styles.upsert(s) }64 }65 for i in 0..<doc.sectionSetups.count {66 var setup = doc.setup(ofSection: i)67 setup.margins = margins68 if let paper { setup.paper = paper; setup.landscape = false }69 doc.setSetup(setup, ofSection: i)70 }71 }72}7374struct ExportProfile: Identifiable {75 let id: String76 let title: String77 let summary: String78 let symbol: String79 let format: DocFormat80 var options = PDFOptions()8182 static var all: [ExportProfile] {83 var screen = PDFOptions(); screen.includeOutline = true; screen.tagged = true84 var print = PDFOptions(); print.includeOutline = false; print.tagged = false; print.cropMarks = true; print.bleed = 985 return [86 ExportProfile(id: "screen-pdf", title: String(localized: "Screen PDF"), summary: String(localized: "Bookmarks from the headings and structure tags for reading on screen."),87 symbol: "display", format: .pdf, options: screen),88 ExportProfile(id: "print-pdf", title: String(localized: "Print PDF"), summary: String(localized: "Crop marks and a ⅛-inch bleed for a print shop."),89 symbol: "printer", format: .pdf, options: print),90 ExportProfile(id: "review-docx", title: String(localized: "Review Copy"), summary: String(localized: "Word document (DOCX) that keeps tracked changes and comments."),91 symbol: "text.bubble", format: .docx),92 ExportProfile(id: "web-html", title: String(localized: "Web"), summary: String(localized: "A single HTML page."), symbol: "globe", format: .html),93 ExportProfile(id: "markdown", title: String(localized: "Plain Markdown"), summary: String(localized: "Text with Markdown structure, for editors and repositories."),94 symbol: "number", format: .markdown),95 ]96 }97}9899struct FontUse: Identifiable {100 let family: String101 let characters: Int102 let installed: Bool103 var id: String { family }104105 /// Families of every run of the document (resolved through the styles), with the number of characters set in each.106 static func scan(_ doc: DocumentModel) -> [FontUse] {107 var counts: [String: Int] = [:]108 var memo: [String: String] = [:]109 doc.forEachParagraphEverywhere { p, _, _ in110 for r in p.runs where r.inline == nil && !r.text.isEmpty {111 let key = "\(p.style)|\(r.charStyle ?? "")|\(r.props.fontFamily ?? "")"112 let family: String113 if let f = memo[key] { family = f } else {114 family = doc.styles.charProps(paraStyle: p.style, charStyle: r.charStyle, direct: CharProps(fontFamily: r.props.fontFamily)).fontFamily115 memo[key] = family116 }117 counts[family, default: 0] += r.length118 }119 }120 return counts.map { FontUse(family: $0.key, characters: $0.value, installed: FontCache.shared.isInstalled($0.key)) }121 .sorted { $0.characters != $1.characters ? $0.characters > $1.characters : $0.family < $1.family }122 }123}124125struct PublishInspector: View {126 @Bindable var session: DocumentSession127 /// Page shown in the preview; nil follows the caret.128 @State private var pinnedPage: Int?129 @State private var preview: (image: CGImage, page: Int, pageCount: Int)?130 @State private var fonts: [FontUse] = []131 @State private var previewCache = LayoutCache()132133 var body: some View {134 let _ = session.selectionRevision135 let revision = session.revision136 let doc = session.doc137 let meta = doc.meta138139 InspectorGroup("Document", id: "publish.document") {140 VStack(alignment: .leading, spacing: 3) {141 Text(verbatim: meta.title.isEmpty ? String(localized: "Untitled") : meta.title)142 .font(.system(size: 13, weight: .semibold)).foregroundStyle(meta.title.isEmpty ? ORIX.Palette.textTertiary : ORIX.Palette.text).lineLimit(2)143 Text(verbatim: meta.author.isEmpty ? String(localized: "No author") : meta.author).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)144 Text("\(session.layout.pageCount) pages · \(session.statistics.words) words · \(CharacterGroups.languageName(meta.language))")145 .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)146 if !meta.keywords.isEmpty {147 Text(verbatim: meta.keywords.joined(separator: " · ")).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(2)148 }149 }150 .accessibilityElement(children: .combine)151 if meta.title.isEmpty || meta.author.isEmpty {152 InspectorNote("The title and the author are written to exported files. Complete them in the properties.", symbol: "exclamationmark.triangle", color: ORIX.Palette.warning)153 }154 InspectorButton("Document Properties…", symbol: "info.circle", identifier: "publish-properties") { session.activeSheet = .properties }155 }156157 InspectorGroup("Typography Presets", id: "publish.presets") {158 ForEach(TypographyPreset.all) { preset in159 ActionCard(symbol: preset.symbol, title: preset.title, summary: preset.summary, trailing: "wand.and.stars", identifier: "publish-preset-\(preset.id)") {160 session.perform(String(localized: "Apply \(preset.title) Preset")) { preset.apply(to: &$0.doc) }161 session.refocusCanvas()162 }163 }164 InspectorNote("A preset changes the theme, the Body style and the margins of every section. One Undo restores the previous look.")165 }166167 InspectorGroup("Page Templates", id: "publish.templates") {168 Grid(horizontalSpacing: ORIX.Space.s, verticalSpacing: ORIX.Space.s) {169 GridRow { insert("Page Break", .insertPageBreak, "doc.badge.plus"); insert("Contents", .insertContents, "list.bullet.rectangle") }170 GridRow { insert("List of Figures", .insertListOfFigures, "photo.stack"); insert("List of Tables", .insertListOfTables, "tablecells") }171 GridRow { insert("Bibliography", .insertBibliography, "books.vertical"); insert("Section Break", .insertSectionNextPage, "rectangle.stack") }172 }173 InspectorNote("Inserted at the caret. Contents, lists and the bibliography update themselves.")174 }175176 InspectorGroup("Print Preview", id: "publish.preview") {177 previewView178 }179 .task(id: PreviewRequest(revision: revision, page: pinnedPage ?? session.currentPage, markup: session.showMarkup)) {180 // Let typing settle before laying the document out for print.181 try? await Task.sleep(for: .milliseconds(preview == nil ? 10 : 280))182 guard !Task.isCancelled else { return }183 renderPreview()184 fonts = FontUse.scan(session.doc)185 }186187 InspectorGroup("Export", id: "publish.export") {188 ForEach(ExportProfile.all) { profile in189 ActionCard(symbol: profile.symbol, title: profile.title, summary: profile.summary, trailing: "square.and.arrow.up", identifier: "publish-export-\(profile.id)") {190 session.exportInteractively(format: profile.format, pdfOptions: profile.options)191 }192 }193 InspectorButton("More Formats…", symbol: "ellipsis", identifier: "publish-export-more") { session.activeSheet = .export }194 }195196 InspectorGroup("Fonts in This Document", id: "publish.fonts") {197 let missing = fonts.filter { !$0.installed }198 ForEach(fonts) { font in199 HStack(spacing: 6) {200 Text(verbatim: font.family)201 .font(font.installed && FontCatalog.shared.drawsLatin(font.family) ? .documentFamily(font.family, size: 12.5) : .system(size: 12))202 .foregroundStyle(ORIX.Palette.text).lineLimit(1)203 Spacer(minLength: 4)204 if font.installed {205 Text("\(font.characters) characters").font(.system(size: 10).monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary)206 } else {207 Label("Not installed", systemImage: "exclamationmark.triangle.fill").font(.system(size: 10, weight: .medium)).foregroundStyle(ORIX.Palette.warning)208 }209 }210 .frame(minHeight: 20)211 .accessibilityElement(children: .combine)212 .accessibilityIdentifier("publish-font-\(font.family)")213 }214 if fonts.isEmpty { InspectorNote("The document has no text yet.") }215 if !missing.isEmpty {216 InspectorNote("\(missing.count) font families are not installed on this Mac. Their text is drawn, and exported to PDF, with Times New Roman.",217 symbol: "exclamationmark.triangle.fill", color: ORIX.Palette.warning)218 }219 }220 }221222 private struct PreviewRequest: Hashable { let revision: Int; let page: Int; let markup: Bool }223224 private func insert(_ title: LocalizedStringKey, _ c: EditorCommand, _ symbol: String) -> some View {225 InspectorButton(title, symbol: symbol, isEnabled: session.isEnabled(c), identifier: "publish-\(c.rawValue)") { session.run(c); session.refocusCanvas() }226 .help(c.title)227 }228229 /// Lays the document out as it will be published (tracked changes accepted, no editing marks) and renders one page.230 private func renderPreview() {231 var clean = session.doc232 if clean.hasTrackedChanges { clean.resolveChanges(accept: true) }233 let layout = Paginator.layout(clean, citations: CitationEngine(document: clean), options: PDFPublisher.layoutOptions, cache: previewCache)234 guard layout.pageCount > 0 else { preview = nil; return }235 let page = max(0, min(layout.pageCount - 1, pinnedPage ?? session.currentPage))236 let width = layout.pages[page].size.width237 let scale = (NSScreen.main?.backingScaleFactor ?? 2) * 252 / max(1, width)238 if let image = PDFPublisher.bitmap(page: page, doc: clean, layout: layout, scale: scale, images: session.images) {239 preview = (image, page, layout.pageCount)240 }241 }242243 @ViewBuilder private var previewView: some View {244 if let p = preview {245 let aspect = CGFloat(p.image.width) / CGFloat(max(1, p.image.height))246 Button { session.revealPage(p.page) } label: {247 Image(decorative: p.image, scale: 1).resizable().interpolation(.high).aspectRatio(aspect, contentMode: .fit)248 .frame(maxWidth: .infinity)249 .background(Color.white)250 .overlay(Rectangle().strokeBorder(ORIX.Palette.hairline, lineWidth: 0.5))251 .shadow(color: .black.opacity(0.14), radius: 5, y: 1.5)252 }253 .buttonStyle(.plain)254 .help("Show this page in the document")255 .accessibilityLabel(Text("Print preview of page \(p.page + 1)"))256 .accessibilityIdentifier("publish-preview")257 HStack(spacing: ORIX.Space.xs) {258 BarButton(symbol: "chevron.left", help: "Previous page", isEnabled: p.page > 0) { pinnedPage = max(0, p.page - 1) }259 .accessibilityIdentifier("publish-preview-previous")260 Spacer(minLength: 0)261 Text("Page \(p.page + 1) of \(p.pageCount)").font(.system(size: 11).monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary)262 .accessibilityIdentifier("publish-preview-page")263 if pinnedPage != nil {264 Button { pinnedPage = nil } label: { Image(systemName: "scope").font(.system(size: 10.5, weight: .medium)).foregroundStyle(ORIX.Palette.accent) }265 .buttonStyle(.plain).help("Follow the caret again").accessibilityLabel(Text("Follow the caret"))266 }267 Spacer(minLength: 0)268 BarButton(symbol: "chevron.right", help: "Next page", isEnabled: p.page < p.pageCount - 1) { pinnedPage = min(p.pageCount - 1, p.page + 1) }269 .accessibilityIdentifier("publish-preview-next")270 }271 InspectorNote("As published: tracked changes accepted, no editing marks.")272 } else {273 RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.text.opacity(0.05)).frame(height: 200)274 .overlay(ProgressView().controlSize(.small))275 .accessibilityLabel(Text("Preparing the preview"))276 }277 }278}279280/// A two-line action row: symbol, title, one-line description and an action glyph.281private struct ActionCard: View {282 let symbol: String283 let title: String284 let summary: String285 let trailing: String286 let identifier: String287 let action: () -> Void288 @State private var hover = false289290 var body: some View {291 Button(action: action) {292 HStack(alignment: .top, spacing: ORIX.Space.s) {293 Image(systemName: symbol).font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.accent).frame(width: 18, height: 16)294 VStack(alignment: .leading, spacing: 2) {295 Text(verbatim: title).font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text).lineLimit(1)296 Text(verbatim: summary).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)297 .multilineTextAlignment(.leading)298 }299 Spacer(minLength: 0)300 Image(systemName: trailing).font(.system(size: 10.5, weight: .medium)).foregroundStyle(hover ? ORIX.Palette.accent : ORIX.Palette.textTertiary).frame(height: 16)301 }302 .padding(.horizontal, 9).padding(.vertical, 7)303 .frame(maxWidth: .infinity, alignment: .leading)304 .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(hover ? ORIX.Palette.surfaceRaised : ORIX.Palette.surface))305 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(hover ? ORIX.Palette.accent.opacity(0.6) : ORIX.Palette.hairline))306 .contentShape(Rectangle())307 }308 .buttonStyle(.plain)309 .onHover { hover = $0 }310 .accessibilityLabel(Text(verbatim: "\(title). \(summary)"))311 .accessibilityIdentifier(identifier)312 }313}314