Files
VCCPlusOSS/platforms/macos/App/DiskImageEditorView.swift
T

332 lines
22 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
import AppKit
struct DiskImageEditorView: View {
@ObservedObject var model: DiskImageEditorModel
var body: some View {
VStack(spacing: 0) {
actionBar
Divider()
HStack(alignment: .top, spacing: 12) {
VStack(alignment: .leading, spacing: 5) {
Label(model.name, systemImage: "externaldrive").font(.headline)
if model.contents.volumes.count > 1 {
Picker("Volume", selection: Binding(get: { model.contents.volumeID }, set: { model.selectVolume($0) })) {
ForEach(model.contents.volumes) { volume in Text(volume.name).tag(volume.id) }
}.frame(maxWidth: 420).disabled(model.busy)
.accessibilityIdentifier("disk-editor-volume")
.help("Choose a filesystem within this image. Other volumes and unrecognized regions stay unchanged.")
}
Text(model.displayPath).font(.callout.monospaced()).foregroundStyle(.secondary)
.accessibilityIdentifier("disk-editor-path")
if model.session != nil {
Label(model.presentation.context, systemImage: "lock.fill")
.font(.caption).foregroundStyle(.secondary)
} else { Text(model.presentation.context).font(.caption).foregroundStyle(.secondary) }
if model.contents.preservedBytes > 0 {
Text("Outside selected volume: \(space(model.contents.preservedBytes)) · Preserved unchanged")
.font(.caption).foregroundStyle(.secondary)
.accessibilityIdentifier("disk-editor-preserved-data")
.help("Other volumes and extra data are preserved. Total, Used and Free describe only the selected filesystem.")
}
}
Spacer()
if model.changed { Text("Unapplied changes").font(.caption).foregroundStyle(.secondary) }
if model.busy { ProgressView().controlSize(.small).accessibilityLabel("Working with disk image") }
}.padding(16)
Divider()
DiskEditorFileTable(model: model).accessibilityIdentifier("disk-editor-files")
if let error = model.error {
HStack(alignment: .top) {
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.red).textSelection(.enabled)
Spacer(); Button("Dismiss") { model.error = nil }
}.font(.callout).padding(12).accessibilityIdentifier("disk-editor-error")
} else if let notice = model.notice { Text(notice).font(.callout).frame(maxWidth: .infinity, alignment: .leading).padding(12) }
Divider()
HStack {
Text(model.os9 ? "OS-9 RBF" : "Disk BASIC")
Text("· \(model.contents.entries.count) \(model.contents.entries.count == 1 ? "entry" : "entries")")
Spacer()
Text("Total \(space(model.contents.capacity)) Used \(space(model.contents.used)) Free \(space(model.contents.free))")
.monospacedDigit().accessibilityIdentifier("disk-editor-space")
.help(model.os9 ? "Volume capacity and allocated/free space from the OS-9 allocation bitmap." : "Allocatable file space from the Disk BASIC granule map. The reserved directory track is excluded.")
}.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16).padding(.vertical, 10)
Divider()
HStack {
if !model.canApply {
Label(model.session?.applyRestriction ?? "The original is read-only. Save an edited copy to keep changes.", systemImage: "lock")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
} else {
Text(model.presentation.applyHint)
.font(.caption).foregroundStyle(.secondary)
}
Spacer()
Button("Close") { model.close() }.accessibilityIdentifier("disk-editor-close")
Button("Save Edited Copy…") { model.saveCopy() }.accessibilityIdentifier("disk-editor-save-copy")
Button(model.presentation.applyButtonTitle) { model.apply() }
.disabled(!model.changed || !model.canApply).accessibilityIdentifier("disk-editor-apply")
}.padding(14).disabled(model.busy)
}
.frame(minWidth: 760, minHeight: 440)
.sheet(item: $model.importing) { request in DiskEditorImportSheet(model: model, request: request) }
.sheet(item: $model.naming) { request in DiskEditorNameSheet(model: model, request: request) }
.sheet(item: $model.information) { information in DiskEditorInformationSheet(model: model, information: information) }
.sheet(item: $model.moving) { request in DiskEditorMoveSheet(model: model, request: request) }
}
// This window is hosted directly in AppKit. Keep its actions in the content
// rather than relying on a SwiftUI scene to install an NSToolbar.
private var actionBar: some View {
HStack(spacing: 8) {
HStack(spacing: 4) {
action("Back", "chevron.left", "disk-editor-back", disabled: !model.canBack) { model.back() }
action("Up", "arrow.up", "disk-editor-up", disabled: model.path.isEmpty) { model.up() }
action("Refresh", "arrow.clockwise", "disk-editor-refresh") { model.refresh() }
}
Divider().frame(height: 22)
HStack(spacing: 4) {
action("Import", "square.and.arrow.down", "disk-editor-import") { model.chooseImport() }
action("Export", "square.and.arrow.up", "disk-editor-export", disabled: !model.selected.contains(where: { !$0.directory })) { model.export() }
action("New Folder", "folder.badge.plus", "disk-editor-new-folder", disabled: !model.os9) { model.newFolder() }
action("Rename", "pencil", "disk-editor-rename", disabled: model.selected.count != 1) { model.rename() }
action("Move To…", "folder", "disk-editor-move", disabled: !model.canMove) { model.moveTo() }
.help("Move selected regular files to another folder in this OS-9 image.")
action("Delete", "trash", "disk-editor-delete", disabled: model.selected.isEmpty) { model.delete() }
action("Info", "info.circle", "disk-editor-info", disabled: model.selected.count != 1) { model.showInfo() }
}
Spacer(minLength: 12)
HStack(spacing: 4) {
Button { model.undo() } label: { Label("Undo", systemImage: "arrow.uturn.backward") }
.keyboardShortcut("z", modifiers: .command).help("Undo disk edit").accessibilityIdentifier("disk-editor-undo")
.accessibilityLabel("Undo")
.disabled(model.busy || model.undoStates.isEmpty)
Button { model.redo() } label: { Label("Redo", systemImage: "arrow.uturn.forward") }
.keyboardShortcut("z", modifiers: [.command, .shift]).help("Redo disk edit").accessibilityIdentifier("disk-editor-redo")
.accessibilityLabel("Redo")
.disabled(model.busy || model.redoStates.isEmpty)
}
}.labelStyle(.iconOnly).buttonStyle(.bordered).padding(.horizontal, 14).padding(.vertical, 10)
}
private func space(_ value: Int64?) -> String {
guard let value else { return "Unavailable" }
return ByteCountFormatter.string(fromByteCount: value, countStyle: .file)
}
private func action(_ name: String, _ symbol: String, _ id: String, disabled: Bool = false, perform: @escaping () -> Void) -> some View {
Button(action: perform) { Label(name, systemImage: symbol) }.help(name)
.accessibilityLabel(name).accessibilityIdentifier(id).disabled(model.busy || disabled)
}
}
private struct DiskEditorMoveSheet: View {
@ObservedObject var model: DiskImageEditorModel
let request: DiskEditorMoveRequest
@State private var destination: String
@State private var selectedFolder: String?
@State private var contents: DiskEditorContents?
@State private var loading = true
@State private var error: String?
init(model: DiskImageEditorModel, request: DiskEditorMoveRequest) {
self.model = model; self.request = request
_destination = State(initialValue: request.sourcePath)
}
private func open(_ path: String) { destination = path; selectedFolder = nil; model.error = nil }
var body: some View {
VStack(alignment: .leading, spacing: 14) {
Text("Move \(request.files.count == 1 ? request.files[0].name : "\(request.files.count) files")").font(.headline)
Text("Choose a folder inside this OS-9 image. Existing files are never replaced.")
.font(.callout).foregroundStyle(.secondary)
HStack {
Button("Root", systemImage: "externaldrive") { open("") }.accessibilityIdentifier("disk-editor-move-root")
Button("Up", systemImage: "arrow.up") { open(destination.split(separator: "/").dropLast().joined(separator: "/")) }
.disabled(destination.isEmpty).keyboardShortcut(.upArrow, modifiers: .command).accessibilityIdentifier("disk-editor-move-up")
Text("/" + destination).font(.callout.monospaced()).lineLimit(1).truncationMode(.middle).help("/" + destination)
.accessibilityLabel("Destination folder").accessibilityValue("/" + destination).accessibilityIdentifier("disk-editor-move-path")
Spacer()
if loading { ProgressView().controlSize(.small) }
}
List(selection: $selectedFolder) {
ForEach(contents?.entries.filter(\.directory) ?? []) { folder in
Label(folder.name, systemImage: "folder").frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle()).tag(folder.path)
.accessibilityIdentifier("disk-editor-move-folder-" + folder.path)
.onTapGesture(count: 2) { open(folder.path) }
}
}.accessibilityLabel("Folders in destination directory").accessibilityIdentifier("disk-editor-move-folders")
if let message = error ?? model.error {
Label(message, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.red)
.fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("disk-editor-move-error")
}
HStack {
Button("Open Folder") { if let path = selectedFolder { open(path) } }
.disabled(loading || selectedFolder == nil).keyboardShortcut(.downArrow, modifiers: .command)
.accessibilityIdentifier("disk-editor-move-open")
Spacer()
Button("Cancel") { model.moving = nil }.keyboardShortcut(.cancelAction).accessibilityIdentifier("disk-editor-move-cancel")
Button("Move Here") { model.move(request, to: destination, expectedDestination: contents) }
.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-move-confirm")
.disabled(loading || contents == nil || destination.caseInsensitiveCompare(request.sourcePath) == .orderedSame || !model.moveSourceIsCurrent(request))
}
}.padding(20).frame(width: 540, height: 420).disabled(model.busy)
.task(id: destination + "/" + model.revision.uuidString) {
loading = true; contents = nil; error = nil
do { contents = try await model.moveDestination(request, path: destination) }
catch { if !Task.isCancelled { self.error = error.localizedDescription } }
if !Task.isCancelled { loading = false }
}
}
}
private struct DiskEditorInformationSheet: View {
@ObservedObject var model: DiskImageEditorModel
let information: DiskEditorInformation
@State private var permissions: Int
@State private var ownerUser: String
@State private var ownerGroup: String
init(model: DiskImageEditorModel, information: DiskEditorInformation) {
self.model = model
self.information = information
_permissions = State(initialValue: information.entry.permissions & 0x7f)
_ownerUser = State(initialValue: String(information.entry.owner))
_ownerGroup = State(initialValue: String(information.entry.group))
}
private func ownerID(_ text: String) -> Int? {
guard !text.isEmpty, text.utf8.allSatisfy({ (48...57).contains($0) }),
let value = Int(text), (0...255).contains(value) else { return nil }
return value
}
private var valid: Bool { ownerID(ownerUser) != nil && ownerID(ownerGroup) != nil }
private var changed: Bool {
permissions != (information.entry.permissions & 0x7f) ||
ownerID(ownerUser) != information.entry.owner || ownerID(ownerGroup) != information.entry.group
}
private func access(_ title: String, bit: Int, id: String) -> some View {
Toggle(title, isOn: Binding(get: { permissions & bit != 0 }, set: { enabled in
if enabled { permissions |= bit } else { permissions &= ~bit }
})).toggleStyle(.checkbox).accessibilityIdentifier(id)
.accessibilityLabel(bit <= 4 ? "Owner \(title)" : bit <= 32 ? "Public \(title)" : title)
}
var body: some View {
VStack(alignment: .leading, spacing: 16) {
Text("File Information").font(.headline)
Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 6) {
GridRow { Text("Name").foregroundStyle(.secondary); Text(information.entry.name).textSelection(.enabled) }
GridRow { Text("Path").foregroundStyle(.secondary); Text("/" + information.entry.path).textSelection(.enabled) }
GridRow { Text("Entry type").foregroundStyle(.secondary); Text(information.entry.directory ? "Directory" : "File").accessibilityIdentifier("disk-editor-info-directory") }
GridRow { Text("Type").foregroundStyle(.secondary); Text(information.entry.type) }
GridRow { Text("Size").foregroundStyle(.secondary); Text("\(information.entry.size) bytes").monospacedDigit() }
}
if model.os9 {
GroupBox("OS-9 Access") {
VStack(alignment: .leading, spacing: 0) {
Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 10) {
GridRow {
Text("Owner")
access("Read", bit: 1, id: "disk-editor-info-owner-read")
access("Write", bit: 2, id: "disk-editor-info-owner-write")
access("Execute", bit: 4, id: "disk-editor-info-owner-execute")
}
GridRow {
Text("Public")
access("Read", bit: 8, id: "disk-editor-info-public-read")
access("Write", bit: 16, id: "disk-editor-info-public-write")
access("Execute", bit: 32, id: "disk-editor-info-public-execute")
}
}.padding(8)
access("Single access (non-shareable)", bit: 64, id: "disk-editor-info-single-access")
.help("Allows only one opener at a time; this is the OS-9 single-access attribute.")
.frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 8)
}
}
GroupBox("OS-9 Ownership") {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 10) {
Text("Group ID")
TextField("Group ID", text: $ownerGroup).frame(width: 70).accessibilityIdentifier("disk-editor-info-owner-group")
Spacer()
Text("User ID")
TextField("User ID", text: $ownerUser).frame(width: 70).accessibilityIdentifier("disk-editor-info-owner-user")
}.textFieldStyle(.roundedBorder).padding(8)
if let group = ownerID(ownerGroup), let user = ownerID(ownerUser) {
Text("Owner ID: \(group * 256 + user)").monospacedDigit().font(.callout)
.frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8)
.accessibilityIdentifier("disk-editor-info-owner-id")
}
Text("OS-9 stores one owner ID. The Owner column shows its high and low bytes as group.user; enter each from 0 to 255.")
.font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 8)
}
}
if !valid {
Label("Group ID and User ID must each be a whole number from 0 to 255.", systemImage: "exclamationmark.triangle")
.font(.callout).foregroundStyle(.red).accessibilityIdentifier("disk-editor-info-validation")
}
}
ScrollView {
Text(information.details).font(.system(.callout, design: .monospaced)).textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}.frame(minHeight: 90, maxHeight: .infinity).accessibilityIdentifier("disk-editor-info-details")
if let error = model.error {
Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.red)
.fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("disk-editor-info-error")
}
HStack {
if model.os9 {
Text("Changes stay in the editor until the disk image is applied or saved.")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
Spacer()
Button("Cancel") { model.information = nil }.keyboardShortcut(.cancelAction).accessibilityIdentifier("disk-editor-info-cancel")
Button("Save Changes") {
guard let user = ownerID(ownerUser), let group = ownerID(ownerGroup) else { return }
model.applyInformation(information, permissions: permissions, ownerUser: user, ownerGroup: group)
}.keyboardShortcut(.defaultAction).disabled(!valid || !changed).accessibilityIdentifier("disk-editor-info-save")
} else {
Spacer()
Button("Done") { model.information = nil }.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-info-done")
}
}
}.padding(20).frame(width: 590, height: model.os9 ? 660 : 440).disabled(model.busy)
}
}
private struct DiskEditorImportSheet: View {
@ObservedObject var model: DiskImageEditorModel
@State var request: DiskEditorImportRequest
var body: some View {
VStack(alignment: .leading, spacing: 16) {
Text("Import into \(model.displayPath)").font(.headline)
Text(request.urls.map(\.lastPathComponent).joined(separator: "\n")).lineLimit(6).textSelection(.enabled)
if !model.os9 {
Picker("File Type", selection: $request.type) {
Text("BASIC program").tag(0); Text("BASIC data").tag(1); Text("Machine language").tag(2); Text("Text").tag(3)
}.accessibilityIdentifier("disk-editor-import-type")
Picker("Encoding", selection: $request.ascii) { Text("ASCII").tag(true); Text("Binary / Tokenized").tag(false) }
.accessibilityIdentifier("disk-editor-import-encoding")
Text("Bytes are copied unchanged. Choose Binary / Tokenized for a tokenized BASIC program. These settings apply to every selected file.")
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
}
HStack {
Spacer(); Button("Cancel") { model.importing = nil }.keyboardShortcut(.cancelAction)
Button("Import") { model.confirmImport(request) }.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-import-confirm")
}
}.padding(22).frame(width: 470)
}
}
private struct DiskEditorNameSheet: View {
@ObservedObject var model: DiskImageEditorModel
@State var request: DiskEditorNameRequest
var body: some View {
VStack(alignment: .leading, spacing: 16) {
Text(request.entry == nil ? "New Folder" : "Rename Entry").font(.headline)
TextField("Name", text: $request.name).accessibilityIdentifier("disk-editor-name")
if !model.os9 { Text("Disk BASIC names use up to 8 characters plus a 3-character extension.").font(.caption).foregroundStyle(.secondary) }
HStack {
Spacer(); Button("Cancel") { model.naming = nil }.keyboardShortcut(.cancelAction)
Button(request.entry == nil ? "Create Folder" : "Rename") { model.confirmName(request) }
.keyboardShortcut(.defaultAction).accessibilityIdentifier("disk-editor-name-confirm")
.disabled(request.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}.padding(22).frame(width: 420)
}
}