diff --git a/.gitignore b/.gitignore index e98b57f..e9ede66 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,6 @@ tmp/ # Copyrighted sample maps used for local testing only — never commit. TestData/ coverage/ +ios/build/ +ios/Local.xcconfig +ios/Version.xcconfig diff --git a/Makefile b/Makefile index 286cf51..47fafee 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: build test lint coverage app run install dmg appstore icon clean +.PHONY: build test lint coverage app run install dmg appstore icon ipad-install ipad-simulator ipad-uitests clean build: swift build @@ -31,9 +31,21 @@ appstore: swift package resolve CHANNEL=appstore scripts/build-app.sh -# Redraws Resources/AppIcon.icns from scripts/make-icon.swift. +# Builds the iPad app and installs it on a connected iPad. IPAD names the iPad. +ipad-install: + scripts/install-ipad.sh + +# Builds the iPad app and starts it in a simulator. IPAD_SIMULATOR names the simulator. +ipad-simulator: + scripts/run-ipad-simulator.sh + +# Runs the iPad UI tests, which screenshot the window in both orientations. +ipad-uitests: + scripts/run-ipad-uitests.sh + +# Redraws Resources/AppIcon.icns and the iPad's icon from scripts/make-icon.swift. icon: scripts/make-icon.sh clean: - rm -rf .build build coverage + rm -rf .build build coverage ios/build diff --git a/Package.swift b/Package.swift index 5942851..3732c9c 100644 --- a/Package.swift +++ b/Package.swift @@ -3,23 +3,26 @@ import PackageDescription let package = Package( name: "Mapsmith", - platforms: [.macOS(.v15)], + platforms: [.macOS(.v15), .iOS(.v18)], products: [ .executable(name: "Mapsmith", targets: ["Mapsmith"]), - .library(name: "MapsmithCore", targets: ["MapsmithCore"]) + .library(name: "MapsmithCore", targets: ["MapsmithCore"]), + // The app shared by the Mac executable and the iPad project in ios/. + .library(name: "MapsmithUI", targets: ["MapsmithUI"]) ], dependencies: [ .package(url: "https://github.com/scooper4711/tabletop-kit.git", from: "1.0.0") ], targets: [ .target(name: "MapsmithCore", dependencies: [.product(name: "TablesideShared", package: "tabletop-kit")]), - .executableTarget( - name: "Mapsmith", + .target( + name: "MapsmithUI", dependencies: [ "MapsmithCore", .product(name: "AppNotices", package: "tabletop-kit"), .product(name: "TablesideShared", package: "tabletop-kit") ] ), + .executableTarget(name: "Mapsmith", dependencies: ["MapsmithUI"]), .testTarget( name: "MapsmithCoreTests", dependencies: ["MapsmithCore", .product(name: "TablesideShared", package: "tabletop-kit")] diff --git a/README.md b/README.md index 4f6c74a..2752c3f 100644 --- a/README.md +++ b/README.md @@ -5,13 +5,13 @@ [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=scooper4711_mapsmith&metric=coverage)](https://sonarcloud.io/summary/new_code?id=scooper4711_mapsmith) [![GitHub Release](https://img.shields.io/github/v/release/scooper4711/mapsmith)](https://github.com/scooper4711/mapsmith/releases) [![GitHub Downloads](https://img.shields.io/github/downloads/scooper4711/mapsmith/total)](https://github.com/scooper4711/mapsmith/releases) -[![Platform](https://img.shields.io/badge/platform-macOS%2015%2B-informational)](#requirements) +[![Platform](https://img.shields.io/badge/platform-macOS%2015%2B%20%7C%20iPadOS%2018%2B-informational)](#requirements) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE) Have you tried printing a Flip-Mat PDF or an adventure's map at home? The map is far bigger than a sheet of paper, and printing it "to fit" shrinks the squares until your miniatures no longer fit them. -Mapsmith is a Mac app that prints battle maps at true scale, one grid square per inch, on ordinary printer +Mapsmith is a Mac and iPad app that prints battle maps at true scale, one grid square per inch, on ordinary printer paper. It finds the map's grid, splits the map into pages that fit your printer's printable area at exactly one inch per square, and prints them, ready to trim and tape together. @@ -59,9 +59,21 @@ Grid detection sums edge strength along every row and column of the map and find autocorrelation. If no grid is found, the app falls back to the PDF's own page scale or the image's DPI metadata, and you can always type the pixels per grid square yourself in the inspector. +### On the iPad + +The iPad app (it runs on the iPhone too) prints the same true-scale pages. The differences: + +- **Open** a PDF or image from the file browser, from Files or another app's share sheet (*Open in Mapsmith*), or + by dropping it on the window. One map is shown at a time. +- **Open from Scrollkeeper** lists the maps in the library Scrollkeeper on the iPad shares, and opens those it has + downloaded. Scrollkeeper on the iPad takes no requests, so download a map there first. +- The iPad has no Page Setup: choose the **paper** and the printer's **margin** (¼ in suits most printers) in the + inspector. Every page prints at 100%, whatever the printer's printable area. +- **Ink Prices** (the drop in the toolbar) holds the cartridge prices for the printer chosen in the inspector. + ## Requirements -macOS 15 or later. +macOS 15 or later, or iPadOS (or iOS) 18 or later. ## Installing a release @@ -109,9 +121,15 @@ make test # runs the unit tests make lint # runs SwiftLint make coverage # runs the tests and enforces the coverage threshold make dmg # packages the app into a disk image -make icon # redraws Resources/AppIcon.icns +make icon # redraws Resources/AppIcon.icns and the iPad's icon +make ipad-simulator # builds the iPad app and starts it in a simulator +make ipad-install # builds the iPad app and installs it on a connected iPad +make ipad-uitests # runs the iPad UI tests, which screenshot both orientations ``` +The iPad app is `ios/Mapsmith.xcodeproj` (scheme `Mapsmith-iPad`). To build it with your own Apple developer team, +put `DEVELOPMENT_TEAM = ` in `ios/Local.xcconfig` (see `ios/Signing.xcconfig`). + Building needs Xcode 16 or later (Swift 6 toolchain). `scripts/sign-app.sh` signs the app with the Developer ID when the keychain holds a Developer ID Application certificate, and ad hoc otherwise. Open `Package.swift` in Xcode to run and debug it. @@ -120,13 +138,15 @@ Tests that read real maps use PDFs in `TestData/`, which is not committed becaus Copy or link your own Flip-Mat PDFs there to run them; they are skipped when the folder is empty. The code is in two parts: `Sources/MapsmithCore` holds all the logic and is unit tested (grid detection, -finding maps in PDFs, planning and exporting pages), and `Sources/Mapsmith` is the SwiftUI app. +finding maps in PDFs, planning and exporting pages), and `Sources/MapsmithUI` is the SwiftUI app, shared by the Mac +(`Sources/Mapsmith`) and the iPad (`ios/`). ## Where things are stored | What | Where | |---|---| -| Images dropped from other apps | `~/Library/Caches/io.github.scooper4711.Mapsmith/Dropped Maps/` | +| Images dropped from other apps | `~/Library/Caches/io.github.scooper4711.Mapsmith/Dropped Maps/`; on the iPad, the app's caches | +| Ink prices; on the iPad also the paper, margin and printer | the app's preferences | | Exported pages | wherever you save them, as PDF files | | Maps opened from Scrollkeeper | Scrollkeeper's downloads folder; Mapsmith only reads Scrollkeeper's map list | diff --git a/Resources/PrivacyInfo.xcprivacy b/Resources/PrivacyInfo.xcprivacy deleted file mode 100644 index 8624286..0000000 --- a/Resources/PrivacyInfo.xcprivacy +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - NSPrivacyTracking - - NSPrivacyTrackingDomains - - NSPrivacyCollectedDataTypes - - NSPrivacyAccessedAPITypes - - - diff --git a/Sources/Mapsmith/main.swift b/Sources/Mapsmith/main.swift new file mode 100644 index 0000000..cff8a00 --- /dev/null +++ b/Sources/Mapsmith/main.swift @@ -0,0 +1,4 @@ +import MapsmithUI + +// The Mac entry point. The app itself lives in the MapsmithUI target, shared with the iPad. +MapsmithApp.main() diff --git a/Sources/MapsmithCore/DroppedImageStore.swift b/Sources/MapsmithCore/DroppedImageStore.swift index bd574cd..24c5bf8 100644 --- a/Sources/MapsmithCore/DroppedImageStore.swift +++ b/Sources/MapsmithCore/DroppedImageStore.swift @@ -30,6 +30,16 @@ public struct DroppedImageStore: Sendable { return url } + /// Copies a dropped file (on the iPad a PDF arrives as a file only readable during the drop) under a name not + /// already in use and returns where it went. + public func saveCopy(of file: URL, suggestedName: String?, type: UTType) throws -> URL { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = unusedURL(baseName: Self.baseName(from: suggestedName ?? file.lastPathComponent), + fileExtension: type.preferredFilenameExtension ?? file.pathExtension) + try FileManager.default.copyItem(at: file, to: url) + return url + } + private static func baseName(from suggestedName: String?) -> String { let stem = suggestedName.map { ($0 as NSString).deletingPathExtension } ?? "" let safe = stem.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: "-") diff --git a/Sources/MapsmithCore/PaperChoice.swift b/Sources/MapsmithCore/PaperChoice.swift new file mode 100644 index 0000000..2b443c4 --- /dev/null +++ b/Sources/MapsmithCore/PaperChoice.swift @@ -0,0 +1,50 @@ +import CoreGraphics + +/// A paper size the user picks where there is no Page Setup (the iPad), with the printer's unprintable border. +public enum PaperChoice: String, CaseIterable, Identifiable, Sendable { + case letter, legal, a4, a3, tabloid + + /// What fits most AirPrint printers: their unprintable border is 1/4 in or less. + public static let defaultMarginInches: CGFloat = 0.25 + /// The margin is kept between nothing and a quarter of the narrowest paper's width. + public static let marginRange: ClosedRange = 0...2 + + public var id: String { rawValue } + + public var title: String { + switch self { + case .letter: "US Letter" + case .legal: "US Legal" + case .a4: "A4" + case .a3: "A3" + case .tabloid: "Tabloid" + } + } + + /// The paper's size in points, portrait. + public var size: CGSize { + switch self { + case .letter: CGSize(width: 612, height: 792) + case .legal: CGSize(width: 612, height: 1008) + case .a4: CGSize(width: 595.28, height: 841.89) + case .a3: CGSize(width: 841.89, height: 1190.55) + case .tabloid: CGSize(width: 792, height: 1224) + } + } + + /// The printable page: the paper with `marginInches` left blank on every side, the margin clamped to + /// `marginRange`. + public func geometry(marginInches: CGFloat) -> PageGeometry { + let clamped = min(max(marginInches, Self.marginRange.lowerBound), Self.marginRange.upperBound) + let margin = clamped * pointsPerInch + let paper = CGRect(origin: .zero, size: size) + return PageGeometry(paperSize: size, imageableRect: paper.insetBy(dx: margin, dy: margin)) + } + + /// The paper the user's region most likely uses: US Letter in the US and Canada and the other Letter + /// countries, A4 elsewhere. + public static func regionalDefault(regionCode: String?) -> PaperChoice { + let letterRegions: Set = ["US", "CA", "MX", "PH", "CL", "CO", "VE", "GT", "CR", "PA", "DO", "SV", "NI", "PR"] + return regionCode.map(letterRegions.contains) == true ? .letter : .a4 + } +} diff --git a/Sources/MapsmithCore/Scrollkeeper/ScrollkeeperBridge.swift b/Sources/MapsmithCore/Scrollkeeper/ScrollkeeperBridge.swift index 9047514..9b3da72 100644 --- a/Sources/MapsmithCore/Scrollkeeper/ScrollkeeperBridge.swift +++ b/Sources/MapsmithCore/Scrollkeeper/ScrollkeeperBridge.swift @@ -2,10 +2,13 @@ import Foundation import Observation import TablesideShared -/// What Mapsmith needs from the system to work with another app. The app uses `NSWorkspace`; -/// tests use a fake. +/// What Mapsmith needs from the system to work with another app. The Mac app uses `NSWorkspace`, the iPad app +/// `UIApplication`; tests use a fake. @MainActor public protocol ApplicationLauncher { + /// Whether Scrollkeeper here answers requests from other apps. Only the Mac's does; on the iPad Mapsmith reads + /// the shared library and nothing else. + var takesRequests: Bool { get } func isInstalled(_ bundleIdentifier: String) -> Bool /// Opens the URL without bringing its app to the front. func openInBackground(_ url: URL) @@ -38,6 +41,8 @@ public final class ScrollkeeperBridge { public enum State: Equatable, Sendable { case idle case notInstalled + /// Scrollkeeper takes no requests and hasn't shared its library (yet). + case noSharedLibrary /// Asked for the list; Scrollkeeper may still be starting or loading its library. case waiting case unsupportedVersion @@ -75,16 +80,24 @@ public final class ScrollkeeperBridge { return } if readLibrary() { return } + guard launcher.takesRequests else { + state = .noSharedLibrary + return + } state = .waiting launcher.openInBackground(Self.requestURL(host: "index", sku: nil)) } - /// Reads the library list again after Scrollkeeper says it changed, while the list shown came from it. + /// Reads the library list again after Scrollkeeper says it changed, or Mapsmith comes back to the + /// foreground, while the list shown came from it or there was none to show. public func refreshLibrary() { - guard isShowingLibrary else { return } + guard isShowingLibrary || state == .noSharedLibrary else { return } _ = readLibrary() } + /// Whether Scrollkeeper can be asked to download a title; when not, the user downloads it in Scrollkeeper. + public var takesRequests: Bool { launcher.takesRequests } + /// Reads the list Scrollkeeper handed over. public func receive(_ file: URL) { isShowingLibrary = false @@ -105,7 +118,7 @@ public final class ScrollkeeperBridge { } /// Opens the title's files when they are in the shared folder; otherwise asks Scrollkeeper to download the - /// title when needed and open it in Mapsmith. + /// title when needed and open it in Mapsmith, or where Scrollkeeper takes no requests, brings it forward. public func open(_ entry: ScrollkeeperIndex.Entry) { guard entry.localFiles.isEmpty else { openDocuments(entry.localFiles) @@ -114,7 +127,8 @@ public final class ScrollkeeperBridge { send(entry, opens: true) } - /// Asks Scrollkeeper to download the title without opening it. + /// Asks Scrollkeeper to download the title without opening it, or where it takes no requests, brings it + /// forward to download it there. public func download(_ entry: ScrollkeeperIndex.Entry) { send(entry, opens: false) } @@ -158,6 +172,10 @@ public final class ScrollkeeperBridge { } private func send(_ entry: ScrollkeeperIndex.Entry, opens: Bool) { + guard launcher.takesRequests else { + launchScrollkeeper() + return + } requests[entry.sku] = ScrollkeeperRequest(sku: entry.sku, opens: opens, phase: .requested) launcher.openInBackground(Self.requestURL(host: opens ? "open" : "download", sku: entry.sku)) } diff --git a/Sources/MapsmithUI/AppLinks.swift b/Sources/MapsmithUI/AppLinks.swift new file mode 100644 index 0000000..72f87c4 --- /dev/null +++ b/Sources/MapsmithUI/AppLinks.swift @@ -0,0 +1,7 @@ +import Foundation + +enum AppLinks { + // A literal URL that is known to parse. + // swiftlint:disable:next force_unwrapping + static let privacyPolicy = URL(string: "https://github.com/scooper4711/mapsmith/blob/main/PRIVACY.md")! +} diff --git a/Sources/Mapsmith/AppModel.swift b/Sources/MapsmithUI/AppModel.swift similarity index 83% rename from Sources/Mapsmith/AppModel.swift rename to Sources/MapsmithUI/AppModel.swift index 4e5d9f6..0000340 100644 --- a/Sources/Mapsmith/AppModel.swift +++ b/Sources/MapsmithUI/AppModel.swift @@ -1,4 +1,5 @@ -import AppKit +import CoreGraphics +import Foundation import MapsmithCore import Observation @@ -34,14 +35,18 @@ final class AppModel { var manualPixelsPerInch: Double? var minimumSliverInches: Double = 1 - /// Each window has its own page setup, starting from the one most recently chosen in any window. - let printInfo = NSPrintInfo.shared.copy() as? NSPrintInfo ?? .shared + /// The paper and printer the tiles are planned for (Page Setup on the Mac, the paper picker on the iPad). + let printSetup = PrintSetup() private(set) var page: PageGeometry = .a4Default + /// The rendered tiles waiting for the user to choose where to save them. + var exportedTiles: TilesPDF? /// The ink the current plan needs, once worked out for `inkEstimateKey`. private(set) var inkCoverage: InkEstimate? private var loadTask: Task? + /// The shown file while it is read in place under security-scoped access (files chosen on the iPad). + private var accessedURL: URL? - init() { page = PrintSetup.geometry(of: printInfo) } + init() { page = printSetup.page } var selectedItem: MapItem? { items.first { $0.id == selectedItemID } } @@ -83,14 +88,20 @@ final class AppModel { return InkEstimate.Key(itemID: itemID, plan: plan, page: page) } - var printerName: String { PrintSetup.printerName(of: printInfo) } - var paperName: String { PrintSetup.paperName(of: printInfo) } + var printerName: String { printSetup.printerName } + var paperName: String { printSetup.paperName } + + /// Plans the tiles again after the paper changed. + func refreshPage() { page = printSetup.page } // MARK: - Opening files func open(_ url: URL) { + let isAccessing = url.startAccessingSecurityScopedResource() do { let found = try MapItem.items(in: url) + stopAccessingShownFile() + accessedURL = isAccessing ? url : nil fileURL = url items = found thumbnails = [:] @@ -98,10 +109,16 @@ final class AppModel { if found.count != 1 { clearSelection() } loadThumbnails(for: found) } catch { + if isAccessing { url.stopAccessingSecurityScopedResource() } errorMessage = "\(error)" } } + private func stopAccessingShownFile() { + accessedURL?.stopAccessingSecurityScopedResource() + accessedURL = nil + } + private func loadThumbnails(for items: [MapItem]) { for item in items { Task.detached(priority: .utility) { [weak self] in @@ -159,31 +176,23 @@ final class AppModel { inkCoverage = InkEstimate(key: key, coverage: pages.reduce(.zero, +), pageCount: pages.count) } - // MARK: - Page setup, export and print - - func runPageSetup() { - guard PrintSetup.runPageSetup(printInfo) else { return } - page = PrintSetup.geometry(of: printInfo) - if let chosen = printInfo.copy() as? NSPrintInfo { NSPrintInfo.shared = chosen } - } + // MARK: - Export and print + /// Renders the tiles, then asks where to save them (the view shows the file exporter for `exportedTiles`). func exportPDF() { guard let map = loadedMap, let plan else { return } - let panel = NSSavePanel() - panel.allowedContentTypes = [.pdf] - panel.nameFieldStringValue = "\(documentTitle) tiles.pdf" - guard panel.runModal() == .OK, let url = panel.url else { return } + let name = "\(documentTitle) tiles" renderTiles(map: map, plan: plan) { [weak self] data in - do { try data.write(to: url) } catch { self?.errorMessage = "Export failed: \(error)" } + self?.exportedTiles = TilesPDF(data: data, name: name) } } func printTiles() { guard let map = loadedMap, let plan else { return } let title = documentTitle - let printInfo = self.printInfo + let printSetup = self.printSetup renderTiles(map: map, plan: plan) { data in - PrintSetup.printTiles(data, title: title, printInfo: printInfo) + printSetup.printTiles(data, title: title) } } diff --git a/Sources/Mapsmith/ContentView.swift b/Sources/MapsmithUI/ContentView.swift similarity index 60% rename from Sources/Mapsmith/ContentView.swift rename to Sources/MapsmithUI/ContentView.swift index f5b7e39..3d43c1b 100644 --- a/Sources/Mapsmith/ContentView.swift +++ b/Sources/MapsmithUI/ContentView.swift @@ -2,30 +2,58 @@ import AppNotices import MapsmithCore import SwiftUI +/// The ways in and out the window has, which each platform supplies: the Mac with its panels and windows, the iPad +/// with sheets. +struct DocumentActions { + var open: () -> Void = {} + var openFromScrollkeeper: () -> Void = {} + /// Ink prices; on the Mac they are in Settings, so this is nil there. + var showInkPrices: (() -> Void)? +} + +extension EnvironmentValues { + @Entry var documentActions = DocumentActions() +} + struct ContentView: View { @Environment(AppModel.self) private var model @Environment(DocumentRouter.self) private var router + @Environment(\.documentActions) private var actions @State private var showsInspector = true @State private var isDropTargeted = false - @Environment(\.openWindow) private var openWindow + @State private var columns = NavigationSplitViewVisibility.automatic var body: some View { @Bindable var model = model - NavigationSplitView { + NavigationSplitView(columnVisibility: $columns) { MapListView() .navigationSplitViewColumnWidth(min: 200, ideal: 240, max: 360) } detail: { detail + // On the detail column rather than the split view, where the iPad shows no toolbar. + .toolbar { toolbar } + .navigationTitle(model.fileURL?.lastPathComponent ?? "Mapsmith") + #if os(iOS) + .navigationBarTitleDisplayMode(.inline) + #endif .inspector(isPresented: $showsInspector) { SettingsInspector() .inspectorColumnWidth(min: 260, ideal: 280, max: 360) } } - .navigationTitle(model.fileURL?.lastPathComponent ?? "Mapsmith") - .toolbar { toolbar } + #if os(iOS) + // The iPad has less room: an image or a one-map PDF has nothing to choose in the list, so the map gets it. + .onChange(of: model.items.count, initial: true) { + columns = model.items.count > 1 ? .automatic : .detailOnly + } + #endif .onDrop(of: MapDrop.acceptedTypes, isTargeted: $isDropTargeted) { providers in MapDrop.open(providers, with: router) } + .fileExporter(isPresented: isExporting, document: model.exportedTiles, contentType: .pdf, + defaultFilename: model.exportedTiles?.name) { result in + if case let .failure(error) = result { model.errorMessage = "Export failed: \(error.localizedDescription)" } + } .alert("Something went wrong", isPresented: Binding( get: { model.errorMessage != nil }, set: { if !$0 { model.errorMessage = nil } } )) { @@ -35,13 +63,17 @@ struct ContentView: View { } } + private var isExporting: Binding { + Binding(get: { model.exportedTiles != nil }, set: { if !$0 { model.exportedTiles = nil } }) + } + /// A window with no file shows the two ways in, here only; the sidebar stays an empty list. @ViewBuilder private var detail: some View { if model.fileURL == nil, !model.isBusy { EmptyWindowView( title: "Open a Map", symbol: "map", message: "Drop a PDF or an image of a battle map here.", - isDropTargeted: isDropTargeted, open: { router.open(OpenPanel.chooseFiles()) }, - openFromScrollkeeper: { openWindow(id: ScrollkeeperWindow.id) }) + isDropTargeted: isDropTargeted, open: actions.open, + openFromScrollkeeper: actions.openFromScrollkeeper) } else { TilePreviewView() } @@ -50,11 +82,14 @@ struct ContentView: View { @ToolbarContentBuilder private var toolbar: some ToolbarContent { ToolbarItemGroup(placement: .primaryAction) { if model.isBusy { ProgressView().controlSize(.small) } - Button("Open", systemImage: "folder") { router.open(OpenPanel.chooseFiles()) } + Button("Open", systemImage: "folder", action: actions.open) Button("Export PDF", systemImage: "square.and.arrow.up") { model.exportPDF() } .disabled(model.plan == nil || model.isBusy) Button("Print", systemImage: "printer") { model.printTiles() } .disabled(model.plan == nil || model.isBusy) + if let showInkPrices = actions.showInkPrices { + Button("Ink Prices", systemImage: "drop", action: showInkPrices) + } Button("Settings", systemImage: "sidebar.right") { showsInspector.toggle() } } } diff --git a/Sources/Mapsmith/DeferredNumberField.swift b/Sources/MapsmithUI/DeferredNumberField.swift similarity index 51% rename from Sources/Mapsmith/DeferredNumberField.swift rename to Sources/MapsmithUI/DeferredNumberField.swift index f7bcdd1..2831af8 100644 --- a/Sources/Mapsmith/DeferredNumberField.swift +++ b/Sources/MapsmithUI/DeferredNumberField.swift @@ -13,7 +13,9 @@ struct DeferredNumberField: View { @State private var draft: Double? var body: some View { - TextField(title, value: $draft, format: .number.precision(.fractionLength(0...2)), prompt: Text(prompt)) + LabeledNumberField(title: title) { + TextField(title, value: $draft, format: .number.precision(.fractionLength(0...2)), prompt: Text(prompt)) + } .onSubmit { commitDraft() } .onChange(of: value, initial: true) { draft = value } .task(id: draft) { @@ -27,3 +29,24 @@ struct DeferredNumberField: View { if draft != value { commit(draft) } } } + +/// A number field with its title beside it. A Mac form shows a text field's title; an iOS form doesn't, so there +/// the title is a label of its own and the number sits on the right. +struct LabeledNumberField: View { + let title: String + @ViewBuilder let field: () -> Field + + var body: some View { + #if os(iOS) + LabeledContent(title) { + field() + .multilineTextAlignment(.trailing) + .keyboardType(.decimalPad) + // Narrow, so the title gets the room and isn't cut short. + .frame(maxWidth: 64) + } + #else + field() + #endif + } +} diff --git a/Sources/Mapsmith/InkCostRow.swift b/Sources/MapsmithUI/InkCostRow.swift similarity index 100% rename from Sources/Mapsmith/InkCostRow.swift rename to Sources/MapsmithUI/InkCostRow.swift diff --git a/Sources/Mapsmith/InkSettingsView.swift b/Sources/MapsmithUI/InkSettingsView.swift similarity index 92% rename from Sources/Mapsmith/InkSettingsView.swift rename to Sources/MapsmithUI/InkSettingsView.swift index 3da77f6..dc85903 100644 --- a/Sources/Mapsmith/InkSettingsView.swift +++ b/Sources/MapsmithUI/InkSettingsView.swift @@ -1,19 +1,17 @@ -import AppKit import MapsmithCore import SwiftUI -/// The Ink pane of Settings: what each of a printer's ink cartridges costs and yields. +/// What each of a printer's ink cartridges costs and yields: the Ink pane of Settings on the Mac, the Ink Prices +/// sheet on the iPad. struct InkSettingsView: View { let book: InkPriceBook - @State private var printer = NSPrintInfo.shared.printer.name + @State private var printer = InkPrinterChoice.initialPrinter @State private var draft = InkSet(cartridges: []) var body: some View { Form { - Picker("Printer", selection: $printer) { - ForEach(NSPrinter.printerNames, id: \.self) { Text($0).tag($0) } - } + InkPrinterChoice(printer: $printer) Section { ForEach(draft.cartridges.indices, id: \.self) { cartridgeRow($draft.cartridges[$0]) } } header: { @@ -44,7 +42,9 @@ struct InkSettingsView: View { } } .formStyle(.grouped) + #if os(macOS) .frame(width: 560, height: 600) + #endif .onChange(of: printer, initial: true) { loadDraft() } .onChange(of: draft) { book.save(draft, for: printer) } } diff --git a/Sources/Mapsmith/MapAnalysis.swift b/Sources/MapsmithUI/MapAnalysis.swift similarity index 100% rename from Sources/Mapsmith/MapAnalysis.swift rename to Sources/MapsmithUI/MapAnalysis.swift diff --git a/Sources/Mapsmith/MapDrop.swift b/Sources/MapsmithUI/MapDrop.swift similarity index 59% rename from Sources/Mapsmith/MapDrop.swift rename to Sources/MapsmithUI/MapDrop.swift index a141e4a..55eb877 100644 --- a/Sources/Mapsmith/MapDrop.swift +++ b/Sources/MapsmithUI/MapDrop.swift @@ -1,22 +1,25 @@ -import AppKit +import Foundation import MapsmithCore import os import UniformTypeIdentifiers -/// Opens whatever is dropped on a window: files, or images dragged straight out of another app -/// (such as a map from Pluck), which arrive as image data rather than as a file. +/// Opens whatever is dropped on a window: files, images dragged straight out of another app +/// (such as a map from Pluck), which arrive as image data rather than as a file, and on the iPad PDFs dragged +/// from Files, which arrive as a copy to take during the drop. @MainActor enum MapDrop { - static let acceptedTypes: [UTType] = [.fileURL, .image] + static let acceptedTypes: [UTType] = [.fileURL, .pdf, .image] private nonisolated static let logger = Logger(subsystem: "io.github.scooper4711.Mapsmith", category: "drop") static func open(_ providers: [NSItemProvider], with router: DocumentRouter) -> Bool { - let usable = providers.filter { carriesFile($0) || imageType(of: $0) != nil } + let usable = providers.filter { carriesFile($0) || carriesPDF($0) || imageType(of: $0) != nil } for provider in usable { - // Prefer the original file; use the image data only when no file is behind the drag. + // Prefer the original file; use a copy or the image data only when no file is behind the drag. if carriesFile(provider) { openFile(of: provider, with: router) + } else if carriesPDF(provider) { + openPDFCopy(of: provider, with: router) } else { openImageData(of: provider, with: router) } @@ -29,6 +32,24 @@ enum MapDrop { provider.registeredTypeIdentifiers.contains(UTType.fileURL.identifier) } + private static func carriesPDF(_ provider: NSItemProvider) -> Bool { + provider.hasItemConformingToTypeIdentifier(UTType.pdf.identifier) + } + + /// The file handed over is removed once the drop ends, so it is copied first. + private static func openPDFCopy(of provider: NSItemProvider, with router: DocumentRouter) { + let suggestedName = provider.suggestedName + _ = provider.loadFileRepresentation(for: .pdf) { file, _, error in + do { + guard let file else { throw error ?? CocoaError(.fileReadUnknown) } + let url = try DroppedImageStore.standard.saveCopy(of: file, suggestedName: suggestedName, type: .pdf) + Task { @MainActor in router.open([url]) } + } catch { + logger.error("Opening a dropped PDF failed: \(error.localizedDescription)") + } + } + } + private static func openFile(of provider: NSItemProvider, with router: DocumentRouter) { _ = provider.loadObject(ofClass: URL.self) { url, _ in guard let url else { return } diff --git a/Sources/Mapsmith/MapsmithApp.swift b/Sources/MapsmithUI/MapsmithApp.swift similarity index 94% rename from Sources/Mapsmith/MapsmithApp.swift rename to Sources/MapsmithUI/MapsmithApp.swift index 750dd0d..1d08220 100644 --- a/Sources/Mapsmith/MapsmithApp.swift +++ b/Sources/MapsmithUI/MapsmithApp.swift @@ -1,13 +1,16 @@ +#if os(macOS) import AppKit import MapsmithCore import TablesideShared import SwiftUI -@main -struct MapsmithApp: App { +/// The Mac app: a window per file, the Open from Scrollkeeper window and Settings. +public struct MapsmithApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate - var body: some Scene { + public init() {} + + public var body: some Scene { // One window per file, as in Preview. Opening a file that already has a window brings it forward. WindowGroup(for: URL.self) { $url in DocumentWindow(url: url, router: appDelegate.router, recents: appDelegate.recents) @@ -72,12 +75,6 @@ struct AppCommands: Commands { } } -enum AppLinks { - // A literal URL that is known to parse. - // swiftlint:disable:next force_unwrapping - static let privacyPolicy = URL(string: "https://github.com/scooper4711/mapsmith/blob/main/PRIVACY.md")! -} - extension FocusedValues { /// The model of the frontmost document window, for the menu bar. @Entry var documentModel: AppModel? @@ -153,6 +150,9 @@ struct DocumentWindow: View { ContentView() .environment(model) .environment(router) + .environment(\.documentActions, DocumentActions( + open: { router.open(OpenPanel.chooseFiles()) }, + openFromScrollkeeper: { openWindow(id: ScrollkeeperWindow.id) })) .focusedSceneValue(\.documentModel, model) .task(id: url) { showDocument() } // File-open events go to `AppDelegate`. Accepting them here as well stops SwiftUI @@ -185,3 +185,4 @@ struct DocumentWindow: View { if let url = model.fileURL { recents.note(url) } } } +#endif diff --git a/Sources/MapsmithUI/PadApp.swift b/Sources/MapsmithUI/PadApp.swift new file mode 100644 index 0000000..6077793 --- /dev/null +++ b/Sources/MapsmithUI/PadApp.swift @@ -0,0 +1,119 @@ +#if os(iOS) +import MapsmithCore +import SwiftUI +import TablesideShared +import UIKit + +/// The iPad and iPhone app: one window showing one map. Opening another file replaces it. +public struct MapsmithApp: App { + @State private var inkPrices = InkPriceBook() + + public init() {} + + public var body: some Scene { + WindowGroup { + PadRootView() + .environment(inkPrices) + } + } +} + +/// The window: the map, the file browser, and the Open from Scrollkeeper and Ink Prices sheets. +struct PadRootView: View { + @State private var model = AppModel() + @State private var router = DocumentRouter() + @State private var scrollkeeper = ScrollkeeperBridge(launcher: PadLauncher(), + libraryFolder: ToolkitGroup.scrollkeeperFolder()) + @State private var libraryChanges: LibraryChangeObserver? + @State private var isChoosingFile = false + @State private var isShowingScrollkeeper = false + @State private var isShowingInkPrices = false + @Environment(InkPriceBook.self) private var inkPrices + @Environment(\.scenePhase) private var scenePhase + + var body: some View { + ContentView() + .environment(model) + .environment(router) + .environment(\.documentActions, DocumentActions( + open: { isChoosingFile = true }, + openFromScrollkeeper: { isShowingScrollkeeper = true }, + showInkPrices: { isShowingInkPrices = true })) + .fileImporter(isPresented: $isChoosingFile, allowedContentTypes: [.pdf, .image]) { result in + switch result { + case let .success(url): router.open([url]) + case let .failure(error): model.errorMessage = "Opening failed: \(error.localizedDescription)" + } + } + .sheet(isPresented: $isShowingScrollkeeper) { scrollkeeperSheet } + .sheet(isPresented: $isShowingInkPrices) { inkPricesSheet } + .onOpenURL { router.open([$0]) } + .onChange(of: router.pendingURLs, initial: true) { openPending() } + .onChange(of: scenePhase) { if scenePhase == .active { scrollkeeper.refreshLibrary() } } + .onAppear(perform: startFollowingScrollkeeper) + #if DEBUG + .task { if let sample = UITestSample.urlIfRequested() { router.open([sample]) } } + #endif + } + + private var scrollkeeperSheet: some View { + NavigationStack { + ScrollkeeperBrowser(bridge: scrollkeeper) { isShowingScrollkeeper = false } + .navigationTitle("Open from Scrollkeeper") + .navigationBarTitleDisplayMode(.inline) + } + } + + private var inkPricesSheet: some View { + NavigationStack { + InkSettingsView(book: inkPrices) + .environment(model) + .navigationTitle("Ink Prices") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { isShowingInkPrices = false } + } + } + } + } + + /// The iPad shows one file, so of several waiting only the newest opens. + private func openPending() { + guard let url = router.claimPending().last else { return } + isShowingScrollkeeper = false + model.open(url) + } + + /// Scrollkeeper says when it rewrites its library list, so an open list follows its downloads. + private func startFollowingScrollkeeper() { + scrollkeeper.openDocuments = { [router] urls in router.open(urls) } + guard libraryChanges == nil else { return } + libraryChanges = LibraryChangeObserver { [scrollkeeper] in scrollkeeper.refreshLibrary() } + } +} + +/// The system side of `ApplicationLauncher` on the iPad. Scrollkeeper there takes no requests: Mapsmith only reads +/// its shared library and brings it forward to download a map. +struct PadLauncher: ApplicationLauncher { + // A literal URL that is known to parse. + // swiftlint:disable:next force_unwrapping + private static let scrollkeeperURL = URL(string: "scrollkeeper://")! + + var takesRequests: Bool { false } + + /// Scrollkeeper's link, when it registers one, or else its folder in the App Group, which it makes on its + /// first launch. + func isInstalled(_ bundleIdentifier: String) -> Bool { + if UIApplication.shared.canOpenURL(Self.scrollkeeperURL) { return true } + guard let folder = ToolkitGroup.scrollkeeperFolder() else { return false } + return FileManager.default.fileExists(atPath: folder.path) + } + + func openInBackground(_ url: URL) {} + + func launch(_ bundleIdentifier: String) { + UIApplication.shared.open(Self.scrollkeeperURL) + } +} +#endif diff --git a/Sources/MapsmithUI/PadPrintSetup.swift b/Sources/MapsmithUI/PadPrintSetup.swift new file mode 100644 index 0000000..7864434 --- /dev/null +++ b/Sources/MapsmithUI/PadPrintSetup.swift @@ -0,0 +1,64 @@ +#if os(iOS) +import MapsmithCore +import Observation +import UIKit + +/// The iPad's print settings: there is no Page Setup, so the user picks the paper and the printer's unprintable +/// border, and the printer whose ink prices to use. All three are remembered. +@MainActor @Observable +final class PrintSetup { + private enum Key { + static let paper = "PaperChoice" + static let margin = "PaperMarginInches" + static let printer = "InkPrinterName" + static let printerURL = "InkPrinterURL" + } + + @ObservationIgnored private let defaults: UserDefaults + + var paper: PaperChoice { didSet { defaults.set(paper.rawValue, forKey: Key.paper) } } + var marginInches: Double { didSet { defaults.set(marginInches, forKey: Key.margin) } } + /// The printer chosen with the printer picker; empty until one is. + private(set) var printerName: String + /// The chosen printer, so the print panel starts on it. + private(set) var printerURL: URL? + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + paper = defaults.string(forKey: Key.paper).flatMap(PaperChoice.init(rawValue:)) + ?? .regionalDefault(regionCode: Locale.current.region?.identifier) + marginInches = defaults.object(forKey: Key.margin) as? Double ?? Double(PaperChoice.defaultMarginInches) + printerName = defaults.string(forKey: Key.printer) ?? "" + printerURL = defaults.url(forKey: Key.printerURL) + } + + var page: PageGeometry { paper.geometry(marginInches: CGFloat(marginInches)) } + + var paperName: String { paper.title } + + /// Shows the system printer picker and remembers the printer chosen. + func choosePrinter() { + let picker = UIPrinterPickerController(initiallySelectedPrinter: printerURL.map(UIPrinter.init(url:))) + picker.present(animated: true) { [weak self] picker, chosen, _ in + guard chosen, let printer = picker.selectedPrinter else { return } + MainActor.assumeIsolated { self?.remember(printer) } + } + } + + func printTiles(_ data: Data, title: String) { + TilePrinter.print(data, title: title, paperSize: paper.size, printerURL: printerURL) + } + + private func remember(_ printer: UIPrinter) { + printerName = printer.displayName + printerURL = printer.url + defaults.set(printerName, forKey: Key.printer) + defaults.set(printerURL, forKey: Key.printerURL) + } +} + +/// The supplies of a printer, which AirPrint doesn't list; the ink settings start from the standard four inks. +enum PrinterSupplies { + static func list(for printerName: String) -> [PrinterSupply] { [] } +} +#endif diff --git a/Sources/Mapsmith/PrintSetup.swift b/Sources/MapsmithUI/PrintSetup.swift similarity index 56% rename from Sources/Mapsmith/PrintSetup.swift rename to Sources/MapsmithUI/PrintSetup.swift index 8a04f17..ffddff8 100644 --- a/Sources/Mapsmith/PrintSetup.swift +++ b/Sources/MapsmithUI/PrintSetup.swift @@ -1,12 +1,16 @@ +#if os(macOS) import AppKit import MapsmithCore import PDFKit -/// Bridges the app's print settings (`NSPrintInfo`) to the tiling geometry. +/// A window's print settings (`NSPrintInfo`) and the tiling geometry they give. @MainActor -enum PrintSetup { - /// The printable page described by `printInfo`, in PDF page coordinates. - static func geometry(of printInfo: NSPrintInfo) -> PageGeometry { +final class PrintSetup { + /// Each window has its own page setup, starting from the one most recently chosen in any window. + let printInfo = NSPrintInfo.shared.copy() as? NSPrintInfo ?? .shared + + /// The printable page, in PDF page coordinates. + var page: PageGeometry { let paper = printInfo.paperSize let imageable = printInfo.imageablePageBounds guard paper.width > 0, paper.height > 0, imageable.width > 0, imageable.height > 0 else { @@ -15,21 +19,20 @@ enum PrintSetup { return PageGeometry(paperSize: paper, imageableRect: imageable) } - static func printerName(of printInfo: NSPrintInfo) -> String { - printInfo.printer.name - } + var printerName: String { printInfo.printer.name } - static func paperName(of printInfo: NSPrintInfo) -> String { - printInfo.localizedPaperName ?? "Custom" - } + var paperName: String { printInfo.localizedPaperName ?? "Custom" } - /// Shows the standard Page Setup sheet. Returns true when the user pressed OK. - static func runPageSetup(_ printInfo: NSPrintInfo) -> Bool { - NSPageLayout().runModal(with: printInfo) == NSApplication.ModalResponse.OK.rawValue + /// Shows the standard Page Setup sheet. Returns true when the user pressed OK; the choice then also becomes + /// the starting point for new windows. + func runPageSetup() -> Bool { + guard NSPageLayout().runModal(with: printInfo) == NSApplication.ModalResponse.OK.rawValue else { return false } + if let chosen = printInfo.copy() as? NSPrintInfo { NSPrintInfo.shared = chosen } + return true } /// Prints a tile PDF exactly as laid out: no scaling, rotation or margins added. - static func printTiles(_ data: Data, title: String, printInfo: NSPrintInfo) { + func printTiles(_ data: Data, title: String) { guard let document = PDFDocument(data: data) else { return } guard let info = printInfo.copy() as? NSPrintInfo else { return } info.topMargin = 0 @@ -50,3 +53,10 @@ enum PrintSetup { } } } + +extension AppModel { + func runPageSetup() { + if printSetup.runPageSetup() { refreshPage() } + } +} +#endif diff --git a/Sources/MapsmithUI/PrinterSection.swift b/Sources/MapsmithUI/PrinterSection.swift new file mode 100644 index 0000000..bf9dde4 --- /dev/null +++ b/Sources/MapsmithUI/PrinterSection.swift @@ -0,0 +1,80 @@ +import MapsmithCore +import SwiftUI + +#if os(macOS) +import AppKit + +/// The inspector's printer and paper, from Page Setup. +struct PrinterSection: View { + @Environment(AppModel.self) private var model + + var body: some View { + Section("Printer") { + LabeledContent("Printer", value: model.printerName) + LabeledContent("Paper", value: model.paperName) + LabeledContent("Printable area", value: model.page.imageableSizeInches.inchesText) + Button("Page Setup…") { model.runPageSetup() } + } + } +} + +/// Settings' printer picker: every printer the Mac knows, starting with the current one. +struct InkPrinterChoice: View { + static var initialPrinter: String { NSPrintInfo.shared.printer.name } + + @Binding var printer: String + + var body: some View { + Picker("Printer", selection: $printer) { + ForEach(NSPrinter.printerNames, id: \.self) { Text($0).tag($0) } + } + } +} + +#else + +/// The inspector's paper and margin, which the iPad has instead of Page Setup, and the printer for ink prices. +struct PrinterSection: View { + @Environment(AppModel.self) private var model + + var body: some View { + @Bindable var setup = model.printSetup + Section { + Picker("Paper", selection: $setup.paper) { + ForEach(PaperChoice.allCases) { Text($0.title).tag($0) } + } + LabeledNumberField(title: "Margin (in)") { + TextField("Margin (in)", value: $setup.marginInches, format: .number.precision(.fractionLength(0...3))) + } + LabeledContent("Printable area", value: model.page.imageableSizeInches.inchesText) + LabeledContent("Printer", value: model.printerName.isEmpty ? "None chosen" : model.printerName) + Button("Choose Printer…") { setup.choosePrinter() } + } header: { + Text("Paper") + } footer: { + Text(""" + The margin is the border your printer can't print on; ¼ in suits most printers. The printer chosen \ + here is the one the ink prices are for. + """) + } + .onChange(of: setup.paper) { model.refreshPage() } + .onChange(of: setup.marginInches) { model.refreshPage() } + } +} + +/// The Ink Prices sheet's printer: the one chosen in the inspector. +struct InkPrinterChoice: View { + @MainActor static var initialPrinter: String { "" } + + @Binding var printer: String + @Environment(AppModel.self) private var model + + var body: some View { + Section { + LabeledContent("Printer", value: model.printerName.isEmpty ? "None chosen" : model.printerName) + Button("Choose Printer…") { model.printSetup.choosePrinter() } + } + .onChange(of: model.printerName, initial: true) { printer = model.printerName } + } +} +#endif diff --git a/Sources/Mapsmith/PrinterSupplies.swift b/Sources/MapsmithUI/PrinterSupplies.swift similarity index 98% rename from Sources/Mapsmith/PrinterSupplies.swift rename to Sources/MapsmithUI/PrinterSupplies.swift index 63c7ded..79f8d46 100644 --- a/Sources/Mapsmith/PrinterSupplies.swift +++ b/Sources/MapsmithUI/PrinterSupplies.swift @@ -1,3 +1,4 @@ +#if os(macOS) import CUPS import MapsmithCore @@ -25,3 +26,4 @@ enum PrinterSupplies { cupsGetOption(name, destination.num_options, destination.options).map { String(cString: $0) } ?? "" } } +#endif diff --git a/Sources/Mapsmith/ScrollkeeperWindow.swift b/Sources/MapsmithUI/ScrollkeeperBrowser.swift similarity index 80% rename from Sources/Mapsmith/ScrollkeeperWindow.swift rename to Sources/MapsmithUI/ScrollkeeperBrowser.swift index 23daaaa..ac238b1 100644 --- a/Sources/Mapsmith/ScrollkeeperWindow.swift +++ b/Sources/MapsmithUI/ScrollkeeperBrowser.swift @@ -1,13 +1,13 @@ -import AppKit +import ImageIO import MapsmithCore import SwiftUI -/// File ▸ Open from Scrollkeeper…: search the maps the user owns and ask Scrollkeeper for one. -struct ScrollkeeperWindow: View { - static let id = "scrollkeeper" - +/// Open from Scrollkeeper…: search the maps the user owns and open one, asking Scrollkeeper for it when needed. +/// The Mac shows it in a window of its own, the iPad in a sheet. +struct ScrollkeeperBrowser: View { let bridge: ScrollkeeperBridge - @Environment(\.dismissWindow) private var dismissWindow + /// Closes the window or sheet. + let close: () -> Void @Environment(\.openURL) private var openURL @State private var query = "" @State private var selection: ScrollkeeperIndex.Entry.ID? @@ -20,20 +20,16 @@ struct ScrollkeeperWindow: View { HStack { footnote Spacer() - Button("Cancel", role: .cancel) { dismissWindow(id: Self.id) } + Button("Cancel", role: .cancel, action: close) .keyboardShortcut(.cancelAction) - Button(selectedEntry?.downloaded == false ? "Download and Open" : "Open") { openSelection() } + Button(openTitle) { openSelection() } .keyboardShortcut(.defaultAction) .disabled(selectedEntry == nil) } } .padding(20) - .frame(width: 520, height: 460) .onAppear(perform: bridge.requestIndex) - // The list and status links Scrollkeeper sends arrive as open events. Taking them here keeps this - // window in front; otherwise SwiftUI hands them to a document window and brings that forward. - .handlesExternalEvents(preferring: ["*"], allowing: ["*"]) - .onChange(of: isOpening) { if isOpening { dismissWindow(id: Self.id) } } + .onChange(of: isOpening) { if isOpening { close() } } .task(id: bridge.state) { isSlow = false guard bridge.state == .waiting else { return } @@ -42,6 +38,12 @@ struct ScrollkeeperWindow: View { } } + /// Download and Open for a title not on disk, or where Scrollkeeper takes no requests, a way to it. + private var openTitle: String { + guard selectedEntry?.downloaded == false else { return "Open" } + return bridge.takesRequests ? "Download and Open" : "Download in Scrollkeeper" + } + private var loadedIndex: ScrollkeeperIndex? { if case let .loaded(index) = bridge.state { index } else { nil } } @@ -70,6 +72,11 @@ struct ScrollkeeperWindow: View { message: "Scrollkeeper downloads the maps you own on paizo.com.") { Button("Get Scrollkeeper") { openURL(ScrollkeeperBridge.downloadPage) } } + case .noSharedLibrary: + unavailable("No Maps from Scrollkeeper Yet", symbol: "books.vertical", + message: "Open Scrollkeeper and sign in to paizo.com; your maps then show up here.") { + Button("Open Scrollkeeper", action: bridge.launchScrollkeeper) + } case .unsupportedVersion: unavailable("Update Mapsmith", symbol: "arrow.down.circle", message: "Scrollkeeper's list of maps is newer than this version of Mapsmith understands.") { @@ -150,7 +157,9 @@ struct ScrollkeeperWindow: View { Button("Download", systemImage: "icloud.and.arrow.down") { bridge.download(entry) } .labelStyle(.iconOnly) .buttonStyle(.borderless) - .help("Not downloaded yet. Click to download it now, or choose Download and Open.") + .help(bridge.takesRequests + ? "Not downloaded yet. Click to download it now, or choose Download and Open." + : "Not downloaded yet. Click to download it in Scrollkeeper.") } private func unavailable(_ title: String, symbol: String, message: String, @@ -192,19 +201,19 @@ struct ScrollkeeperWindow: View { private func openSelection() { guard let entry = selectedEntry else { return } bridge.open(entry) - if entry.downloaded { dismissWindow(id: Self.id) } + if entry.downloaded { close() } } } /// A title's cover from Scrollkeeper's folder, or a map symbol when there is none, loaded off the main thread. private struct CoverThumbnail: View { let url: URL? - @State private var image: NSImage? + @State private var image: CGImage? var body: some View { Group { if let image { - Image(nsImage: image).resizable().scaledToFit() + Image(decorative: image, scale: 1).resizable().scaledToFit() } else { Image(systemName: "map").foregroundStyle(.secondary) } @@ -212,10 +221,14 @@ private struct CoverThumbnail: View { .frame(width: 28, height: 36) .task(id: url) { guard let url else { return } - let data = await Task.detached { try? Data(contentsOf: url) }.value - image = data.flatMap(NSImage.init(data:)) + image = await Task.detached { Self.loadImage(url) }.value } } + + private nonisolated static func loadImage(_ url: URL) -> CGImage? { + guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil } + return CGImageSourceCreateImageAtIndex(source, 0, nil) + } } extension ScrollkeeperRequest.Phase { @@ -223,21 +236,3 @@ extension ScrollkeeperRequest.Phase { if case .failed = self { true } else { false } } } - -/// The system side of `ApplicationLauncher`. -struct WorkspaceLauncher: ApplicationLauncher { - func isInstalled(_ bundleIdentifier: String) -> Bool { - NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) != nil - } - - func openInBackground(_ url: URL) { - let configuration = NSWorkspace.OpenConfiguration() - configuration.activates = false - NSWorkspace.shared.open(url, configuration: configuration) - } - - func launch(_ bundleIdentifier: String) { - guard let app = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) else { return } - NSWorkspace.shared.openApplication(at: app, configuration: .init()) - } -} diff --git a/Sources/MapsmithUI/ScrollkeeperWindow.swift b/Sources/MapsmithUI/ScrollkeeperWindow.swift new file mode 100644 index 0000000..20df727 --- /dev/null +++ b/Sources/MapsmithUI/ScrollkeeperWindow.swift @@ -0,0 +1,41 @@ +#if os(macOS) +import AppKit +import MapsmithCore +import SwiftUI + +/// File ▸ Open from Scrollkeeper…: the browser in a window of its own. +struct ScrollkeeperWindow: View { + static let id = "scrollkeeper" + + let bridge: ScrollkeeperBridge + @Environment(\.dismissWindow) private var dismissWindow + + var body: some View { + ScrollkeeperBrowser(bridge: bridge) { dismissWindow(id: Self.id) } + .frame(width: 520, height: 460) + // The list and status links Scrollkeeper sends arrive as open events. Taking them here keeps this + // window in front; otherwise SwiftUI hands them to a document window and brings that forward. + .handlesExternalEvents(preferring: ["*"], allowing: ["*"]) + } +} + +/// The system side of `ApplicationLauncher`. Scrollkeeper on the Mac answers requests. +struct WorkspaceLauncher: ApplicationLauncher { + var takesRequests: Bool { true } + + func isInstalled(_ bundleIdentifier: String) -> Bool { + NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) != nil + } + + func openInBackground(_ url: URL) { + let configuration = NSWorkspace.OpenConfiguration() + configuration.activates = false + NSWorkspace.shared.open(url, configuration: configuration) + } + + func launch(_ bundleIdentifier: String) { + guard let app = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier) else { return } + NSWorkspace.shared.openApplication(at: app, configuration: .init()) + } +} +#endif diff --git a/Sources/Mapsmith/SettingsInspector.swift b/Sources/MapsmithUI/SettingsInspector.swift similarity index 88% rename from Sources/Mapsmith/SettingsInspector.swift rename to Sources/MapsmithUI/SettingsInspector.swift index 2960540..5e21e5d 100644 --- a/Sources/Mapsmith/SettingsInspector.swift +++ b/Sources/MapsmithUI/SettingsInspector.swift @@ -8,12 +8,7 @@ struct SettingsInspector: View { var body: some View { @Bindable var model = model Form { - Section("Printer") { - LabeledContent("Printer", value: model.printerName) - LabeledContent("Paper", value: model.paperName) - LabeledContent("Printable area", value: inches(model.page.imageableSizeInches)) - Button("Page Setup…") { model.runPageSetup() } - } + PrinterSection() Section("Scale") { scaleDescription @@ -29,8 +24,10 @@ struct SettingsInspector: View { } Section("Edges") { - TextField("Skip strips under (in)", value: $model.minimumSliverInches, - format: .number.precision(.fractionLength(0...2))) + LabeledNumberField(title: "Skip strips under (in)") { + TextField("Skip strips under (in)", value: $model.minimumSliverInches, + format: .number.precision(.fractionLength(0...2))) + } Text("An edge row or column holding less map than this is trimmed instead of printed.") .font(.caption).foregroundStyle(.secondary) } @@ -107,7 +104,10 @@ struct SettingsInspector: View { "\(Int(size.width)) × \(Int(size.height)) px" } - private func inches(_ size: CGSize) -> String { - String(format: "%.2f × %.2f in", size.width, size.height) - } + private func inches(_ size: CGSize) -> String { size.inchesText } +} + +extension CGSize { + /// Width by height in inches, for a size given in inches. + var inchesText: String { String(format: "%.2f × %.2f in", width, height) } } diff --git a/Sources/Mapsmith/TilePreviewView.swift b/Sources/MapsmithUI/TilePreviewView.swift similarity index 100% rename from Sources/Mapsmith/TilePreviewView.swift rename to Sources/MapsmithUI/TilePreviewView.swift diff --git a/Sources/MapsmithUI/TilePrinter.swift b/Sources/MapsmithUI/TilePrinter.swift new file mode 100644 index 0000000..8ad7cca --- /dev/null +++ b/Sources/MapsmithUI/TilePrinter.swift @@ -0,0 +1,68 @@ +#if os(iOS) +import UIKit + +/// Prints a tile PDF on the iPad exactly as laid out. Handing the PDF to the print panel as a printing item would +/// scale each page to the printer's printable area; this draws every page at the paper's origin at 100% instead, +/// and asks the printer for the paper the tiles were planned for. +@MainActor +enum TilePrinter { + static func print(_ data: Data, title: String, paperSize: CGSize, printerURL: URL?) { + guard let provider = CGDataProvider(data: data as CFData), let document = CGPDFDocument(provider) else { + return + } + let info = UIPrintInfo.printInfo() + info.jobName = title + info.outputType = .general + info.orientation = .portrait + info.printerID = printerURL?.absoluteString + + let controller = UIPrintInteractionController.shared + let delegate = PaperChooser(paperSize: paperSize) + controller.printInfo = info + controller.printPageRenderer = ActualSizeRenderer(document: document) + controller.delegate = delegate + controller.present(animated: true) { _, _, _ in + // The controller holds its delegate weakly; this keeps it until the print panel is done. + withExtendedLifetime(delegate) {} + } + } +} + +/// Asks the printer for the paper the tiles were planned for, or the closest it has. +private final class PaperChooser: NSObject, UIPrintInteractionControllerDelegate { + let paperSize: CGSize + + init(paperSize: CGSize) { + self.paperSize = paperSize + } + + func printInteractionController(_ controller: UIPrintInteractionController, + choosePaper paperList: [UIPrintPaper]) -> UIPrintPaper { + UIPrintPaper.bestPaper(forPageSize: paperSize, withPapersFrom: paperList) + } +} + +/// Draws each page of the PDF at the paper's top-left corner, one PDF point to one printed point. +private final class ActualSizeRenderer: UIPrintPageRenderer { + private let document: CGPDFDocument + + init(document: CGPDFDocument) { + self.document = document + } + + override var numberOfPages: Int { document.numberOfPages } + + override func drawPage(at pageIndex: Int, in printableRect: CGRect) { + guard let page = document.page(at: pageIndex + 1), let context = UIGraphicsGetCurrentContext() else { return } + let box = page.getBoxRect(.mediaBox) + context.saveGState() + // The context is in paper coordinates with the origin at the top left; PDF pages have theirs at the + // bottom left. + context.translateBy(x: paperRect.minX, y: paperRect.minY + box.height) + context.scaleBy(x: 1, y: -1) + context.translateBy(x: -box.minX, y: -box.minY) + context.drawPDFPage(page) + context.restoreGState() + } +} +#endif diff --git a/Sources/MapsmithUI/TilesPDF.swift b/Sources/MapsmithUI/TilesPDF.swift new file mode 100644 index 0000000..640467e --- /dev/null +++ b/Sources/MapsmithUI/TilesPDF.swift @@ -0,0 +1,26 @@ +import SwiftUI +import UniformTypeIdentifiers + +/// Rendered tiles, for the file exporter. +struct TilesPDF: FileDocument { + static let readableContentTypes: [UTType] = [.pdf] + + let data: Data + /// The suggested file name, without the extension. + let name: String + + init(data: Data, name: String) { + self.data = data + self.name = name + } + + init(configuration: ReadConfiguration) throws { + guard let data = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) } + self.data = data + name = configuration.file.filename ?? "Tiles" + } + + func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { + FileWrapper(regularFileWithContents: data) + } +} diff --git a/Sources/MapsmithUI/UITestSample.swift b/Sources/MapsmithUI/UITestSample.swift new file mode 100644 index 0000000..e5502df --- /dev/null +++ b/Sources/MapsmithUI/UITestSample.swift @@ -0,0 +1,49 @@ +#if DEBUG && os(iOS) +import CoreGraphics +import Foundation +import ImageIO +import UniformTypeIdentifiers + +/// A gridded map the UI tests open (launch argument `-UITestSample`), since the sample maps are copyrighted and the +/// tests can't hand the app a file. +enum UITestSample { + static let argument = "-UITestSample" + static let squarePixels = 100 + + static func urlIfRequested() -> URL? { + guard ProcessInfo.processInfo.arguments.contains(argument) else { return nil } + let url = FileManager.default.temporaryDirectory.appending(path: "UI Test Map.png") + guard let image = drawGrid(columns: 30, rows: 20), write(image, to: url) else { return nil } + return url + } + + private static func drawGrid(columns: Int, rows: Int) -> CGImage? { + let width = columns * squarePixels, height = rows * squarePixels + guard let space = CGColorSpace(name: CGColorSpace.sRGB), + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, + space: space, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) + else { return nil } + context.setFillColor(CGColor(srgbRed: 0.93, green: 0.88, blue: 0.76, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + context.setStrokeColor(CGColor(gray: 0.2, alpha: 1)) + context.setLineWidth(3) + for column in 0...columns { + context.move(to: CGPoint(x: column * squarePixels, y: 0)) + context.addLine(to: CGPoint(x: column * squarePixels, y: height)) + } + for row in 0...rows { + context.move(to: CGPoint(x: 0, y: row * squarePixels)) + context.addLine(to: CGPoint(x: width, y: row * squarePixels)) + } + context.strokePath() + return context.makeImage() + } + + private static func write(_ image: CGImage, to url: URL) -> Bool { + guard let destination = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, + nil) else { return false } + CGImageDestinationAddImage(destination, image, nil) + return CGImageDestinationFinalize(destination) + } +} +#endif diff --git a/Tests/MapsmithCoreTests/DroppedImageStoreTests.swift b/Tests/MapsmithCoreTests/DroppedImageStoreTests.swift index 9c6b236..f7987ee 100644 --- a/Tests/MapsmithCoreTests/DroppedImageStoreTests.swift +++ b/Tests/MapsmithCoreTests/DroppedImageStoreTests.swift @@ -22,6 +22,19 @@ import UniformTypeIdentifiers #expect(names == ["Dropped Map.tiff", "Dropped Map 2.tiff", "Dropped Map 3.tiff"]) } + @Test func copiesADroppedFileWithoutReplacingAnother() throws { + let original = FileManager.default.temporaryDirectory.appendingPathComponent("drop-\(UUID().uuidString).pdf") + try data.write(to: original) + defer { try? FileManager.default.removeItem(at: original) } + + let first = try store.saveCopy(of: original, suggestedName: "Forest.pdf", type: .pdf) + let second = try store.saveCopy(of: original, suggestedName: "Forest.pdf", type: .pdf) + + #expect([first, second].map(\.lastPathComponent) == ["Forest.pdf", "Forest 2.pdf"]) + #expect(try Data(contentsOf: second) == data) + #expect(FileManager.default.fileExists(atPath: original.path)) + } + @Test func keepsDropsInTheCachesFolder() { let path = DroppedImageStore.standard.directory.path #expect(path.contains("/Caches/") && path.hasSuffix("/Dropped Maps")) diff --git a/Tests/MapsmithCoreTests/PaperChoiceTests.swift b/Tests/MapsmithCoreTests/PaperChoiceTests.swift new file mode 100644 index 0000000..c25481f --- /dev/null +++ b/Tests/MapsmithCoreTests/PaperChoiceTests.swift @@ -0,0 +1,32 @@ +import CoreGraphics +import Testing +@testable import MapsmithCore + +@Suite struct PaperChoiceTests { + @Test func insetsThePaperByTheMargin() { + let page = PaperChoice.letter.geometry(marginInches: 0.25) + #expect(page.paperSize == CGSize(width: 612, height: 792)) + #expect(page.imageableRect == CGRect(x: 18, y: 18, width: 576, height: 756)) + #expect(page.imageableSizeInches == CGSize(width: 8, height: 10.5)) + } + + @Test func keepsTheMarginInRange() { + #expect(PaperChoice.a4.geometry(marginInches: -1).imageableRect.minX == 0) + #expect(PaperChoice.a4.geometry(marginInches: 9).imageableRect.minX == 2 * pointsPerInch) + } + + @Test func everyPaperIsPortraitAndNamed() { + for paper in PaperChoice.allCases { + #expect(paper.size.height > paper.size.width) + #expect(!paper.title.isEmpty) + #expect(paper.id == paper.rawValue) + } + } + + @Test func picksLetterOrA4ByRegion() { + #expect(PaperChoice.regionalDefault(regionCode: "US") == .letter) + #expect(PaperChoice.regionalDefault(regionCode: "CA") == .letter) + #expect(PaperChoice.regionalDefault(regionCode: "DE") == .a4) + #expect(PaperChoice.regionalDefault(regionCode: nil) == .a4) + } +} diff --git a/Tests/MapsmithCoreTests/ScrollkeeperBridgeTests.swift b/Tests/MapsmithCoreTests/ScrollkeeperBridgeTests.swift index cfded29..cd9faaa 100644 --- a/Tests/MapsmithCoreTests/ScrollkeeperBridgeTests.swift +++ b/Tests/MapsmithCoreTests/ScrollkeeperBridgeTests.swift @@ -6,6 +6,7 @@ import Testing @MainActor final class FakeLauncher: ApplicationLauncher { var installed = true + var takesRequests = true private(set) var backgroundURLs: [URL] = [] private(set) var launched: [String] = [] diff --git a/Tests/MapsmithCoreTests/ScrollkeeperSharedLibraryOnlyTests.swift b/Tests/MapsmithCoreTests/ScrollkeeperSharedLibraryOnlyTests.swift new file mode 100644 index 0000000..73d063d --- /dev/null +++ b/Tests/MapsmithCoreTests/ScrollkeeperSharedLibraryOnlyTests.swift @@ -0,0 +1,64 @@ +import Foundation +import Testing +@testable import MapsmithCore + +/// The bridge where Scrollkeeper takes no requests, as on the iPad: only the shared library is read. +@MainActor @Suite struct ScrollkeeperSharedLibraryOnlyTests { + let launcher: FakeLauncher = { + let launcher = FakeLauncher() + launcher.takesRequests = false + return launcher + }() + let folder = FakeScrollkeeperFolder() + + @Test func saysThereIsNoSharedLibraryInsteadOfAsking() { + let bridge = ScrollkeeperBridge(launcher: launcher, libraryFolder: folder.url) + bridge.requestIndex() + #expect(bridge.state == .noSharedLibrary) + #expect(launcher.backgroundURLs.isEmpty) + #expect(!bridge.takesRequests) + } + + @Test func readsTheLibraryOnceScrollkeeperSharesIt() throws { + let bridge = ScrollkeeperBridge(launcher: launcher, libraryFolder: folder.url) + bridge.requestIndex() + try folder.writeLibrary(titles: [FakeScrollkeeperFolder.title("MAP1")]) + + bridge.refreshLibrary() + + guard case let .loaded(index) = bridge.state else { throw ScrollkeeperLibraryTestError.notLoaded } + #expect(index.titles.map(\.sku) == ["MAP1"]) + } + + @Test func bringsScrollkeeperForwardForATitleNotDownloaded() { + let bridge = ScrollkeeperBridge(launcher: launcher, libraryFolder: folder.url) + let entry = ScrollkeeperIndex.Entry(sku: "PZO1", title: "Forest", downloaded: false) + + bridge.open(entry) + bridge.download(entry) + + #expect(launcher.launched == [ScrollkeeperBridge.bundleIdentifier, ScrollkeeperBridge.bundleIdentifier]) + #expect(launcher.backgroundURLs.isEmpty) + #expect(bridge.request(for: entry) == nil) + } + + @Test func opensADownloadedTitleFromTheSharedFolder() { + let bridge = ScrollkeeperBridge(launcher: launcher, libraryFolder: folder.url) + var opened: [URL] = [] + bridge.openDocuments = { opened = $0 } + var entry = ScrollkeeperIndex.Entry(sku: "PZO1", title: "Forest") + entry.localFiles = [URL(filePath: "/shared/forest.pdf")] + + bridge.open(entry) + + #expect(opened == [URL(filePath: "/shared/forest.pdf")]) + #expect(launcher.launched.isEmpty) + } + + @Test func leavesAnInstalledCheckFirst() { + launcher.installed = false + let bridge = ScrollkeeperBridge(launcher: launcher, libraryFolder: folder.url) + bridge.requestIndex() + #expect(bridge.state == .notInstalled) + } +} diff --git a/docs/specs/ipad-app/design.md b/docs/specs/ipad-app/design.md new file mode 100644 index 0000000..5bdf570 --- /dev/null +++ b/docs/specs/ipad-app/design.md @@ -0,0 +1,62 @@ +# iPad app: design + +## Targets +- `MapsmithUI` (library) holds the SwiftUI app shared by both platforms: + `MapsmithApp`, the views and `AppModel`. Platform code sits behind + `#if os(macOS)` / `#if os(iOS)`, mostly in files of its own. +- `Mapsmith` (Mac executable) is `main.swift` calling `MapsmithApp.main()`, so + `scripts/build-app.sh` and the release keep building `Mapsmith`. +- `ios/Mapsmith.xcodeproj` (scheme `Mapsmith-iPad`) is the iPad and iPhone app. + Its only source is `ios/App/MapsmithMain.swift`; it links `MapsmithUI` from + the local package. Signing, version and the App Group entitlement follow + Field Guide's `ios/` folder. +- `MapsmithCore` stays platform-neutral (CoreGraphics, ImageIO). + +## Scenes +- Mac: unchanged (`WindowGroup(for: URL.self)`, Open from Scrollkeeper window, + Settings scene). +- iOS: one `WindowGroup` whose `PadRootView` owns an `AppModel`. `onOpenURL` + and the file importer call `AppModel.open`, which replaces the shown file + (R1.5). Open from Scrollkeeper and Ink Prices are sheets. + +## Files the app may only read in place +`AppModel.open` starts security-scoped access to the URL and stops it for the +previous file. The PDF is read again for every render, so access lasts while +the file is shown. On the Mac `startAccessingSecurityScopedResource` returns +false for ordinary URLs and nothing changes. + +## Printing (`PrintSetup`) +One type per platform with the same surface: `page`, `printerName`, +`paperName`. +- Mac: wraps `NSPrintInfo` as before. +- iOS: `PadPrintSetup` keeps a `PaperChoice` (named size) and a margin in + `UserDefaults`; `page` is the paper inset by the margin. `TilePrinter` uses + `UIPrintInteractionController` with a `UIPrintPageRenderer` that draws each + tile-PDF page at the paper's origin with no scaling (printing a PDF as + `printingItem` would scale it to the printable area). Its delegate's + `choosePaper` picks `UIPrintPaper.bestPaper(forPageSize:withPapersFrom:)` for + the chosen size. +- The printer for ink prices comes from `UIPrinterPickerController` and is + remembered by display name, which keys `InkPriceBook` as the Mac's printer + name does. + +## Export +Both platforms render the tiles first and then present `.fileExporter` with a +`TilesPDF` (`FileDocument`). On the Mac this replaces the modal `NSSavePanel` +with the same save panel as a window sheet. + +## Scrollkeeper on iOS +`ApplicationLauncher` gains `takesRequests`. The Mac launcher says yes; the +iOS one (`PadLauncher`) says no, checks for Scrollkeeper with +`canOpenURL("scrollkeeper://")` (listed in `LSApplicationQueriesSchemes`) and +opens it with `UIApplication.open`. When the launcher takes no requests, +`ScrollkeeperBridge.requestIndex` goes to `.noSharedLibrary` instead of asking, +and the browser shows Open Scrollkeeper for titles not downloaded (R2.3). +The browser view (`ScrollkeeperBrowser`) is shared; the Mac wraps it in its +window, the iPad in a sheet. Covers load through ImageIO as `CGImage`. + +## Testing +- Unit tests in `MapsmithCoreTests` cover the bridge's iOS behavior and the + paper geometry (`PaperChoice` lives in `MapsmithCore`). +- `ios/UITests` opens the app in both orientations on an iPad simulator and + screenshots the empty window and the inspector. diff --git a/docs/specs/ipad-app/requirements.md b/docs/specs/ipad-app/requirements.md new file mode 100644 index 0000000..fb61f4c --- /dev/null +++ b/docs/specs/ipad-app/requirements.md @@ -0,0 +1,51 @@ +# iPad app: requirements + +Mapsmith also runs on the iPad (and the iPhone, which gets the same layout in a +compact width). It prints the same true-scale tiles as the Mac app: one grid +square per inch, ready to trim and tape together. + +## R1 Opening a map +- R1.1 With no map open, the window offers Open… and Open from Scrollkeeper…, + as on the Mac. +- R1.2 Open… shows the system file browser for PDFs and images. The file is + read in place; it is not copied into Mapsmith. +- R1.3 A PDF or image shared to Mapsmith from Files or another app ("Open in + Mapsmith") opens in the window, replacing the map shown. +- R1.4 A PDF or image dropped on the window opens, as on the Mac. +- R1.5 The iPad shows one map at a time; opening another replaces it. + +## R2 Open from Scrollkeeper +- R2.1 Open from Scrollkeeper… lists the maps the user owns from + Scrollkeeper's library in the Tableside Toolkit's App Group, with covers and + the same search as on the Mac. +- R2.2 A map Scrollkeeper has downloaded opens straight from the shared folder. +- R2.3 Scrollkeeper on the iPad takes no requests from other apps, so a map + not downloaded yet has an Open Scrollkeeper button instead of a download + button; once Scrollkeeper has downloaded it, it opens in Mapsmith. +- R2.4 The list is read again when Mapsmith comes back to the foreground and + when Scrollkeeper says its library changed. +- R2.5 When there is no shared library (Scrollkeeper isn't installed or hasn't + loaded the library yet), the sheet says so and offers to open Scrollkeeper, + or to get it when it isn't installed. + +## R3 Paper and printing +- R3.1 The iPad has no Page Setup. The inspector has a paper picker (US + Letter, US Legal, A4, A3, Tabloid) and a margin, the printer's unprintable + border, defaulting to 1/4 in, which fits most AirPrint printers. Both are + remembered. +- R3.2 Tiles are planned for the chosen paper's printable area, as on the Mac. +- R3.3 Print shows the system print panel and prints every page at 100% + scale: the page is never scaled to fit the printer's printable area, and the + printer is asked for the chosen paper size. +- R3.4 Export saves the tiles as a PDF through the system file browser. + +## R4 Ink cost +- R4.1 The printer the ink prices belong to is chosen with the system printer + picker and remembered. +- R4.2 Ink Prices… (toolbar) shows the same cartridge settings as the Mac's + Settings, starting from cyan, magenta, yellow and black, since AirPrint + doesn't list a printer's supplies. + +## R5 Layout +- R5.1 The map list, preview and inspector fit in landscape and portrait. +- R5.2 The Mac app keeps working as before. diff --git a/ios/App/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/App/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..27a4f38 --- /dev/null +++ b/ios/App/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images" : [ + { + "filename" : "icon-1024.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ios/App/Assets.xcassets/AppIcon.appiconset/icon-1024.png b/ios/App/Assets.xcassets/AppIcon.appiconset/icon-1024.png new file mode 100644 index 0000000..a388a7b Binary files /dev/null and b/ios/App/Assets.xcassets/AppIcon.appiconset/icon-1024.png differ diff --git a/ios/App/Assets.xcassets/Contents.json b/ios/App/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/ios/App/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ios/App/MapsmithMain.swift b/ios/App/MapsmithMain.swift new file mode 100644 index 0000000..477a490 --- /dev/null +++ b/ios/App/MapsmithMain.swift @@ -0,0 +1,9 @@ +import MapsmithUI + +/// The iPad entry point. The app itself lives in the MapsmithUI package target, shared with the Mac. +@main +enum MapsmithMain { + static func main() { + MapsmithApp.main() + } +} diff --git a/ios/App/PrivacyInfo.xcprivacy b/ios/App/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..6a40946 --- /dev/null +++ b/ios/App/PrivacyInfo.xcprivacy @@ -0,0 +1,28 @@ + + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/ios/Info.plist b/ios/Info.plist new file mode 100644 index 0000000..99b39eb --- /dev/null +++ b/ios/Info.plist @@ -0,0 +1,42 @@ + + + + + + + CFBundleDocumentTypes + + + CFBundleTypeName + PDF Map + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + LSItemContentTypes + + com.adobe.pdf + + + + CFBundleTypeName + Map Image + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + LSItemContentTypes + + public.image + + + + LSSupportsOpeningDocumentsInPlace + + + LSApplicationQueriesSchemes + + scrollkeeper + + + diff --git a/ios/Mapsmith.entitlements b/ios/Mapsmith.entitlements new file mode 100644 index 0000000..b7429bc --- /dev/null +++ b/ios/Mapsmith.entitlements @@ -0,0 +1,12 @@ + + + + + + com.apple.security.application-groups + + group.io.github.scooper4711.tableside + + + diff --git a/ios/Mapsmith.xcodeproj/project.pbxproj b/ios/Mapsmith.xcodeproj/project.pbxproj new file mode 100644 index 0000000..79c9ebf --- /dev/null +++ b/ios/Mapsmith.xcodeproj/project.pbxproj @@ -0,0 +1,391 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + A1000000000000000000000A /* MapsmithUI in Frameworks */ = {isa = PBXBuildFile; productRef = A1000000000000000000000B /* MapsmithUI */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + A10000000000000000000001 /* Mapsmith.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Mapsmith.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + A10000000000000000000015 /* Signing.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Signing.xcconfig; sourceTree = ""; }; + A20000000000000000000001 /* MapsmithUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MapsmithUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXContainerItemProxy section */ + A20000000000000000000002 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A10000000000000000000009 /* Project object */; + proxyType = 1; + remoteGlobalIDString = A10000000000000000000006; + remoteInfo = "Mapsmith-iPad"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXTargetDependency section */ + A20000000000000000000003 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A10000000000000000000006 /* Mapsmith-iPad */; + targetProxy = A20000000000000000000002 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + A10000000000000000000002 /* App */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = App; + sourceTree = ""; + }; + A20000000000000000000004 /* UITests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = UITests; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + A10000000000000000000003 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A1000000000000000000000A /* MapsmithUI in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A20000000000000000000005 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + A10000000000000000000004 = { + isa = PBXGroup; + children = ( + A10000000000000000000002 /* App */, + A20000000000000000000004 /* UITests */, + A10000000000000000000015 /* Signing.xcconfig */, + A10000000000000000000005 /* Products */, + ); + sourceTree = ""; + }; + A10000000000000000000005 /* Products */ = { + isa = PBXGroup; + children = ( + A10000000000000000000001 /* Mapsmith.app */, + A20000000000000000000001 /* MapsmithUITests.xctest */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + A10000000000000000000006 /* Mapsmith-iPad */ = { + isa = PBXNativeTarget; + buildConfigurationList = A10000000000000000000010 /* Build configuration list for PBXNativeTarget "Mapsmith-iPad" */; + buildPhases = ( + A10000000000000000000007 /* Sources */, + A10000000000000000000003 /* Frameworks */, + A10000000000000000000008 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + A10000000000000000000002 /* App */, + ); + name = "Mapsmith-iPad"; + packageProductDependencies = ( + A1000000000000000000000B /* MapsmithUI */, + ); + productName = "Mapsmith-iPad"; + productReference = A10000000000000000000001 /* Mapsmith.app */; + productType = "com.apple.product-type.application"; + }; + A20000000000000000000006 /* MapsmithUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A2000000000000000000000A /* Build configuration list for PBXNativeTarget "MapsmithUITests" */; + buildPhases = ( + A20000000000000000000007 /* Sources */, + A20000000000000000000005 /* Frameworks */, + A20000000000000000000008 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + A20000000000000000000003 /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A20000000000000000000004 /* UITests */, + ); + name = MapsmithUITests; + productName = MapsmithUITests; + productReference = A20000000000000000000001 /* MapsmithUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A10000000000000000000009 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2600; + LastUpgradeCheck = 2600; + TargetAttributes = { + A10000000000000000000006 = { + CreatedOnToolsVersion = 26.0; + }; + A20000000000000000000006 = { + CreatedOnToolsVersion = 26.0; + TestTargetID = A10000000000000000000006; + }; + }; + }; + buildConfigurationList = A1000000000000000000000F /* Build configuration list for PBXProject "Mapsmith" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = A10000000000000000000004; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + A1000000000000000000000C /* XCLocalSwiftPackageReference ".." */, + ); + preferredProjectObjectVersion = 77; + productRefGroup = A10000000000000000000005 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A10000000000000000000006 /* Mapsmith-iPad */, + A20000000000000000000006 /* MapsmithUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + A10000000000000000000008 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A20000000000000000000008 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + A10000000000000000000007 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A20000000000000000000007 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + A10000000000000000000011 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_MODULES = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_OPTIMIZATION_LEVEL = 0; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + A10000000000000000000012 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_MODULES = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + A10000000000000000000013 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A10000000000000000000015 /* Signing.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + CODE_SIGN_ENTITLEMENTS = Mapsmith.entitlements; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Mapsmith; + INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; + INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2026 Stephen Cooper"; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_NAME = "Mapsmith"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + A10000000000000000000014 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A10000000000000000000015 /* Signing.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + CODE_SIGN_ENTITLEMENTS = Mapsmith.entitlements; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Mapsmith; + INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; + INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2026 Stephen Cooper"; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_NAME = "Mapsmith"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + A2000000000000000000000B /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A10000000000000000000015 /* Signing.xcconfig */; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = io.github.scooper4711.MapsmithUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = "Mapsmith-iPad"; + }; + name = Debug; + }; + A2000000000000000000000C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A10000000000000000000015 /* Signing.xcconfig */; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = io.github.scooper4711.MapsmithUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = "Mapsmith-iPad"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A1000000000000000000000F /* Build configuration list for PBXProject "Mapsmith" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A10000000000000000000011 /* Debug */, + A10000000000000000000012 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A10000000000000000000010 /* Build configuration list for PBXNativeTarget "Mapsmith-iPad" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A10000000000000000000013 /* Debug */, + A10000000000000000000014 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A2000000000000000000000A /* Build configuration list for PBXNativeTarget "MapsmithUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A2000000000000000000000B /* Debug */, + A2000000000000000000000C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + A1000000000000000000000C /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + A1000000000000000000000B /* MapsmithUI */ = { + isa = XCSwiftPackageProductDependency; + productName = MapsmithUI; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = A10000000000000000000009 /* Project object */; +} diff --git a/ios/Mapsmith.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ios/Mapsmith.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..81d5c6b --- /dev/null +++ b/ios/Mapsmith.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,15 @@ +{ + "originHash" : "a97c42a735ae795846f36e8dbfc77fb6a83baa57bde47663dc3222726314622a", + "pins" : [ + { + "identity" : "tabletop-kit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/scooper4711/tabletop-kit.git", + "state" : { + "revision" : "5a904d82a72311f64fc0e3be7666a02aae7ca553", + "version" : "1.0.0" + } + } + ], + "version" : 3 +} diff --git a/ios/Mapsmith.xcodeproj/xcshareddata/xcschemes/Mapsmith-iPad.xcscheme b/ios/Mapsmith.xcodeproj/xcshareddata/xcschemes/Mapsmith-iPad.xcscheme new file mode 100644 index 0000000..43c4221 --- /dev/null +++ b/ios/Mapsmith.xcodeproj/xcshareddata/xcschemes/Mapsmith-iPad.xcscheme @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Signing.xcconfig b/ios/Signing.xcconfig new file mode 100644 index 0000000..a5221e4 --- /dev/null +++ b/ios/Signing.xcconfig @@ -0,0 +1,22 @@ +// Signing and version settings for the iPad app. +// +// The team is the individual Apple Developer Program team that publishes Mapsmith, so archives build +// anywhere, CI included. To build with your own team, put it in Local.xcconfig next to this file, which is not +// committed: +// +// DEVELOPMENT_TEAM = ABCDE12345 +// +// If Xcode reports that the bundle identifier is taken, set your own there as well: +// +// PRODUCT_BUNDLE_IDENTIFIER = com.example.Mapsmith +DEVELOPMENT_TEAM = 9SWRBY8HN9 +PRODUCT_BUNDLE_IDENTIFIER = io.github.scooper4711.Mapsmith + +// The version and build number come from git (scripts/version.sh): the Mapsmith-iPad scheme's build pre-action +// writes them to Version.xcconfig before every build, Product > Archive included. These are the fallbacks for a +// build that skips the scheme. +MARKETING_VERSION = 0.0.0 +CURRENT_PROJECT_VERSION = 1 +#include? "Version.xcconfig" + +#include? "Local.xcconfig" diff --git a/ios/UITests/LayoutUITests.swift b/ios/UITests/LayoutUITests.swift new file mode 100644 index 0000000..ad21233 --- /dev/null +++ b/ios/UITests/LayoutUITests.swift @@ -0,0 +1,81 @@ +import XCTest + +/// The window in both orientations, empty and with a map: what a user sees first, and the map with its pages and +/// the inspector. Each test keeps a screenshot in the test results. +final class LayoutUITests: XCTestCase { + private var app: XCUIApplication! + + override func setUpWithError() throws { + continueAfterFailure = false + app = XCUIApplication() + } + + override func tearDown() { + XCUIDevice.shared.orientation = .portrait + super.tearDown() + } + + func testEmptyWindowInLandscape() { + showEmptyWindow(.landscapeLeft) + } + + func testEmptyWindowInPortrait() { + showEmptyWindow(.portrait) + } + + func testMapAndInspectorInLandscape() { + showMap(.landscapeLeft) + } + + func testMapAndInspectorInPortrait() { + showMap(.portrait) + } + + func testOpenFromScrollkeeperSaysWhereTheMapsComeFrom() { + launch(.landscapeLeft) + app.buttons["Open from Scrollkeeper…"].tap() + // Unsigned in the simulator, the app has no App Group, so there is no library to show. + let notice = app.staticTexts["Scrollkeeper Isn't Installed"] + XCTAssertTrue(notice.waitForExistence(timeout: 10), app.debugDescription) + keepScreenshot("Open from Scrollkeeper") + } + + private func showEmptyWindow(_ orientation: UIDeviceOrientation) { + launch(orientation) + XCTAssertTrue(app.buttons["Open…"].waitForExistence(timeout: 10), app.debugDescription) + XCTAssertTrue(app.buttons["Open…"].isHittable) + XCTAssertTrue(app.buttons["Open from Scrollkeeper…"].isHittable) + keepScreenshot("Empty window, \(orientation == .portrait ? "portrait" : "landscape")") + } + + private func showMap(_ orientation: UIDeviceOrientation) { + launch(orientation, arguments: ["-UITestSample"]) + // The sample's 100 px squares are found, and the inspector shows the paper and the page count. + let detected = app.staticTexts["Grid detected: 100.0 px per square"] + XCTAssertTrue(detected.waitForExistence(timeout: 20), app.debugDescription) + XCTAssertTrue(app.buttons["Paper"].exists || app.staticTexts["Paper"].exists, app.debugDescription) + XCTAssertTrue(app.staticTexts["Margin (in)"].exists, app.debugDescription) + for action in ["Open", "Export PDF", "Print", "Ink Prices"] { + XCTAssertTrue(app.buttons[action].isHittable, "No \(action) button in the toolbar") + } + // Every page is on screen, none under the inspector. + let lastPage = app.staticTexts["8"] + XCTAssertTrue(lastPage.exists && lastPage.isHittable, app.debugDescription) + keepScreenshot("Map and inspector, \(orientation == .portrait ? "portrait" : "landscape")") + } + + private func launch(_ orientation: UIDeviceOrientation, arguments: [String] = []) { + XCUIDevice.shared.orientation = orientation + app.launchArguments = arguments + app.launch() + } + + private func keepScreenshot(_ name: String) { + // Let a rotation finish first. The screen's screenshot, unlike the app's, isn't cropped to portrait. + Thread.sleep(forTimeInterval: 1) + let attachment = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 4ee65d2..b70d49f 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -34,7 +34,7 @@ cp "$BINARY" "$APP/Contents/MacOS/$EXECUTABLE" cp Resources/Info.plist "$APP/Contents/Info.plist" cp Resources/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns" cp Resources/container-migration.plist "$APP/Contents/Resources/container-migration.plist" -cp Resources/PrivacyInfo.xcprivacy "$APP/Contents/Resources/PrivacyInfo.xcprivacy" +cp ios/App/PrivacyInfo.xcprivacy "$APP/Contents/Resources/PrivacyInfo.xcprivacy" /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $VERSION" \ -c "Set :CFBundleVersion ${BUILD_NUMBER:-$VERSION}" "$APP/Contents/Info.plist" # The entitlements turn on the App Sandbox. A build signed with the team's Developer ID also joins the Tableside diff --git a/scripts/install-ipad.sh b/scripts/install-ipad.sh new file mode 100755 index 0000000..32d3a5f --- /dev/null +++ b/scripts/install-ipad.sh @@ -0,0 +1,67 @@ +#!/bin/sh +# Builds the iPad app, installs it on a connected iPad and starts it. +# +# The iPad must be connected by cable or on the same network, unlocked, with Developer Mode on. +# Your Apple developer team goes in ios/Local.xcconfig (see ios/Signing.xcconfig). +# +# IPAD name of the iPad to install on (default: the first connected iPad) +# IPAD_LAUNCH "no" to leave the app closed after installing, as a scheduled reinstall does +set -eu + +cd "$(dirname "$0")/.." + +DEVICES="$(mktemp)" +BUILD_LOG="$(mktemp)" +trap 'rm -f "$DEVICES" "$BUILD_LOG"' EXIT +xcrun devicectl list devices --json-output "$DEVICES" >/dev/null + +IPAD="${IPAD:-$(/usr/bin/python3 - "$DEVICES" <<'PYTHON' +import json +import sys + +devices = json.load(open(sys.argv[1]))["result"]["devices"] +ipads = [ + device["deviceProperties"]["name"] for device in devices + if device.get("hardwareProperties", {}).get("deviceType") == "iPad" + and device.get("connectionProperties", {}).get("tunnelState") != "unavailable" +] +print(ipads[0] if ipads else "") +PYTHON +)}" +[ -n "$IPAD" ] || { echo "Installing failed: no iPad is connected." >&2; exit 1; } + +BUNDLE_ID="$(xcodebuild -project ios/Mapsmith.xcodeproj -scheme Mapsmith-iPad \ + -showBuildSettings 2>/dev/null | sed -n 's/^ *PRODUCT_BUNDLE_IDENTIFIER = //p' | head -n 1)" + +echo "Building for ${IPAD}..." +# A failed build must stop here: the app left by an earlier build would install with its old signature. +if ! xcodebuild -project ios/Mapsmith.xcodeproj -scheme Mapsmith-iPad \ + -destination 'generic/platform=iOS' -derivedDataPath ios/build -allowProvisioningUpdates build \ + >"$BUILD_LOG" 2>&1; then + grep -E 'error:' "$BUILD_LOG" >&2 || tail -n 20 "$BUILD_LOG" >&2 + echo "Installing failed: the build failed." >&2 + exit 1 +fi +grep -E 'warning: .*[Pp]rovision|BUILD' "$BUILD_LOG" || true + +APP="ios/build/Build/Products/Debug-iphoneos/Mapsmith.app" +[ -d "$APP" ] || { echo "Installing failed: the build did not produce the app." >&2; exit 1; } + +xcrun devicectl device install app --device "$IPAD" "$APP" >/dev/null +echo "Installed on $IPAD." +[ "${IPAD_LAUNCH:-yes}" = no ] && exit 0 + +if LAUNCH="$(xcrun devicectl device process launch --device "$IPAD" "$BUNDLE_ID" 2>&1)"; then + echo "Started the app." +elif echo "$LAUNCH" | grep -q "not been explicitly trusted"; then + cat >&2 <<'MESSAGE' +Starting the app failed: the iPad does not trust your developer profile yet. +On the iPad open Settings > General > VPN & Device Management, tap your Apple ID +under Developer App and tap Trust. Then open the app from the Home Screen. +MESSAGE + exit 1 +else + echo "Starting the app failed:" >&2 + echo "$LAUNCH" | tail -n 5 >&2 + exit 1 +fi diff --git a/scripts/ipad-simulator-id.sh b/scripts/ipad-simulator-id.sh new file mode 100755 index 0000000..8671155 --- /dev/null +++ b/scripts/ipad-simulator-id.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# Prints the identifier of an iPad simulator: the one named by IPAD_SIMULATOR, or otherwise an +# iPad on the newest installed iOS version. Prints nothing when there is none. +set -eu + +xcrun simctl list devices available --json | /usr/bin/python3 -c ' +import json +import os +import sys + +wanted = os.environ.get("IPAD_SIMULATOR", "") +runtimes = json.load(sys.stdin)["devices"] + + +def version(runtime): + digits = runtime.rsplit("iOS-", 1)[-1].split("-") + return [int(part) for part in digits if part.isdigit()] + + +candidates = [ + (version(runtime), device) + for runtime, devices in runtimes.items() if "iOS" in runtime + for device in devices if device["name"].startswith("iPad") + and (not wanted or device["name"] == wanted) +] +candidates.sort(key=lambda pair: pair[0]) +print(candidates[-1][1]["udid"] if candidates else "") +' diff --git a/scripts/make-icon.sh b/scripts/make-icon.sh index 30e01e0..218e967 100755 --- a/scripts/make-icon.sh +++ b/scripts/make-icon.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Regenerate Resources/AppIcon.icns from scripts/make-icon.swift. +# Regenerate Resources/AppIcon.icns and the iPad's icon from scripts/make-icon.swift. set -euo pipefail cd "$(dirname "$0")/.." @@ -16,3 +16,7 @@ for size in 16 32 128 256 512; do done iconutil -c icns "$ICONSET" -o Resources/AppIcon.icns echo "Wrote Resources/AppIcon.icns" + +IPAD_ICON=ios/App/Assets.xcassets/AppIcon.appiconset/icon-1024.png +swift scripts/make-icon.swift --full-bleed "$IPAD_ICON" +echo "Wrote $IPAD_ICON" diff --git a/scripts/make-icon.swift b/scripts/make-icon.swift index d546a8d..b05b879 100755 --- a/scripts/make-icon.swift +++ b/scripts/make-icon.swift @@ -1,12 +1,15 @@ #!/usr/bin/env swift // Draws the app icon (a parchment battle map split into print tiles, with a compass rose) -// and writes a 1024 px PNG. Usage: swift scripts/make-icon.swift +// and writes a 1024 px PNG. Usage: swift scripts/make-icon.swift [--full-bleed] +// --full-bleed draws the iPad's icon: the map fills the square, opaque, and the system rounds the corners. import AppKit import CoreGraphics +let fullBleed = CommandLine.arguments.contains("--full-bleed") +let outputPath = CommandLine.arguments.dropFirst().filter { $0 != "--full-bleed" } let size: CGFloat = 1024 let body = CGRect(x: 100, y: 100, width: 824, height: 824) -let cornerRadius: CGFloat = 185 +let cornerRadius: CGFloat = fullBleed ? 0 : 185 func color(_ hex: UInt32, _ alpha: CGFloat = 1) -> CGColor { CGColor(srgbRed: CGFloat((hex >> 16) & 0xFF) / 255, green: CGFloat((hex >> 8) & 0xFF) / 255, @@ -168,20 +171,26 @@ func drawNorthLabel(at point: CGPoint) { label.draw(at: CGPoint(x: point.x - bounds.width / 2, y: point.y - bounds.height / 2)) } -guard CommandLine.arguments.count == 2 else { - FileHandle.standardError.write("usage: make-icon.swift \n".data(using: .utf8)!) +guard outputPath.count == 1 else { + FileHandle.standardError.write("usage: make-icon.swift [--full-bleed] \n".data(using: .utf8)!) exit(1) } +// App Store Connect rejects an iOS icon with an alpha channel, so the full-bleed icon is drawn opaque. +let alpha = fullBleed ? CGImageAlphaInfo.noneSkipLast : CGImageAlphaInfo.premultipliedLast let context = CGContext(data: nil, width: Int(size), height: Int(size), bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, - bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: alpha.rawValue)! NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false) +if fullBleed { + // The map's square fills the canvas. + context.scaleBy(x: size / body.width, y: size / body.height) + context.translateBy(x: -body.minX, y: -body.minY) +} drawBackground(context) drawTerrain(context) drawGrid(context) drawCompass(context) -let output = URL(fileURLWithPath: CommandLine.arguments[1]) +let output = URL(fileURLWithPath: outputPath[0]) let destination = CGImageDestinationCreateWithURL(output as CFURL, "public.png" as CFString, 1, nil)! CGImageDestinationAddImage(destination, context.makeImage()!, nil) guard CGImageDestinationFinalize(destination) else { exit(1) } diff --git a/scripts/run-ipad-simulator.sh b/scripts/run-ipad-simulator.sh new file mode 100755 index 0000000..a634d69 --- /dev/null +++ b/scripts/run-ipad-simulator.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Builds the iPad app for the simulator, installs it and starts it. +# +# IPAD_SIMULATOR name of the simulator to use (default: an iPad on the newest iOS installed) +set -eu + +cd "$(dirname "$0")/.." + +DEVICE="$(scripts/ipad-simulator-id.sh)" +[ -n "$DEVICE" ] || { echo "Starting the simulator failed: no iPad simulator is installed." >&2; exit 1; } + +# Unsigned, so it builds without a developer team; the App Group is then missing and Open from Scrollkeeper finds +# no library. +xcodebuild -project ios/Mapsmith.xcodeproj -scheme Mapsmith-iPad \ + -destination "platform=iOS Simulator,id=$DEVICE" -derivedDataPath ios/build \ + CODE_SIGNING_ALLOWED=NO build | tail -n 3 + +APP="ios/build/Build/Products/Debug-iphonesimulator/Mapsmith.app" +xcrun simctl boot "$DEVICE" 2>/dev/null || true +# Xcode 27 shows simulators in Device Hub; earlier versions in the Simulator app. +open -b com.apple.dt.Devices 2>/dev/null || open -a Simulator +xcrun simctl install "$DEVICE" "$APP" +xcrun simctl launch "$DEVICE" io.github.scooper4711.Mapsmith diff --git a/scripts/run-ipad-uitests.sh b/scripts/run-ipad-uitests.sh new file mode 100755 index 0000000..edc15d8 --- /dev/null +++ b/scripts/run-ipad-uitests.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# Runs the iPad UI tests in a simulator. They screenshot the window in landscape and portrait; the screenshots are +# kept in the test results (ios/build/Logs/Test). +# +# IPAD_SIMULATOR name of the simulator to use (default: an iPad on the newest iOS installed) +# ONLY tests to run, space-separated, such as "LayoutUITests/testInspectorInLandscape" +set -eu + +cd "$(dirname "$0")/.." + +DEVICE="$(scripts/ipad-simulator-id.sh)" +[ -n "$DEVICE" ] || { echo "Running the UI tests failed: no iPad simulator is installed." >&2; exit 1; } +echo "Running the UI tests on simulator $DEVICE..." + +set -- -project ios/Mapsmith.xcodeproj -scheme Mapsmith-iPad \ + -destination "platform=iOS Simulator,id=$DEVICE" -derivedDataPath ios/build CODE_SIGNING_ALLOWED=NO +for test in ${ONLY:-}; do set -- "$@" -only-testing:"MapsmithUITests/$test"; done + +LOG="$(mktemp)" +trap 'rm -f "$LOG"' EXIT +STATUS=0 +xcodebuild test "$@" > "$LOG" 2>&1 || STATUS=$? +grep -E " error: |Test Case .*(passed|failed)|\*\* TEST" "$LOG" || tail -n 20 "$LOG" +exit "$STATUS" diff --git a/scripts/version.sh b/scripts/version.sh new file mode 100755 index 0000000..60568c4 --- /dev/null +++ b/scripts/version.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# Prints the app's version, taken from git so the iPad and Mac builds agree. +# +# scripts/version.sh marketing the newest release tag without its "v" (1.2.0), or 0.0.0 before the first +# scripts/version.sh build the build number: the commit count, which grows with every commit on main +# scripts/version.sh xcconfig both, as Xcode build settings (written to ios/Version.xcconfig) +set -eu + +cd "$(dirname "$0")/.." + +marketing() { + tag="$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || echo v0.0.0)" + echo "${tag#v}" +} + +build() { + # A shallow clone counts only the commits it fetched, which would make a build number go backwards. + if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then + echo "Reading the build number failed: the clone is shallow; fetch the full history." >&2 + exit 1 + fi + git rev-list --count HEAD +} + +case "${1:-}" in + marketing) marketing ;; + build) build ;; + xcconfig) + echo "// Written by scripts/version.sh; not committed." + echo "MARKETING_VERSION = $(marketing)" + echo "CURRENT_PROJECT_VERSION = $(build)" + ;; + *) echo "Usage: scripts/version.sh marketing|build|xcconfig" >&2; exit 2 ;; +esac diff --git a/sonar-project.properties b/sonar-project.properties index ce0a460..437e0e4 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -10,4 +10,4 @@ sonar.coverageReportPaths=coverage/sonar-coverage.xml # The SwiftUI app is a thin layer and is not unit tested; all logic lives in MapsmithCore, which is # what the coverage gate measures (see docs/specs). -sonar.coverage.exclusions=Sources/Mapsmith/** +sonar.coverage.exclusions=Sources/Mapsmith/**,Sources/MapsmithUI/**