SPB Git

Repository Public BSD-3-Clause

DownloadsScreen.swift 14.6 KB 277 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/Regions/DownloadsScreen.swift10// Module           : Regions11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ORIXDesignSystem89import ORIXMapPackage90import SwiftUI91import UniformTypeIdentifiers9293extension UTType {94    static let orixMapPackage = UTType(exportedAs: "ai.spboucher.orix.maps.package", conformingTo: .data)95}9697/// Downloaded maps: what is installed, what the catalog offers, running downloads, import from Files.98struct DownloadsScreen: View {99    @Environment(AppModel.self) private var app100    @State private var importing = false101    @State private var confirmDelete: InstalledRegion?102103    private var regions: RegionsModel { app.regionsModel }104    private var language: String { app.settings.interfaceLanguageCode }105106    var body: some View {107        @Bindable var model = app.regionsModel108        List {109            if let error = regions.storeError {110                Section { NoticeView("Map storage could not be opened on this device.", kind: .error); Text(verbatim: RegionsModel.describe(error)).font(.footnote) }111            }112            Section {113                if regions.installed.isEmpty {114                    Text("No region installed. The built-in world map shows countries, cities and coastlines only.")115                        .font(.footnote).foregroundStyle(.secondary)116                }117                ForEach(regions.installed) { region in installedRow(region) }118            } header: { Text("On this device") } footer: {119                if !regions.installed.isEmpty {120                    Text("Maps use \(app.settings.formatter.bytes(Int64(regions.totalInstalledBytes))) on this device.")121                }122            }123            Section {124                if let catalog = regions.catalog {125                    if catalog.isStale {126                        NoticeView("Offline: this list was last updated on \(catalog.fetchedAt.formatted(date: .abbreviated, time: .shortened)).", kind: .warning)127                    }128                    let offered = catalog.document.regions129                    if offered.isEmpty { Text("No region is published yet.").font(.footnote).foregroundStyle(.secondary) }130                    ForEach(offered) { region in catalogRow(region) }131                } else if regions.isLoadingCatalog {132                    HStack { ProgressView(); Text("Loading the catalog…").foregroundStyle(.secondary) }133                } else if let error = regions.catalogError {134                    NoticeView("\(RegionsModel.describe(error))", kind: .warning)135                    Button("Try again") { Task { await regions.refreshCatalog(force: true) } }136                }137            } header: { Text("Available from ORIX Labs") } footer: {138                Text("Maps are downloaded from www.orixlab.dev. The request contains no position, no search and no identifier. Each file is signed and checked before it is installed.")139            }140            Section {141                Button { importing = true } label: { Label("Import a map file", systemImage: "square.and.arrow.down") }142                    .accessibilityIdentifier("downloads.import")143            } footer: { Text("Install a .orixmap file from Files, for example one copied from another device. It is verified like a download.") }144        }145        .navigationTitle("Maps")146        .navigationBarTitleDisplayMode(.inline)147        .refreshable { await regions.refreshCatalog(force: true) }148        .task { await regions.refreshCatalog() }149        .fileImporter(isPresented: $importing, allowedContentTypes: [.orixMapPackage, .data]) { result in150            guard let url = try? result.get() else { return }151            Task { if await regions.importPackage(from: url) { app.showToast(String(localized: "Map installed")) } }152        }153        .alert("Not installed", isPresented: Binding(get: { model.lastFailure != nil }, set: { if !$0 { model.lastFailure = nil } })) { Button("OK") {} } message: { Text(model.lastFailure ?? "") }154        .accessibilityIdentifier("downloads.list")155    }156157    private func installedRow(_ region: InstalledRegion) -> some View {158        VStack(alignment: .leading, spacing: 6) {159            AdaptiveStack {160                Text(region.manifest.names[language] ?? region.manifest.names["en"] ?? region.id).font(.headline)161                Spacer(minLength: 0)162                Text(app.settings.formatter.bytes(Int64(region.totalSizeOnDisk))).font(.subheadline).foregroundStyle(.secondary)163            }164            AdaptiveStack(spacing: 10) {165                ForEach(region.manifest.capabilities, id: \.self) { capabilityBadge($0) }166            }167            if let date = Timestamp.parse(region.manifest.dataTimestamp) {168                Text("Map data of \(date.formatted(date: .abbreviated, time: .omitted))").font(.footnote).foregroundStyle(.secondary)169            }170            HStack {171                Button {172                    app.modal = nil173                    app.map.fit(region.manifest.bbox)174                } label: { Text("Show on map").frame(minHeight: ORIX.minimumTarget).contentShape(.rect) }175                .buttonStyle(.borderless)176                Spacer()177                if region.previousVersion != nil {178                    Menu {179                        Button("Go back to the previous version") { regions.rollback(region.id) }180                        Button("Remove the previous version") { regions.removePreviousVersion(region.id) }181                    } label: { Image(systemName: "clock.arrow.circlepath").frame(width: ORIX.minimumTarget, height: 36) }182                        .accessibilityLabel("Previous version")183                }184                Button(role: .destructive) { confirmDelete = region } label: { Image(systemName: "trash").frame(width: ORIX.minimumTarget, height: 36) }185                    .buttonStyle(.borderless)186                    .accessibilityLabel(Text("Delete \(region.manifest.names[language] ?? region.id)"))187                    .accessibilityIdentifier("downloads.delete.\(region.id)")188                    .confirmationDialog("Delete this map?", isPresented: Binding(get: { confirmDelete?.id == region.id }, set: { if !$0 { confirmDelete = nil } }), titleVisibility: .visible) {189                        Button("Delete \(region.manifest.names[language] ?? region.id)", role: .destructive) { regions.delete(region.id) }190                            .accessibilityIdentifier("downloads.delete.confirm")191                    } message: { Text("Streets, search and directions for this region will no longer be available offline. Saved places and tracks are kept.") }192            }193            .font(.subheadline)194        }195        .padding(.vertical, 4)196        .accessibilityElement(children: .contain)197        .accessibilityIdentifier("downloads.installed.\(region.id)")198    }199200    private func capabilityBadge(_ capability: String) -> some View {201        let (icon, label): (String, LocalizedStringKey) = switch capability {202        case "map": ("map", "Map")203        case "search": ("magnifyingglass", "Search")204        case "routing": ("arrow.triangle.turn.up.right.diamond", "Directions")205        case "terrain": ("mountain.2", "Terrain")206        default: ("questionmark", "Other")207        }208        return Label(label, systemImage: icon).font(.caption).foregroundStyle(.secondary).labelStyle(.titleAndIcon).fixedSize()209    }210211    @ViewBuilder212    private func catalogRow(_ region: CatalogRegion) -> some View {213        let state = regions.downloads[region.id]214        let local = regions.installedRegion(region.id)215        VStack(alignment: .leading, spacing: 6) {216            AdaptiveStack {217                Text(region.name(preferring: [language])).font(.headline)218                Spacer(minLength: 0)219                Text(app.settings.formatter.bytes(Int64(region.latest.downloadSize))).font(.subheadline).foregroundStyle(.secondary)220            }221            AdaptiveStack(spacing: 10) { ForEach(region.capabilities, id: \.self) { capabilityBadge($0) } }222            if let date = region.latest.dataDate {223                Text("Map data of \(date.formatted(date: .abbreviated, time: .omitted))").font(.footnote).foregroundStyle(.secondary)224            }225            switch state {226            case .downloading(let p):227                ProgressView(value: p.fraction) {228                    Text("Downloading \(app.settings.formatter.bytes(Int64(p.receivedBytes))) of \(app.settings.formatter.bytes(Int64(p.totalBytes)))").font(.footnote)229                }230                HStack {231                    Button("Pause") { regions.pause(region.id) }.buttonStyle(.borderless).accessibilityIdentifier("downloads.pause.\(region.id)")232                    Spacer()233                    Button("Cancel", role: .destructive) { regions.cancel(region.id) }.buttonStyle(.borderless)234                }235                .font(.subheadline)236            case .waitingToRetry(_, _, let reason):237                Text(verbatim: RegionsModel.describe(reason)).font(.footnote).foregroundStyle(.secondary)238                Button("Cancel", role: .destructive) { regions.cancel(region.id) }.buttonStyle(.borderless).font(.subheadline)239            case .verifying, .installing:240                HStack { ProgressView(); Text("Checking and installing…").font(.footnote).foregroundStyle(.secondary) }241            case .paused(let received, let total):242                ProgressView(value: total == 0 ? 0 : Double(received) / Double(total)) { Text("Paused").font(.footnote) }243                HStack {244                    Button("Resume") { regions.resume(region.id) }.buttonStyle(.borderless).accessibilityIdentifier("downloads.resume.\(region.id)")245                    Spacer()246                    Button("Cancel", role: .destructive) { regions.cancel(region.id) }.buttonStyle(.borderless)247                }248                .font(.subheadline)249            case .failed(let error):250                NoticeView("\(RegionsModel.describe(error))", kind: .error)251                HStack {252                    Button("Try again") { regions.resume(region.id) }.buttonStyle(.borderless)253                    Spacer()254                    Button("Dismiss") { regions.dismissFailure(region.id) }.buttonStyle(.borderless)255                }256                .font(.subheadline)257            case .completed, .cancelled, .none:258                if let missing = regions.missingSpace(for: region) {259                    NoticeView("Not enough free space: \(app.settings.formatter.bytes(Int64(missing))) more is needed.", kind: .warning)260                } else if local == nil {261                    Button { regions.download(region) } label: { Label("Download", systemImage: "arrow.down.circle.fill") }262                        .buttonStyle(.borderless).font(.subheadline.weight(.semibold))263                        .accessibilityIdentifier("downloads.get.\(region.id)")264                } else if regions.hasUpdate(region) {265                    Button { regions.download(region) } label: { Label("Update", systemImage: "arrow.triangle.2.circlepath") }266                        .buttonStyle(.borderless).font(.subheadline.weight(.semibold))267                } else {268                    Label("Installed and up to date", systemImage: "checkmark.circle.fill").font(.footnote).foregroundStyle(ORIX.Palette.success)269                }270            }271        }272        .padding(.vertical, 4)273        .accessibilityElement(children: .contain)274        .accessibilityIdentifier("downloads.catalog.\(region.id)")275    }276}277
Files main
Menu

Theme