241 lines
12 KiB
Swift
241 lines
12 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 body: some View {
|
|
switch content {
|
|
case .image(let image): ArchiveInlineImage(image: image, title: title)
|
|
case .text(let text): ArchiveInlineText(text: text, worksheet: false, title: title)
|
|
case .worksheet(let text): ArchiveInlineText(text: text, worksheet: true, title: title)
|
|
}
|
|
}
|
|
}
|
|
|
|
private struct ArchiveInlineImage: View {
|
|
let image: CGImage
|
|
let title: String
|
|
@State private var zoom = 0
|
|
|
|
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()
|
|
GeometryReader { geometry in
|
|
let width = CGFloat(image.width), height = CGFloat(image.height)
|
|
let fit = min(1, min(geometry.size.width / width, geometry.size.height / height))
|
|
let scale = fit * pow(2.0, CGFloat(zoom))
|
|
ScrollView([.horizontal, .vertical]) {
|
|
Image(image, scale: 1, label: Text(title))
|
|
.resizable()
|
|
.frame(width: width * scale, height: height * scale)
|
|
.accessibilityIdentifier("archive-inline-image")
|
|
.frame(minWidth: geometry.size.width, minHeight: geometry.size.height)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private struct ArchiveInlineText: NSViewRepresentable {
|
|
let text: String
|
|
let worksheet: Bool
|
|
let title: String
|
|
|
|
func makeNSView(context: Context) -> NSScrollView {
|
|
let scroll = NSTextView.scrollableTextView()
|
|
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 }
|
|
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))
|
|
scroll.contentView.scroll(to: .zero)
|
|
scroll.reflectScrolledClipView(scroll.contentView)
|
|
}
|
|
}
|