import AppKit import SwiftUI @MainActor struct MenuBarServer: App { @StateObject private var model = ServerControl() var body: some Scene { MenuBarExtra { ServerPanel(model: model) } label: { Image(nsImage: Self.menuIcon) .renderingMode(.original) .accessibilityLabel("ezServer") } .menuBarExtraStyle(.window) } private static let menuIcon: NSImage = { let image = NSImage(size: NSSize(width: 18, height: 18), flipped: false) { bounds in let border = NSBezierPath(rect: bounds.insetBy(dx: 1.5, dy: 1.5)) NSColor.systemGray.setStroke() border.lineWidth = 1 border.stroke() let letter = NSBezierPath() letter.move(to: NSPoint(x: 5, y: 13)) letter.line(to: NSPoint(x: 9, y: 5)) letter.line(to: NSPoint(x: 13, y: 13)) letter.lineWidth = 2 letter.lineCapStyle = .round letter.lineJoinStyle = .round NSColor.systemRed.setStroke() letter.stroke() return true } image.isTemplate = false return image }() } @MainActor private final class ServerControl: ObservableObject { @Published var running = false @Published var starting = false @Published var stopping = false @Published var copying = false @Published var port = String(ServerConfiguration.defaultPort) @Published var notice: String? private var configuration: ServerConfiguration? private var server: LocalServer? private var generation = UUID() init() { do { let configuration = try ServerConfiguration() self.configuration = configuration let savedPort = UserDefaults.standard.string(forKey: "listenPort") if ProcessInfo.processInfo.environment["EZSERVER_PORT"] != nil || savedPort == "55005" { port = String(configuration.port) } else { port = savedPort ?? String(configuration.port) } start() } catch { notice = error.localizedDescription } } var imagesPath: String { configuration?.store.files.path ?? "" } var canChangeImages: Bool { !running && !starting && !stopping && !copying && ProcessInfo.processInfo.environment["EZSERVER_IMAGES_PARENT"] == nil } func start() { guard server == nil, !stopping, !copying, let configuration else { return } guard let portValue = UInt16(port), portValue > 0 else { notice = "Укажите порт от 1 до 65535." return } do { let api = LibraryAPI(store: configuration.store, secret: configuration.token) let server = try LocalServer(port: portValue, library: api) self.server = server starting = true notice = nil generation = UUID() let generation = self.generation server.start { [weak self] result in Task { @MainActor in guard let self, self.generation == generation else { return } self.starting = false switch result { case .success: self.running = true UserDefaults.standard.set(String(portValue), forKey: "listenPort") case let .failure(error): self.stop() self.notice = error.localizedDescription } } } } catch { notice = error.localizedDescription } } func stop() { guard let server, !stopping else { return } generation = UUID() starting = false running = false stopping = true server.stop { [weak self] in Task { @MainActor in self?.server = nil self?.stopping = false } } } func chooseImagesFolder() { guard canChangeImages, let configuration else { return } let panel = NSOpenPanel() panel.canChooseFiles = false panel.canChooseDirectories = true panel.canCreateDirectories = true panel.message = "Выберите папку, в которой EzServer создаст каталог Files." guard panel.runModal() == .OK, let url = panel.url else { return } let parent = url.resolvingSymlinksInPath().standardizedFileURL guard parent.path != configuration.store.files.deletingLastPathComponent().path else { return } guard !parent.path.hasPrefix(configuration.store.files.path + "/"), parent.path != configuration.store.files.path else { notice = "Выберите папку вне текущего каталога Files." return } copying = true notice = nil Task { defer { copying = false } do { let store = configuration.store try await Task.detached { try store.copyImages(to: parent) }.value self.configuration = try ServerConfiguration(imagesParent: parent) UserDefaults.standard.set(parent.path, forKey: "imagesParent") notice = "Снимки скопированы. Прежняя папка сохранена." } catch { notice = error.localizedDescription } } } func openConsole() { guard running, let port = UInt16(port), let url = URL(string: "http://127.0.0.1:\(port)/webconsole") else { return } NSWorkspace.shared.open(url) } } private struct ServerPanel: View { @ObservedObject var model: ServerControl var body: some View { VStack(alignment: .leading, spacing: 14) { HStack(spacing: 10) { Image(systemName: "externaldrive.fill") .font(.system(size: 17, weight: .medium)) .foregroundStyle(Color.accentColor) .frame(width: 34, height: 34) .background(Color.accentColor.opacity(0.12), in: RoundedRectangle(cornerRadius: 8)) Text("ezServer") .font(.title3.weight(.semibold)) .accessibilityAddTraits(.isHeader) Spacer() Label(serverStatus, systemImage: "circle.fill") .font(.caption.weight(.medium)) .foregroundStyle(model.running ? Color.green : Color.secondary) } Divider() HStack { Text("Порт") TextField(String(ServerConfiguration.defaultPort), text: $model.port) .frame(width: 75) .disabled(model.running || model.starting || model.stopping) .accessibilityLabel("Порт HTTP") Spacer() Button(model.running || model.starting ? "Остановить" : "Запустить") { if model.running || model.starting { model.stop() } else { model.start() } } .disabled(model.imagesPath.isEmpty || model.stopping || model.copying) } HStack { Text("Папка снимков") Spacer() Button("Выбрать…", action: model.chooseImagesFolder) .disabled(!model.canChangeImages || model.imagesPath.isEmpty) } Text(model.imagesPath) .font(.caption) .foregroundStyle(.secondary) .textSelection(.enabled) if model.copying { ProgressView("Копирование снимков…").controlSize(.small) } if let notice = model.notice { Text(notice).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) } Divider() Button(action: model.openConsole) { Label("Открыть Web Console", systemImage: "arrow.up.right.square") .frame(maxWidth: .infinity) } .buttonStyle(.borderedProminent) .controlSize(.large) .disabled(!model.running) } .padding(16) .frame(width: 360) } private var serverStatus: String { if model.starting { return "Запускается" } if model.stopping { return "Останавливается" } return model.running ? "Работает" : "Остановлен" } }