SPB Git

Repository Public

ObjectInspector.swift 21.9 KB 394 lines swift

1// ORIX Docs2// File: App/Sources/Inspector/ObjectInspector.swift3// Description: The Object tab: size, rotation, crop, alternative text and placement of the selected image; kind, stroke, fill, text and4//              placement of a shape; source, preview and display mode of an equation.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import UniformTypeIdentifiers11import DocModel12import DocLayout13import DocMath1415struct ObjectInspector: View {16    @Bindable var session: DocumentSession17    @State private var lockAspect = true1819    private struct Target { let position: Position; let story: StoryID; let inline: Inline }2021    /// The object selected as a whole (the canvas' notion; computed from the model when the canvas cannot place it).22    private var target: Target? {23        let story = session.selection.story24        if let o = session.canvas?.selectedObject() { return Target(position: o.position, story: story, inline: o.inline) }25        let sel = session.selection26        let s = sel.start, e = sel.end27        guard !sel.isCaret, s.path == e.path, e.offset == s.offset + 1, let inline = session.editor.inline(at: s, in: story) else { return nil }28        switch inline { case .image, .shape, .equation: return Target(position: s, story: story, inline: inline); default: return nil }29    }3031    private func update(_ name: String, key: String? = nil, _ t: Target, _ change: (inout Inline) -> Void) {32        session.perform(name, coalesce: key.map { "object-\($0)" }) { $0.updateInline(at: t.position, in: t.story, change) }33        session.refocusCanvas()34    }35    private func image(_ name: String, key: String? = nil, _ t: Target, _ change: (inout ImageObject) -> Void) {36        update(name, key: key, t) { inline in if case .image(var i) = inline { change(&i); inline = .image(i) } }37    }38    private func shape(_ name: String, key: String? = nil, _ t: Target, _ change: (inout ShapeObject) -> Void) {39        update(name, key: key, t) { inline in if case .shape(var s) = inline { change(&s); inline = .shape(s) } }40    }41    private func placement(_ name: String, key: String? = nil, _ t: Target, _ change: (inout Placement) -> Void) {42        update(name, key: key, t) { inline in43            switch inline {44            case .image(var i): change(&i.placement); inline = .image(i)45            case .shape(var s): change(&s.placement); inline = .shape(s)46            default: break47            }48        }49    }5051    var body: some View {52        let _ = session.selectionRevision53        let _ = session.revision54        if let t = target {55            switch t.inline {56            case .image(let img): imageEditor(img, t)57            case .shape(let s): shapeEditor(s, t)58            case .equation(let eq): equationEditor(eq, t)59            default: EmptyView()60            }61        } else {62            EmptyState(symbol: "photo.on.rectangle.angled", title: "No object selected", message: "Click an image, a shape or an equation in the document to adjust it here.")63                .padding(.vertical, ORIX.Space.xl)64        }65    }6667    private func header(_ symbol: String, _ title: LocalizedStringKey, _ detail: String) -> some View {68        VStack(alignment: .leading, spacing: ORIX.Space.xs) {69            HStack(spacing: ORIX.Space.s) {70                Image(systemName: symbol).font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)71                Text(title).font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text)72                Spacer(minLength: 0)73            }74            Text(verbatim: detail).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)75        }76        .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.m)77        .frame(maxWidth: .infinity, alignment: .leading)78        .overlay(alignment: .bottom) { Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1) }79        .accessibilityElement(children: .combine)80    }8182    private func sizeDetail(_ w: Double, _ h: Double) -> String {83        let u = LengthUnit.current84        return "\(u.format(w)) × \(u.format(h))"85    }8687    // MARK: Size (images and shapes)8889    private func resize(_ w: Double, _ h: Double, key: String, _ t: Target) {90        update(String(localized: "Resize Object"), key: key, t) { inline in91            switch inline {92            case .image(var i): i.width = w; i.height = h; inline = .image(i)93            case .shape(var s): s.width = w; s.height = h; inline = .shape(s)94            default: break95            }96        }97    }9899    @ViewBuilder private func sizeRows(width: Double, height: Double, _ t: Target) -> some View {100        let ratio = width > 0 ? height / width : 1101        PropertyRow("Width") {102            LengthField(points: width, range: 4...14_400, label: "Object width", identifier: "object-width") { w in103                resize(w, lockAspect ? max(4, (w * ratio * 100).rounded() / 100) : height, key: "w", t)104            }105        }106        PropertyRow("Height") {107            LengthField(points: height, range: 4...14_400, label: "Object height", identifier: "object-height") { h in108                resize(lockAspect && ratio > 0 ? max(4, (h / ratio * 100).rounded() / 100) : width, h, key: "h", t)109            }110        }111        SwitchRow("Lock aspect ratio", isOn: lockAspect, identifier: "object-lock-aspect") { lockAspect = $0 }112    }113114    // MARK: Placement (images and shapes)115116    private static var wrapModes: [(value: WrapMode, title: String)] {117        [(.square, String(localized: "Square")), (.topAndBottom, String(localized: "Top and bottom")),118         (.behindText, String(localized: "Behind text")), (.inFrontOfText, String(localized: "In front of text"))]119    }120121    @ViewBuilder private func placementGroup(_ p: Placement, _ t: Target) -> some View {122        InspectorGroup("Placement", id: "object.placement") {123            TextSegments(items: [(false, String(localized: "Inline with text")), (true, String(localized: "Floating"))], selection: p.isFloating, identifier: "object-placement") { floating in124                guard floating != p.isFloating else { return }125                placement(String(localized: "Object Placement"), t) { $0 = floating ? .floating(wrap: .square, align: .left, xOffset: 0, yOffset: 0) : .inline }126            }127            if case .floating(let wrap, let align, let x, let y) = p {128                PropertyRow("Text wrap") {129                    ChoicePopup(selection: wrap, options: ObjectInspector.wrapModes, width: 140, label: "How text flows around the object", identifier: "object-wrap") { w in130                        placement(String(localized: "Text Wrap"), t) { $0 = .floating(wrap: w, align: align, xOffset: x, yOffset: y) }131                    }132                }133                PropertyRow("Align in column") {134                    IconSegments(items: [.init(value: HorizontalAnchor.left, symbol: "align.horizontal.left", title: String(localized: "Left of the column")),135                                         .init(value: .center, symbol: "align.horizontal.center", title: String(localized: "Centre of the column")),136                                         .init(value: .right, symbol: "align.horizontal.right", title: String(localized: "Right of the column"))],137                                 selection: align, identifier: "object-align") { a in138                        placement(String(localized: "Object Alignment"), t) { $0 = .floating(wrap: wrap, align: a, xOffset: x, yOffset: y) }139                    }140                }141                PropertyRow("Horizontal offset") {142                    LengthField(points: x, range: -1440...1440, label: "Horizontal offset from the aligned position", identifier: "object-x") { v in143                        placement(String(localized: "Object Position"), key: "x", t) { $0 = .floating(wrap: wrap, align: align, xOffset: v, yOffset: y) }144                    }145                }146                PropertyRow("Vertical offset") {147                    LengthField(points: y, range: -1440...1440, label: "Vertical offset below the top of the anchor paragraph", identifier: "object-y") { v in148                        placement(String(localized: "Object Position"), key: "y", t) { $0 = .floating(wrap: wrap, align: align, xOffset: x, yOffset: v) }149                    }150                }151                InspectorNote("A floating object is anchored to its paragraph and moves with it.")152            } else {153                InspectorNote("An inline object sits on the line like a character.")154            }155        }156    }157158    // MARK: Alternative text159160    @ViewBuilder private func altTextGroup(_ alt: String, required: Bool, _ commit: @escaping (String) -> Void) -> some View {161        InspectorGroup("Accessibility", id: "object.alt") {162            Text("Alternative text").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)163            InspectorTextField(text: alt, placeholder: String(localized: "Describe the object for people who cannot see it"), multiline: true,164                               label: "Alternative text", identifier: "object-alt-text", onCommit: commit)165            if alt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && required {166                InspectorNote("No alternative text yet. Screen readers and tagged PDFs need a short description.", symbol: "exclamationmark.triangle.fill", color: ORIX.Palette.warning)167            } else {168                InspectorNote("Read by screen readers and written to tagged PDF, DOCX and HTML exports.")169            }170        }171    }172173    // MARK: Image174175    private func naturalSize(of img: ImageObject) -> CGSize? {176        guard let asset = session.doc.assets[img.asset] else { return nil }177        if asset.mimeType == "application/pdf" {178            guard let provider = CGDataProvider(data: asset.data as CFData), let page = CGPDFDocument(provider)?.page(at: 1) else { return nil }179            return page.getBoxRect(.cropBox).size180        }181        return ImageStore.naturalSize(of: asset.data)182    }183184    @ViewBuilder private func imageEditor(_ img: ImageObject, _ t: Target) -> some View {185        header("photo", "Image", sizeDetail(img.width, img.height))186187        InspectorGroup("Size", id: "object.size") {188            sizeRows(width: img.width, height: img.height, t)189            let natural = naturalSize(of: img)190            InspectorButton("Reset to Natural Size", symbol: "arrow.uturn.backward", isEnabled: natural != nil, identifier: "object-reset-size") {191                guard let n = natural, n.width > 0, n.height > 0 else { return }192                // As on insertion: the natural size, reduced to fit the column.193                let scale = min(1, session.columnWidthAtCaret / n.width)194                image(String(localized: "Reset Image Size"), t) { $0.width = (n.width * scale).rounded(); $0.height = (n.height * scale).rounded() }195            }196            .help(natural.map { "Natural size: \(sizeDetail($0.width, $0.height)), reduced to the column width if larger" } ?? "The image data is not available")197        }198199        InspectorGroup("Rotation and Crop", id: "object.transform") {200            PropertyRow("Rotation") {201                BarButton(symbol: "rotate.left", help: "Rotate 90° anticlockwise") { image(String(localized: "Rotate Image"), t) { $0.rotation = ObjectInspector.normalized($0.rotation - 90) } }202                BarButton(symbol: "rotate.right", help: "Rotate 90° clockwise") { image(String(localized: "Rotate Image"), t) { $0.rotation = ObjectInspector.normalized($0.rotation + 90) } }203                ValueField(value: img.rotation, range: -360...360, step: 1, decimals: 1, suffix: "°", width: 66, label: "Clockwise rotation in degrees", identifier: "object-rotation") { v in204                    image(String(localized: "Rotate Image"), key: "rotation", t) { $0.rotation = v }205                }206            }207            Text("Crop").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)208            Grid(alignment: .leading, horizontalSpacing: ORIX.Space.s, verticalSpacing: ORIX.Space.s) {209                GridRow {210                    cropLabel("Top"); cropField(img.crop.top, other: img.crop.bottom, "Crop from the top", "ct", t) { $0.crop.top = $1 }211                    cropLabel("Bottom").padding(.leading, 4); cropField(img.crop.bottom, other: img.crop.top, "Crop from the bottom", "cb", t) { $0.crop.bottom = $1 }212                }213                GridRow {214                    cropLabel("Left"); cropField(img.crop.left, other: img.crop.right, "Crop from the left", "cl", t) { $0.crop.left = $1 }215                    cropLabel("Right").padding(.leading, 4); cropField(img.crop.right, other: img.crop.left, "Crop from the right", "cr", t) { $0.crop.right = $1 }216                }217            }218            if img.crop != .zero {219                InspectorButton("Remove Crop", symbol: "crop") { image(String(localized: "Crop Image"), t) { $0.crop = .zero } }220            }221        }222223        altTextGroup(img.altText, required: true) { text in image(String(localized: "Alternative Text"), t) { $0.altText = text } }224        placementGroup(img.placement, t)225226        VStack {227            InspectorButton("Replace Image…", symbol: "photo.badge.arrow.down", identifier: "object-replace") { replaceImage(t) }228        }229        .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.m)230    }231232    private static func normalized(_ degrees: Double) -> Double {233        var d = degrees.truncatingRemainder(dividingBy: 360)234        if d > 180 { d -= 360 } else if d <= -180 { d += 360 }235        return d236    }237238    private func cropLabel(_ text: LocalizedStringKey) -> some View {239        Text(text).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).fixedSize()240    }241242    private func cropField(_ fraction: Double, other: Double, _ label: LocalizedStringKey, _ key: String, _ t: Target, _ set: @escaping (inout ImageObject, Double) -> Void) -> some View {243        // Opposite edges may not meet: at least 5 % of the image stays visible.244        ValueField(value: fraction * 100, range: 0...max(0, 95 - other * 100), step: 1, decimals: 1, suffix: "%", width: 70, label: label) { v in245            image(String(localized: "Crop Image"), key: key, t) { set(&$0, v / 100) }246        }247    }248249    private func replaceImage(_ t: Target) {250        guard let window = session.canvas?.window else { return }251        let panel = NSOpenPanel()252        panel.allowedContentTypes = [.image, .pdf]253        panel.allowsMultipleSelection = false254        panel.beginSheetModal(for: window) { response in255            guard response == .OK, let url = panel.url, let data = try? Data(contentsOf: url), data.count < 200 * 1024 * 1024 else { return }256            let mime = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "image/png"257            var size: CGSize?258            if mime == "application/pdf" {259                if let provider = CGDataProvider(data: data as CFData), let page = CGPDFDocument(provider)?.page(at: 1) { size = page.getBoxRect(.cropBox).size }260            } else {261                size = ImageStore.naturalSize(of: data)262            }263            guard let s = size, s.width > 0, s.height > 0 else {264                session.statusMessage = String(localized: "The image could not be read.")265                return266            }267            let asset = Asset(mimeType: mime, data: data)268            session.perform(String(localized: "Replace Image")) { e in269                e.doc.assets[asset.id] = asset270                e.updateInline(at: t.position, in: t.story) { inline in271                    guard case .image(var i) = inline else { return }272                    // Same width on the page; the height follows the new picture's proportions.273                    i.asset = asset.id274                    i.height = (i.width * s.height / s.width).rounded()275                    i.crop = .zero276                    inline = .image(i)277                }278            }279            session.focusCanvas()280        }281    }282283    // MARK: Shape284285    private static func shapeName(_ k: ShapeObject.Kind) -> String {286        switch k {287        case .rectangle: return String(localized: "Rectangle")288        case .roundedRectangle: return String(localized: "Rounded rectangle")289        case .ellipse: return String(localized: "Ellipse")290        case .line: return String(localized: "Line")291        case .arrow: return String(localized: "Arrow")292        case .callout: return String(localized: "Callout")293        }294    }295296    @ViewBuilder private func shapeEditor(_ s: ShapeObject, _ t: Target) -> some View {297        let linear = s.kind == .line || s.kind == .arrow298        header("square.on.circle", "Shape", "\(ObjectInspector.shapeName(s.kind)) · \(sizeDetail(s.width, s.height))")299300        InspectorGroup("Shape", id: "object.shape") {301            PropertyRow("Kind") {302                ChoicePopup(selection: s.kind, options: ShapeObject.Kind.allCases.map { ($0, ObjectInspector.shapeName($0)) }, width: 150, label: "Shape kind", identifier: "object-shape-kind") { k in303                    shape(String(localized: "Shape Kind"), t) { $0.kind = k }304                }305            }306            sizeRows(width: s.width, height: s.height, t)307        }308        InspectorGroup("Stroke and Fill", id: "object.stroke") {309            PropertyRow("Stroke") {310                ValueField(value: s.strokeWidth, range: 0...24, step: 0.25, decimals: 2, suffix: "pt", width: 66, label: "Stroke width", identifier: "object-stroke-width") { v in311                    shape(String(localized: "Stroke Width"), key: "sw", t) { $0.strokeWidth = v }312                }313                SwatchMenu(help: "Stroke colour", current: s.stroke, identifier: "object-stroke") { c in shape(String(localized: "Stroke Colour"), key: "sc", t) { if let c { $0.stroke = c } } }314            }315            if !linear {316                PropertyRow("Fill") {317                    SwatchMenu(help: "Fill colour", current: s.fill, allowsNone: true, palette: ColorMenu.highlights + ColorMenu.inks, identifier: "object-fill") { c in318                        shape(String(localized: "Fill Colour"), key: "fc", t) { $0.fill = c }319                    }320                }321            }322        }323        if !linear {324            InspectorGroup("Text", id: "object.text") {325                InspectorTextField(text: s.text, placeholder: String(localized: "Text inside the shape"), multiline: true, label: "Text inside the shape", identifier: "object-shape-text") { text in326                    shape(String(localized: "Shape Text"), t) { $0.text = text }327                }328            }329        }330        altTextGroup(s.altText, required: s.text.isEmpty) { text in shape(String(localized: "Alternative Text"), t) { $0.altText = text } }331        placementGroup(s.placement, t)332    }333334    // MARK: Equation335336    @ViewBuilder private func equationEditor(_ eq: Equation, _ t: Target) -> some View {337        header("function", "Equation", eq.display ? String(localized: "Display style") : String(localized: "Inline style"))338339        InspectorGroup("Equation", id: "object.equation") {340            EquationPreview(latex: eq.latex, display: eq.display)341            Text("LaTeX source").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)342            Text(verbatim: eq.latex.isEmpty ? "—" : eq.latex)343                .font(.system(size: 11, design: .monospaced)).foregroundStyle(ORIX.Palette.text).textSelection(.enabled)344                .lineLimit(8).fixedSize(horizontal: false, vertical: true)345                .padding(.horizontal, 7).padding(.vertical, 5).frame(maxWidth: .infinity, alignment: .leading)346                .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))347                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline))348                .accessibilityLabel(Text("LaTeX source: \(eq.latex)"))349                .accessibilityIdentifier("object-equation-source")350            InspectorButton("Edit Equation…", symbol: "pencil", prominent: true, identifier: "object-equation-edit") { session.activeSheet = .equation(existing: t.position) }351            SwitchRow("Display style", isOn: eq.display, identifier: "object-equation-display") { on in352                update(String(localized: "Equation Style"), t) { inline in if case .equation(var e) = inline { e.display = on; inline = .equation(e) } }353            }354            InspectorNote("Display style sets larger operators and limits above and below, as for an equation on its own line.")355        }356    }357}358359/// The typeset equation on paper, scaled down when wider than the panel.360private struct EquationPreview: View {361    let latex: String362    let display: Bool363364    var body: some View {365        let layout = MathRenderer.layout(latex: latex, fontSize: 15, display: display)366        let size = NSSize(width: max(1, ceil(layout.width)), height: max(1, ceil(layout.ascent + layout.descent)))367        let ascent = layout.ascent368        let image = NSImage(size: size, flipped: true) { _ in369            guard let ctx = NSGraphicsContext.current?.cgContext else { return false }370            layout.draw(in: ctx, at: CGPoint(x: 0, y: ascent))371            return true372        }373        VStack(alignment: .leading, spacing: ORIX.Space.xs) {374            HStack {375                Spacer(minLength: 0)376                if size.width > 216 {377                    Image(nsImage: image).resizable().scaledToFit().frame(maxWidth: 216)378                } else {379                    Image(nsImage: image)380                }381                Spacer(minLength: 0)382            }383            .padding(.vertical, 10).padding(.horizontal, 8)384            .frame(maxWidth: .infinity, minHeight: 52)385            .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(Color.white))386            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.hairline))387            .accessibilityLabel(Text("Equation preview"))388            if let error = layout.error {389                InspectorNote("This source does not typeset: \(error)", symbol: "exclamationmark.triangle.fill", color: ORIX.Palette.warning)390            }391        }392    }393}394
Files main
Menu

Theme