import AVFoundation import FoundationModels import PhotosUI import SwiftUI import UIKit import UniformTypeIdentifiers extension ComposeView { var canPublish: Bool { (!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty || video != nil) && text.count <= characterLimit } var canGenerateAltText: Bool { #if DEBUG let arguments = ProcessInfo.processInfo.arguments if let altTextTestMode { return altTextTestMode != "unavailable" } if arguments.contains("-ui-testing") { return !arguments.contains("-ui-testing-alt-unavailable") } #endif return SystemLanguageModel.default.isAvailable } var attachmentStrip: some View { ScrollView(.horizontal) { HStack(spacing: 12) { if video != nil { ZStack(alignment: .topTrailing) { Label("Video", systemImage: "video.fill") .frame(width: 132, height: 132) .background( Color(uiColor: .secondarySystemBackground), in: RoundedRectangle(cornerRadius: 12)) Button { video = nil } label: { Image(systemName: "xmark.circle.fill") .font(.title2) .symbolRenderingMode(.palette) .foregroundStyle(.white, .black.opacity(0.65)) } .padding(6) .accessibilityLabel("Remove video") } .accessibilityIdentifier("videoAttachment") } ForEach(Array(attachments.enumerated()), id: \.element.id) { index, attachment in VStack(alignment: .leading, spacing: 6) { Button { altTextReview = AltTextReview( id: attachment.id, originalText: attachment.altText, draft: attachment.altText) } label: { AttachmentThumbnail(attachment: attachment, contentMode: .fill) .frame(width: 132, height: 132) .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) } .buttonStyle(.plain) .accessibilityLabel("Edit alt text for image \(index + 1)") .accessibilityIdentifier("editAltText-\(index)") .overlay(alignment: .topTrailing) { Button { attachments.remove(at: index) } label: { Image(systemName: "xmark.circle.fill") .font(.title2) .symbolRenderingMode(.palette) .foregroundStyle(.white, .black.opacity(0.65)) } .padding(6) .accessibilityLabel("Remove image \(index + 1)") } } } } .padding(.horizontal, 16) .padding(.vertical, 12) } .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("imageAttachments") .disabled(isComposerBusy) } func contextRow(title: String, postID: String, isQuote: Bool) -> some View { let post = model.post(id: postID).flatMap { model.canShowTimelineContent($0) ? $0 : nil } return ContextCard( kind: isQuote ? .quote : .reply, title: title, showsHeader: false, openPost: {}, content: { HStack(spacing: 8) { Label( post.map { "\(title) \(displayPreferences.name($0.author))" } ?? title, systemImage: isQuote ? "quote.bubble" : "arrow.turn.down.right" ) .frame(maxWidth: .infinity, alignment: .leading) if let post { if let date = post.createdAt { PostTimestamp(date: date) .fixedSize() } AuthorAvatar(author: post.author, size: 24) } } .appFont(.subheadline, weight: .medium) .foregroundStyle(isQuote ? AppPalette.quote : AppPalette.reply) Text( PostTextFacets.render( post?.text ?? "Post preview unavailable", facets: post?.facets ?? [], linksEnabled: false ) ) .appFont(.subheadline) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("composeContextText-\(postID)") } ) .padding(.horizontal, 16) .accessibilityElement(children: .contain) } func altTextBinding(for id: UUID) -> Binding { Binding( get: { attachments.first(where: { $0.id == id })?.altText ?? "" }, set: { newValue in guard let index = attachments.firstIndex(where: { $0.id == id }) else { return } attachments[index] = ImageAttachment( id: id, data: attachments[index].data, altText: newValue, mimeType: attachments[index].mimeType) } ) } } struct AttachmentThumbnail: View { let attachment: ImageAttachment var contentMode: ContentMode = .fit @State private var image: UIImage? var body: some View { Group { if let image { Image(uiImage: image).resizable().aspectRatio(contentMode: contentMode) } else { Color(uiColor: .systemGray5) } } .task(id: attachment.id) { image = nil let decoded = await ImageDecodeQueue.shared.decode(attachment.data) guard !Task.isCancelled else { return } image = decoded } } } extension ComposeView { func loadMedia(_ items: [PhotosPickerItem]) async { isLoadingImages = true defer { isLoadingImages = false selectedItems = [] } let movieItems = items.filter { $0.supportedContentTypes.contains { $0.conforms(to: .movie) } } guard movieItems.isEmpty || (items.count == 1 && attachments.isEmpty && video == nil) else { mediaError = "Choose one video or up to ten photos." return } if let item = movieItems.first { guard let data = try? await item.loadTransferable(type: Data.self) else { mediaError = "The video could not be read. Try again." return } video = await prepareVideo(data) } else { for item in items.prefix(max(0, imageLimit - attachments.count)) { guard let data = try? await item.loadTransferable(type: Data.self), addImage(data) else { mediaError = "A photo could not be read. Try again." continue } } } } func loadPastedMedia(_ providers: [NSItemProvider]) async { guard !isLoadingImages, !model.isPublishing else { return } isLoadingImages = true defer { isLoadingImages = false } let movies = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.movie.identifier) } guard movies.isEmpty || (providers.count == 1 && attachments.isEmpty && video == nil), video == nil, attachments.count + providers.count <= imageLimit else { mediaError = "Choose one video or up to ten photos." return } for provider in providers { let isMovie = provider.hasItemConformingToTypeIdentifier(UTType.movie.identifier) let type = isMovie ? UTType.movie.identifier : UTType.image.identifier do { let data: Data = try await withCheckedThrowingContinuation { continuation in provider.loadDataRepresentation(forTypeIdentifier: type) { data, error in if let data { continuation.resume(returning: data) } else { continuation.resume(throwing: error ?? CocoaError(.fileReadCorruptFile)) } } } if isMovie { video = await prepareVideo(data) } else if !addImage(data) { mediaError = "A photo could not be read. Try again." } } catch { mediaError = "The media could not be read. Try again." } } } func acknowledgeSharedImport() async { guard let sharedImport else { return } do { try await SharedImportStore.acknowledge(sharedImport) } catch { mediaError = "The shared items could not be cleared. They will appear again when you open Old Fella." } } func addSharedMedia(_ items: [SharedImport.Attachment]) async { guard !items.isEmpty else { return } isLoadingImages = true defer { isLoadingImages = false } for item in items { switch item.kind { case .image: if !addImage(item.data) { mediaError = "A photo could not be read. Try again." } case .video: video = await prepareVideo(item.data) } } } func prepareVideo(_ data: Data) async -> VideoAttachment? { do { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } let input = directory.appendingPathComponent("input.mov") let output = directory.appendingPathComponent("output.mp4") try await Task.detached(priority: .userInitiated) { try data.write(to: input, options: .atomic) }.value let asset = AVURLAsset(url: input) guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else { throw CocoaError(.fileReadCorruptFile) } try await exporter.export(to: output, as: .mp4) let result = try await Task.detached(priority: .userInitiated) { try Data(contentsOf: output, options: .mappedIfSafe) }.value return VideoAttachment(data: result, mimeType: "video/mp4") } catch { mediaError = "The video could not be prepared. Try another video." return nil } } @discardableResult func addImage(_ data: Data) -> Bool { guard let image = UIImage(data: data), let jpeg = image.jpegData(compressionQuality: 0.88) else { return false } attachments.append(ImageAttachment(data: jpeg, mimeType: "image/jpeg")) return true } func publish() async { guard !isComposerBusy, !draftIsUncertain else { return } if let savedDraftID { isWorkingWithDrafts = true var pending = currentDraft pending.publishResultUnknown = true do { _ = try await model.saveSavedDraft(pending, id: savedDraftID) } catch { isWorkingWithDrafts = false draftError = NetworkFailure.message(for: error) return } isWorkingWithDrafts = false } let succeeded = await model.publish( text: text, replyTo: composerReplyTo, quotePostID: composerQuotePostID, images: attachments, video: video, draftID: compositionID) if succeeded { if let savedDraftID { isWorkingWithDrafts = true do { try await model.deleteSavedDraft(id: savedDraftID) } catch { clearComposer() isWorkingWithDrafts = false draftError = "The post was sent, but its saved draft could not be removed. " + NetworkFailure.message(for: error) return } isWorkingWithDrafts = false } clearComposer() if let onSharedPost { onSharedPost() } else { dismiss() } } else if let savedDraftID, !draftIsUncertain { isWorkingWithDrafts = true defer { isWorkingWithDrafts = false } do { _ = try await model.saveSavedDraft(currentDraft, id: savedDraftID) } catch { draftError = NetworkFailure.message(for: error) } } } }