Files
VCCPlusOSS/platforms/macos/App/ArchiveInlinePreview.swift

332 lines
17 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import AppKit
import ImageIO
import SwiftUI
import UniformTypeIdentifiers
/// ImageIO can be decoding a large diagram when the user moves through several rows.
/// Only one bitmap is decoded at a time, and superseded selections skip the decode.
actor ArchivePreviewDecoder {
static let shared = ArchivePreviewDecoder()
func read(_ url: URL, format: String, number: Int) throws -> ArchiveInlineContent {
try Task.checkCancellation()
if format == "image" { return try ArchiveInlineContent.loadImage(at: url, number: number) }
return try ArchiveInlineContent.loadText(at: url)
}
}
enum ArchiveInlineContent: Sendable {
case image(CGImage)
case text(String)
case worksheet(String)
/// Decode away from the main actor. Some original diagrams are over 260 megapixels.
static func loadImage(at url: URL, number: Int = 1) throws -> Self {
let options = [kCGImageSourceShouldCache: false] as CFDictionary
guard number > 0, let source = CGImageSourceCreateWithURL(url as CFURL, options),
let type = CGImageSourceGetType(source) as String?,
[UTType.jpeg, .png, .gif, .tiff, .bmp, .webP].contains(where: { $0.identifier == type }) else {
throw PreviewError.image
}
if let image = thumbnail(source, index: number - 1) { return .image(image) }
if type == UTType.tiff.identifier, number == 1,
let corrected = tiffWithoutDuplicatePalette(at: url), let image = thumbnail(corrected, index: 0) {
return .image(image)
}
throw PreviewError.image
}
private static func thumbnail(_ source: CGImageSource, index: Int) -> CGImage? {
let options = [kCGImageSourceShouldCache: false] as CFDictionary
guard index < CGImageSourceGetCount(source),
let properties = CGImageSourceCopyPropertiesAtIndex(source, index, options) as? [CFString: Any],
let width = properties[kCGImagePropertyPixelWidth] as? Int, width > 0,
let height = properties[kCGImagePropertyPixelHeight] as? Int, height > 0 else {
return nil
}
// Bound the decoded bitmap to 16 megapixels, retaining aspect and EXIF orientation.
let ratio = min(1, sqrt(16_000_000 / (Double(width) * Double(height))))
let longest = max(1, Int((Double(max(width, height)) * ratio).rounded(.down)))
let thumbnailOptions: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: longest,
kCGImageSourceShouldCacheImmediately: true
]
return CGImageSourceCreateThumbnailAtIndex(source, index, thumbnailOptions as CFDictionary)
}
/// The Glenside IDE schematic has two ColorMap tags in its classic TIFF directory.
/// Keep the first palette, as libtiff does, in a bounded in-memory copy for ImageIO.
private static func tiffWithoutDuplicatePalette(at url: URL) -> CGImageSource? {
let limit = 8 * 1024 * 1024
guard let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= limit,
var bytes = try? Data(contentsOf: url), bytes.count >= 8, bytes.count <= limit else { return nil }
let littleEndian = bytes.starts(with: [0x49, 0x49, 42, 0])
guard littleEndian || bytes.starts(with: [0x4d, 0x4d, 0, 42]) else { return nil }
func integer(at start: Int, count: Int) -> Int {
(0..<count).reduce(0) { result, index in
let offset = littleEndian ? count - 1 - index : index
return (result << 8) | Int(bytes[start + offset])
}
}
let directory = integer(at: 4, count: 4)
guard directory >= 8, directory + 2 <= bytes.count else { return nil }
let count = integer(at: directory, count: 2)
let first = directory + 2
let end = first + count * 12
guard count >= 2, end + 4 <= bytes.count else { return nil }
for entry in stride(from: first + 12, to: end, by: 12) {
guard integer(at: entry - 12, count: 2) == 320, integer(at: entry, count: 2) == 320 else { continue }
let values = integer(at: entry + 4, count: 4)
guard (6...(3 * 65_536)).contains(values), values.isMultiple(of: 3),
(values / 3).nonzeroBitCount == 1,
[entry - 12, entry].allSatisfy({ tag in
let palette = integer(at: tag + 8, count: 4)
return integer(at: tag + 2, count: 2) == 3 && integer(at: tag + 4, count: 4) == values
&& palette >= 8 && palette + 2 * values <= bytes.count
}) else { return nil }
// Slide just the remaining directory entries and the next-directory pointer.
// Strip offsets and all data elsewhere in the file retain their positions.
let rest = bytes[(entry + 12)..<(end + 4)]
bytes.replaceSubrange(entry..<(entry + rest.count), with: rest)
bytes[directory + (littleEndian ? 0 : 1)] = UInt8(truncatingIfNeeded: count - 1)
bytes[directory + (littleEndian ? 1 : 0)] = UInt8((count - 1) >> 8)
return CGImageSourceCreateWithData(bytes as CFData, nil)
}
return nil
}
static func loadText(at url: URL) throws -> Self {
let limit = 8 * 1024 * 1024
guard let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size <= limit else { throw PreviewError.text }
let data = try Data(contentsOf: url, options: .mappedIfSafe)
guard data.count <= limit else { throw PreviewError.text }
// A number of the Archive's floppy-era text files have NUL/EOF sector padding.
let text: String?
if data.starts(with: [0xff, 0xfe]) || data.starts(with: [0xfe, 0xff]) {
text = String(data: data, encoding: .utf16)
} else {
var end = data.endIndex
while end > data.startIndex {
let last = data[end - 1]
guard last == 0 || last == 0x1a || last == 0xff else { break }
end -= 1
}
if !data[end...].contains(0) && !data[end...].contains(0x1a) { end = data.endIndex }
let bytes = data[..<end]
let start = bytes.starts(with: [0xef, 0xbb, 0xbf]) ? bytes.dropFirst(3) : bytes
text = String(data: start, encoding: .utf8)
?? String(data: start, encoding: .windowsCP1252)
?? String(data: start, encoding: .isoLatin1)
}
guard let text else { throw PreviewError.text }
return .text(text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n"))
}
private enum PreviewError: LocalizedError {
case image, text
var errorDescription: String? {
switch self {
case .image: return "The image could not be opened at the cited location."
case .text: return "The original could not be read as an Archive text document."
}
}
}
}
struct ArchiveInlinePreview: View {
let content: ArchiveInlineContent
let title: String
var position: LibraryReadingPosition? = nil
var onPositionChange: (Double, Double, Double?) -> Void = { _,_,_ in }
var body: some View {
switch content {
case .image(let image): ArchiveInlineImage(image: image, title: title, position: position, onPositionChange: onPositionChange)
case .text(let text): ArchiveInlineText(text: text, worksheet: false, title: title, position: position, onPositionChange: onPositionChange)
case .worksheet(let text): ArchiveInlineText(text: text, worksheet: true, title: title, position: position, onPositionChange: onPositionChange)
}
}
}
private struct ArchiveInlineImage: View {
let image: CGImage
let title: String
let position: LibraryReadingPosition?
let onPositionChange: (Double, Double, Double?) -> Void
@State private var zoom: Int
init(image: CGImage, title: String, position: LibraryReadingPosition?, onPositionChange: @escaping (Double, Double, Double?) -> Void) {
self.image = image; self.title = title; self.position = position; self.onPositionChange = onPositionChange
_zoom = State(initialValue: min(5,max(0,Int(log2(position?.zoom ?? 1)))))
}
var body: some View {
VStack(spacing: 0) {
HStack {
Button("Fit Image") { zoom = 0 }.disabled(zoom == 0)
Button { zoom -= 1 } label: { Image(systemName: "minus.magnifyingglass") }
.disabled(zoom == 0).accessibilityLabel("Zoom out")
Button { zoom += 1 } label: { Image(systemName: "plus.magnifyingglass") }
.disabled(zoom >= 5).accessibilityLabel("Zoom in")
Spacer()
}.padding(6)
Divider()
ArchiveImageSurface(image: image, title: title, zoom: zoom, initialPosition: position, onPositionChange: onPositionChange)
}
}
}
private struct ArchiveImageSurface: NSViewRepresentable {
let image: CGImage
let title: String
let zoom: Int
let initialPosition: LibraryReadingPosition?
let onPositionChange: (Double, Double, Double?) -> Void
func makeCoordinator() -> Coordinator { Coordinator() }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView()
scroll.hasHorizontalScroller = true; scroll.hasVerticalScroller = true
let imageView = NSImageView()
imageView.image = NSImage(cgImage: image, size: NSSize(width: image.width, height: image.height))
imageView.imageScaling = .scaleAxesIndependently
imageView.setAccessibilityLabel(title)
imageView.setAccessibilityIdentifier("archive-inline-image")
let container = NSView()
container.addSubview(imageView)
scroll.documentView = container
context.coordinator.imageView = imageView
context.coordinator.scroll = scroll
scroll.contentView.postsBoundsChangedNotifications = true
context.coordinator.observer = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: scroll.contentView, queue: .main) { [weak coordinator = context.coordinator] _ in coordinator?.changed() }
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
let coordinator = context.coordinator
coordinator.onPositionChange = onPositionChange; coordinator.imageSize = NSSize(width: image.width, height: image.height)
coordinator.initialPosition = initialPosition; coordinator.zoom = zoom
DispatchQueue.main.async { [weak coordinator] in coordinator?.layout() }
}
final class Coordinator {
weak var scroll: NSScrollView?
weak var imageView: NSImageView?
var observer: NSObjectProtocol?
var imageSize = NSSize.zero
var initialPosition: LibraryReadingPosition?
var zoom = 0
var restored = false
var layingOut = false
var viewport = NSSize.zero
var onPositionChange: (Double,Double,Double?) -> Void = { _,_,_ in }
deinit { if let observer { NotificationCenter.default.removeObserver(observer) } }
func layout() {
guard let scroll, let image = scroll.documentView, imageSize.width > 0,
scroll.contentSize.width > 0, scroll.contentSize.height > 0 else { return }
layingOut = true
viewport = scroll.contentSize
let fit = min(1,min(scroll.contentSize.width/imageSize.width,scroll.contentSize.height/imageSize.height))
let picture = NSSize(width:imageSize.width*fit*pow(2,Double(zoom)),height:imageSize.height*fit*pow(2,Double(zoom)))
let size = NSSize(width:max(scroll.contentSize.width,picture.width),height:max(scroll.contentSize.height,picture.height))
image.setFrameSize(size)
imageView?.frame = NSRect(x:(size.width-picture.width)/2,y:(size.height-picture.height)/2,width:picture.width,height:picture.height)
if !restored {
restored = true
let target = NSPoint(x:(initialPosition?.horizontalOffset ?? 0)*max(0,size.width-scroll.contentSize.width),y:(initialPosition?.offset ?? 0)*max(0,size.height-scroll.contentSize.height))
scroll.contentView.scroll(to: target); scroll.reflectScrolledClipView(scroll.contentView)
}
layingOut = false
changed()
}
func changed() {
guard !layingOut, let scroll, let image = scroll.documentView else { return }
if viewport != scroll.contentSize { layout(); return }
let x = scroll.contentView.bounds.minX/max(1,image.bounds.width-scroll.contentSize.width)
let y = scroll.contentView.bounds.minY/max(1,image.bounds.height-scroll.contentSize.height)
onPositionChange(min(1,max(0,y)),min(1,max(0,x)),pow(2,Double(zoom)))
}
}
}
private struct ArchiveInlineText: NSViewRepresentable {
let text: String
let worksheet: Bool
let title: String
let position: LibraryReadingPosition?
let onPositionChange: (Double, Double, Double?) -> Void
func makeCoordinator() -> Coordinator { Coordinator() }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSTextView.scrollableTextView()
scroll.contentView.postsBoundsChangedNotifications = true
context.coordinator.scroll = scroll
context.coordinator.observer = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: scroll.contentView, queue: .main) { [weak coordinator = context.coordinator] _ in coordinator?.changed() }
guard let view = scroll.documentView as? NSTextView else { return scroll }
view.isEditable = false
view.isSelectable = true
view.isRichText = false
view.usesFindBar = true
view.isIncrementalSearchingEnabled = true
view.textContainerInset = NSSize(width: 12, height: 10)
view.font = .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular)
view.textColor = .textColor
view.backgroundColor = .textBackgroundColor
view.setAccessibilityIdentifier("archive-inline-text")
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let view = scroll.documentView as? NSTextView else { return }
context.coordinator.onPositionChange = onPositionChange
view.setAccessibilityLabel(title)
guard view.string != text else { return }
view.string = text
scroll.hasHorizontalScroller = worksheet
view.isHorizontallyResizable = worksheet
view.textContainer?.widthTracksTextView = !worksheet
if worksheet, let font = view.font {
// The indexed worksheet starts each row with its original row number. Align
// columns for reading while keeping the original tabs in a copied selection.
var widths: [CGFloat] = []
for row in text.split(separator: "\n") {
for (index, cell) in row.components(separatedBy: "\t").enumerated() {
if index == widths.count { widths.append(0) }
widths[index] = max(widths[index], (cell as NSString).size(withAttributes: [.font: font]).width)
}
}
var location: CGFloat = 0
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byClipping
style.tabStops = widths.map { width in
location += ceil(width) + 18
return NSTextTab(textAlignment: .left, location: location)
}
let width = location + 2 * (view.textContainerInset.width + 6)
view.textContainer?.containerSize = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude)
view.setFrameSize(NSSize(width: max(scroll.contentSize.width, width), height: view.frame.height))
view.textStorage?.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: (text as NSString).length))
}
view.setSelectedRange(NSRange(location: 0, length: 0))
let initial = position
DispatchQueue.main.async { [weak scroll] in
guard let scroll, let view = scroll.documentView as? NSTextView else { return }
view.layoutManager?.ensureLayout(for: view.textContainer!)
let point = NSPoint(x:(initial?.horizontalOffset ?? 0)*max(0,view.bounds.width-scroll.contentSize.width),y:(initial?.offset ?? 0)*max(0,view.bounds.height-scroll.contentSize.height))
scroll.contentView.scroll(to: point); scroll.reflectScrolledClipView(scroll.contentView)
}
}
final class Coordinator {
weak var scroll: NSScrollView?
var observer: NSObjectProtocol?
var onPositionChange: (Double,Double,Double?) -> Void = { _,_,_ in }
deinit { if let observer { NotificationCenter.default.removeObserver(observer) } }
func changed() {
guard let scroll, let view = scroll.documentView else { return }
let y = scroll.contentView.bounds.minY/max(1,view.bounds.height-scroll.contentSize.height)
let x = scroll.contentView.bounds.minX/max(1,view.bounds.width-scroll.contentSize.width)
onPositionChange(min(1,max(0,y)),min(1,max(0,x)),nil)
}
}
}