diff --git a/Packaging/Info.plist b/Packaging/Info.plist index 0788ee4..a9cec77 100644 --- a/Packaging/Info.plist +++ b/Packaging/Info.plist @@ -16,6 +16,8 @@ 1 LSMinimumSystemVersion 13.0 + NSLocalNetworkUsageDescription + EzDent подключается к указанному вами серверу в локальной сети. NSHighResolutionCapable diff --git a/README.md b/README.md index 312e31e..5ac09b6 100644 --- a/README.md +++ b/README.md @@ -18,3 +18,16 @@ open dist/EzDent.app ``` Скрипт собирает обе архитектуры, объединяет их через `lipo` и ставит локальную подпись ad hoc. Для распространения за пределами Mac App Store подготовьте подпись Developer ID и нотарификацию. + +## Текущая версия клиента + +В боковой панели можно искать демонстрационные карточки по имени и номеру. Кнопка «Открыть снимки…» загружает поддерживаемые macOS изображения, например JPEG, PNG и TIFF, в выбранную карточку на время работы окна. DICOM, данные с сервера и управление рентгеновским оборудованием пока не поддерживаются. + +В настройках приложения (`⌘,`) можно сохранить хост и порт ezServer и проверить TCP-подключение к этому адресу. Клиент пока не выполняет авторизацию и запросы к API. + +## Что выяснилось из установщика EzDent-i 3.1.11 + +- Установщик InstallShield содержит профили Client и Console. Главный Windows-клиент — `VTE232.exe`. В справке CHM описаны поиск по имени или номеру карты, просмотр снимков, их получение, отчёты и консультации. +- В шаблоне `VTServerConfig.ini` указаны File Manager (55001), Patch Manager (55011) и EzWebServer (43112). Порт 55005 указан дополнительно для поиска. Клиент macOS по умолчанию предлагает 43112 и позволяет изменить порт. +- Шаблон `VTDBConfig.ini` указывает на PostgreSQL. В Windows-бинарнике есть ссылки на HTTP, `/api/v1` и авторизацию. Эти артефакты сами по себе не определяют, каким способом конкретная инсталляция отдаёт карточки и снимки. Для интеграции нужно подтвердить контракт API на ezServer. +- Установщик изучался статически без запуска. Windows-бинарники, ресурсы и настройки из дистрибутива не входят в приложение macOS. diff --git a/Sources/EzDent/EzDentApp.swift b/Sources/EzDent/EzDentApp.swift index 9a066d5..90b80e9 100644 --- a/Sources/EzDent/EzDentApp.swift +++ b/Sources/EzDent/EzDentApp.swift @@ -4,9 +4,13 @@ import SwiftUI struct EzDentApp: App { var body: some Scene { WindowGroup { - Text("EzDent") - .font(.largeTitle) - .frame(minWidth: 480, minHeight: 320) + PatientWorkspace() + .frame(minWidth: 760, minHeight: 480) + } + .defaultSize(width: 1050, height: 680) + + Settings { + ServerSettings() } } } diff --git a/Sources/EzDent/PatientWorkspace.swift b/Sources/EzDent/PatientWorkspace.swift new file mode 100644 index 0000000..e9453c1 --- /dev/null +++ b/Sources/EzDent/PatientWorkspace.swift @@ -0,0 +1,163 @@ +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +struct PatientWorkspace: View { + private struct Patient: Identifiable { + let id: String + let name: String + } + + private struct Attachment: Identifiable { + let id = UUID() + let name: String + let image: NSImage + } + + private let patients = [ + Patient(id: "DEMO-001", name: "Демо-пациент 1"), + Patient(id: "DEMO-002", name: "Демо-пациент 2") + ] + + @State private var search = "" + @State private var patientID: Patient.ID? + @State private var attachments: [Patient.ID: [Attachment]] = [:] + @State private var attachmentID: Attachment.ID? + @State private var showImporter = false + @State private var importError: String? + + private var filteredPatients: [Patient] { + let query = search.trimmingCharacters(in: .whitespacesAndNewlines) + return patients.filter { + query.isEmpty || $0.name.localizedStandardContains(query) + || $0.id.localizedStandardContains(query) + } + } + + private var patient: Patient? { + patients.first { $0.id == patientID } + } + + private var patientAttachments: [Attachment] { + patientID.flatMap { attachments[$0] } ?? [] + } + + var body: some View { + NavigationSplitView { + List(filteredPatients, selection: $patientID) { patient in + VStack(alignment: .leading, spacing: 4) { + Text(patient.name) + Text(patient.id) + .font(.caption) + .foregroundStyle(.secondary) + } + .tag(patient.id) + } + .searchable(text: $search, placement: .sidebar, prompt: "Имя или номер карты") + .navigationTitle("Пациенты") + .navigationSplitViewColumnWidth(min: 190, ideal: 240) + .safeAreaInset(edge: .bottom) { + Text("Демонстрационные данные") + .font(.caption) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(12) + .background(.bar) + } + } detail: { + if let patient { + imageWorkspace + .navigationTitle(patient.name) + .navigationSubtitle(patient.id) + .toolbar { + Button { + showImporter = true + } label: { + Label("Открыть снимки…", systemImage: "folder") + } + } + } else { + placeholder("Выберите пациента", icon: "person.crop.rectangle") + .navigationTitle("EzDent") + } + } + .onChange(of: patientID) { _ in + attachmentID = patientAttachments.first?.id + } + .fileImporter(isPresented: $showImporter, allowedContentTypes: [.image], allowsMultipleSelection: true) { + importImages($0) + } + .alert("Не удалось открыть снимки", isPresented: Binding( + get: { importError != nil }, + set: { if !$0 { importError = nil } } + )) { + Button("ОК", role: .cancel) {} + } message: { + Text(importError ?? "") + } + } + + private var imageWorkspace: some View { + VStack(spacing: 0) { + if let attachment = patientAttachments.first(where: { $0.id == attachmentID }) { + Image(nsImage: attachment.image) + .resizable() + .scaledToFit() + .accessibilityLabel(attachment.name) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(16) + } else { + placeholder("Откройте локальные снимки", icon: "photo") + } + + if !patientAttachments.isEmpty { + Divider() + Picker("Снимок", selection: $attachmentID) { + ForEach(patientAttachments) { attachment in + Text(attachment.name).tag(Optional(attachment.id)) + } + } + .padding(12) + } + } + } + + private func placeholder(_ title: String, icon: String) -> some View { + VStack(spacing: 12) { + Image(systemName: icon) + .font(.largeTitle) + .accessibilityHidden(true) + Text(title) + .font(.headline) + } + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private func importImages(_ result: Result<[URL], Error>) { + guard let patientID else { return } + do { + var imported: [Attachment] = [] + var failures: [String] = [] + for url in try result.get() { + let hasAccess = url.startAccessingSecurityScopedResource() + defer { if hasAccess { url.stopAccessingSecurityScopedResource() } } + if let data = try? Data(contentsOf: url), + let image = NSImage(data: data), image.isValid { + imported.append(Attachment(name: url.lastPathComponent, image: image)) + } else { + failures.append(url.lastPathComponent) + } + } + if let first = imported.first { + attachments[patientID, default: []].append(contentsOf: imported) + attachmentID = first.id + } + if !failures.isEmpty { + importError = failures.joined(separator: "\n") + } + } catch { + importError = error.localizedDescription + } + } +} diff --git a/Sources/EzDent/ServerSettings.swift b/Sources/EzDent/ServerSettings.swift new file mode 100644 index 0000000..a59cb88 --- /dev/null +++ b/Sources/EzDent/ServerSettings.swift @@ -0,0 +1,92 @@ +import Network +import SwiftUI + +struct ServerSettings: View { + @AppStorage("ezServerHost") private var host = "" + @AppStorage("ezServerPort") private var port = "43112" + @StateObject private var probe = ServerProbe() + + var body: some View { + Form { + TextField("Сервер", text: $host, prompt: Text("Имя хоста или IP-адрес")) + TextField("Порт", text: $port) + Button(probe.isChecking ? "Отменить" : "Проверить TCP") { + if probe.isChecking { + probe.reset() + } else { + probe.check(host: host, port: port) + } + } + if let status = probe.status { + Text(status) + .foregroundStyle(.secondary) + .textSelection(.enabled) + } + } + .padding(24) + .frame(width: 450) + .onChange(of: host) { _ in probe.reset() } + .onChange(of: port) { _ in probe.reset() } + .onDisappear { probe.reset() } + } +} + +@MainActor +private final class ServerProbe: ObservableObject { + @Published private(set) var status: String? + @Published private(set) var isChecking = false + + private var connection: NWConnection? + private var timeout: Task? + + func check(host: String, port: String) { + reset() + let host = host.trimmingCharacters(in: .whitespacesAndNewlines) + guard !host.isEmpty, + host.rangeOfCharacter(from: .whitespacesAndNewlines) == nil, + !host.contains("/"), + let number = UInt16(port.trimmingCharacters(in: .whitespacesAndNewlines)), + number > 0, let endpointPort = NWEndpoint.Port(rawValue: number) else { + status = "Укажите имя хоста или IP-адрес и порт от 1 до 65535." + return + } + + let connection = NWConnection(host: NWEndpoint.Host(host), port: endpointPort, using: .tcp) + self.connection = connection + isChecking = true + status = "Подключение…" + connection.stateUpdateHandler = { [weak self, weak connection] state in + Task { @MainActor in + guard let self, let connection, self.connection === connection else { return } + switch state { + case .ready: + self.finish("TCP-порт доступен. Запросы к API не отправлялись.") + case let .failed(error), let .waiting(error): + self.finish("Подключение не удалось: \(error.localizedDescription)") + default: + break + } + } + } + timeout = Task { + try? await Task.sleep(for: .seconds(5)) + guard !Task.isCancelled else { return } + finish("Сервер не ответил за 5 секунд.") + } + connection.start(queue: .main) + } + + func reset() { + finish(nil) + } + + private func finish(_ message: String?) { + timeout?.cancel() + timeout = nil + connection?.stateUpdateHandler = nil + connection?.cancel() + connection = nil + isChecking = false + status = message + } +}