From 62ca9e2f9ea6c8cfa4f46ebc90b9005d04cd1fc7 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sat, 21 Nov 2026 00:41:13 +0330 Subject: [PATCH 01/14] apple: size photos and videos by content and send them without metadata Photos are prepared once at attach, off the main thread, by one shared preparer: camera photos at 1600 px, screenshots and other images at 2560 px, JPEG 0.8, PNG only when a pixel is transparent. Pixels are written upright with no location, camera or time, and the color profile is kept. The upload path checks the file again, so older drafts are cleaned too. Camera video goes at 720p and 3 Mbps, screen recordings at 1080p up to 5 Mbps; H.264 within those limits is remuxed, and exports drop location and device. Nothing falls back to the raw file: a photo that can't be prepared goes as a file, a video that can't be prepared fails. The untouched original behind each attachment is kept for 3 days so the composer's Original toggle can send it as a document, metadata included. Replaces ImageCompression. --- .../InlineKit/Sources/InlineKit/Drafts2.swift | 30 +- .../Files/AttachmentMediaMaterializer.swift | 128 +++++- .../Sources/InlineKit/Files/FileCache.swift | 120 +++--- .../Sources/InlineKit/Files/FileUpload.swift | 63 +-- .../InlineKit/Files/ImageCompression.swift | 224 ----------- .../Files/MediaSendPreparation.swift | 370 ++++++++++++++++++ .../InlineKit/Files/OriginalMediaStore.swift | 145 +++++++ .../InlineKit/Files/VideoCompression.swift | 286 +++++--------- .../MediaSendPreparationTests.swift | 240 ++++++++++++ .../VideoCompressionTests.swift | 95 +++-- .../InlineMacUI/DraftAttachmentImporter.swift | 35 +- .../DraftAttachmentImporterTests.swift | 11 +- 12 files changed, 1174 insertions(+), 573 deletions(-) delete mode 100644 apple/InlineKit/Sources/InlineKit/Files/ImageCompression.swift create mode 100644 apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift create mode 100644 apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift create mode 100644 apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift diff --git a/apple/InlineKit/Sources/InlineKit/Drafts2.swift b/apple/InlineKit/Sources/InlineKit/Drafts2.swift index 72a85713a6..5625030944 100644 --- a/apple/InlineKit/Sources/InlineKit/Drafts2.swift +++ b/apple/InlineKit/Sources/InlineKit/Drafts2.swift @@ -395,36 +395,32 @@ public final class Drafts2: @unchecked Sendable { return attachment } + /// Adds a decoded image. Pass `sourceURL` when the image came from a file: the photo is then + /// prepared from the file itself, which keeps it available for sending as the original. @discardableResult public func addImage( peer: Peer, image: PlatformImage, - preferredFormat: ImageFormat? = nil, + sourceURL: URL? = nil, onComplete: Drafts2AttachmentCompletion? = nil ) -> String { - addImage( - peer: peer, - image: image, - preferredFormat: preferredFormat, - fallbackURL: nil, - onComplete: onComplete - ) + startMaterialization(peer: peer, prefix: "pending_photo") { + try await AttachmentMediaMaterializer.image(image, sourceURL: sourceURL) + } onComplete: { result in + onComplete?(result) + } } + /// Adds a photo from its encoded source without decoding it on the caller's side. @discardableResult - public func addImage( + public func addPhoto( peer: Peer, - image: PlatformImage, - preferredFormat: ImageFormat? = nil, - fallbackURL: URL?, + source: MediaSendPreparation.PhotoSource, + originalFileName: String? = nil, onComplete: Drafts2AttachmentCompletion? = nil ) -> String { startMaterialization(peer: peer, prefix: "pending_photo") { - try await AttachmentMediaMaterializer.image( - image, - preferredFormat: preferredFormat, - sourceURL: fallbackURL - ) + try await AttachmentMediaMaterializer.photo(source, originalFileName: originalFileName) } onComplete: { result in onComplete?(result) } diff --git a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift index 31722c2989..9e4d13cf7b 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift @@ -1,29 +1,119 @@ import Foundation +import Logger /// Turns a selected attachment into its preferred rich representation without /// ever making that representation a requirement for retaining the source. public enum AttachmentMediaMaterializer { - public static func image( - _ image: PlatformImage, - preferredFormat: ImageFormat? = nil, - sourceURL: URL? = nil + /// Prepares a picked photo for sending (see `MediaSendPreparation`) and keeps its untouched + /// source for the composer's Original toggle. Images too thin or too small to show as a photo + /// go as a file, as before. + public static func photo( + _ source: MediaSendPreparation.PhotoSource, + originalFileName: String? = nil, + content: MediaSendPreparation.PhotoContent? = nil ) async throws -> FileMediaItem { try await withBareFileFallback { - .photo(try FileCache.savePhoto(image: image, preferredFormat: preferredFormat)) + try await detached { + OriginalMediaStore.sweep() + if let size = MediaSendPreparation.pixelSize(of: source), + MediaSendPreparation.shouldSendAsDocument(width: size.width, height: size.height) + { + return try await document(from: source, fileName: originalFileName) + } + let photo = FileMediaItem.photo(try FileCache.savePreparedPhoto(source, content: content)) + retainOriginal(source, fileName: originalFileName, content: content, for: photo) + return photo + } } fallback: { - if let sourceURL { - return .document(try await FileCache.saveDocumentWithThumbnail(url: sourceURL)) + try await document(from: source, fileName: originalFileName) + } + } + + /// A decoded image, prepared from `sourceURL` when the encoded file behind it is known. + public static func image(_ image: PlatformImage, sourceURL: URL? = nil) async throws -> FileMediaItem { + if let sourceURL { + return try await photo(.file(sourceURL), originalFileName: sourceURL.lastPathComponent) + } + return try await photo(.platformImage(image)) + } + + static func retainOriginal( + _ source: MediaSendPreparation.PhotoSource, + fileName: String?, + content: MediaSendPreparation.PhotoContent? = nil, + for media: FileMediaItem + ) { + do { + switch source { + case let .file(url): + try OriginalMediaStore.retain(copyOf: url, fileName: fileName ?? url.lastPathComponent, for: media) + case let .data(data): + let name = fileName ?? "Photo." + (MediaSendPreparation.fileExtension(of: data) ?? "jpg") + try OriginalMediaStore.retain(data: data, fileName: name, for: media) + case .cgImage, .platformImage: + // A camera capture handed over as pixels has no file behind it: keep a full-resolution + // copy so Original still sends every pixel. Other pixel-only images (pastes, stickers) + // send the prepared photo even with Original on. + guard content == .camera else { break } + let full = try MediaSendPreparation.preparePhoto( + source, + content: .camera, + target: .init(maxPixelSize: 100_000, jpegQuality: 0.95) + ) + try OriginalMediaStore.retain(data: full.data, fileName: fileName ?? "Photo" + full.format.toExt(), for: media) } + } catch { + Log.shared.warning("Couldn't keep the original photo for sending as a file: \(error.localizedDescription)") + } + } - let format = preferredFormat ?? .png - let fileName = "image-" + UUID().uuidString + format.toExt() - let (_, temporaryURL) = try image.save( - to: FileHelpers.getTrueTemporaryDirectory(), - withName: fileName, - format: format + /// The source as a file and sent as a document, untouched where an encoded source exists. + private static func document( + from source: MediaSendPreparation.PhotoSource, + fileName: String? + ) async throws -> FileMediaItem { + switch source { + case let .file(url): + return .document(try await FileCache.saveDocumentWithThumbnail(url: url)) + case let .data(data): + let name = fileName ?? "image-\(UUID().uuidString)." + (MediaSendPreparation.fileExtension(of: data) ?? "png") + return try await documentFromTemporaryFile(named: name) { try data.write(to: $0, options: .atomic) } + case .cgImage, .platformImage: + // Full resolution: a long screenshot sent as a file must stay readable. + let full = try MediaSendPreparation.preparePhoto( + source, + target: .init(maxPixelSize: 100_000, jpegQuality: 0.92) ) - defer { try? FileManager.default.removeItem(at: temporaryURL) } - return .document(try await FileCache.saveDocumentWithThumbnail(url: temporaryURL)) + let name = (fileName.map { ($0 as NSString).deletingPathExtension } ?? "image-\(UUID().uuidString)") + + full.format.toExt() + return try await documentFromTemporaryFile(named: name) { try full.data.write(to: $0, options: .atomic) } + } + } + + private static func documentFromTemporaryFile( + named name: String, + write: (URL) throws -> Void + ) async throws -> FileMediaItem { + let folder = FileHelpers.getTrueTemporaryDirectory().appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let url = folder.appendingPathComponent(OriginalMediaStore.safeFileName(name)) + try write(url) + return .document(try await FileCache.saveDocumentWithThumbnail(url: url)) + } + + /// Runs decode and disk work off the caller's thread, cancelling with the caller. + private static func detached( + _ work: @escaping @Sendable () async throws -> Value + ) async throws -> Value { + let worker = Task.detached(priority: .userInitiated) { + try Task.checkCancellation() + return try await work() + } + return try await withTaskCancellationHandler { + try await worker.value + } onCancel: { + worker.cancel() } } @@ -32,7 +122,13 @@ public enum AttachmentMediaMaterializer { thumbnail: PlatformImage? = nil ) async throws -> FileMediaItem { try await withBareFileFallback { - .video(try await FileCache.saveVideo(url: url, thumbnail: thumbnail)) + let video = FileMediaItem.video(try await FileCache.saveVideo(url: url, thumbnail: thumbnail)) + do { + try OriginalMediaStore.retain(copyOf: url, for: video) + } catch { + Log.shared.warning("Couldn't keep the original video for sending as a file: \(error.localizedDescription)") + } + return video } fallback: { .document(try await FileCache.saveDocumentWithThumbnail(url: url)) } diff --git a/apple/InlineKit/Sources/InlineKit/Files/FileCache.swift b/apple/InlineKit/Sources/InlineKit/Files/FileCache.swift index afdeab31b0..3aaf2eb017 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/FileCache.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/FileCache.swift @@ -715,55 +715,44 @@ public actor FileCache: Sendable { // MARK: - Local Saves - public static func savePhoto( - image: PlatformImage, - preferredFormat: ImageFormat? = nil, - optimize: Bool = false + /// Prepares a photo the way it is sent (resized for its content, upright, no metadata; see + /// `MediaSendPreparation`) and stores the result as a local photo. The stored file is the exact + /// body that is later staged, hashed and uploaded. Does decode and disk work: call off the main thread. + public static func savePreparedPhoto( + _ source: MediaSendPreparation.PhotoSource, + content: MediaSendPreparation.PhotoContent? = nil, + target: MediaSendPreparation.PhotoTarget? = nil ) throws -> InlineKit.PhotoInfo { - // Info - get actual pixel dimensions, not just logical size - let actualSize: CGSize - #if os(macOS) - actualSize = getActualPixelSize(from: image) - #else - // On iOS, image.size already gives pixel dimensions - actualSize = image.size - #endif - - let w = Int(actualSize.width) - let h = Int(actualSize.height) - let format: ImageFormat = preferredFormat ?? (hasAlphaChannel(image: image) ? .png : .jpeg) - let protoFormat = format.toProtocol() - let ext = protoFormat.toExtension() - let mimeType = protoFormat.toMimeType() - let fileName = UUID().uuidString + ext - - Log.shared - .debug( - "Saving photo \(fileName) with format \(format) and mimeType \(mimeType), w: \(w), h: \(h), optimize: \(optimize)" - ) - - // Save in files - let directory = FileHelpers.getLocalCacheDirectory(for: .photos) - guard let (localPath, _) = try? image.save(to: directory, withName: fileName, format: format, optimize: optimize) - else { throw FileCacheError.failedToSave } - let fileURL = directory.appendingPathComponent( - localPath - ) - let fileSize = FileHelpers.getFileSize(at: fileURL) - - // Save in DB - let photoInfo = try AppDatabase.shared.dbWriter.write { db in - try Photo.createLocalPhoto( - db, - format: format, - localPath: localPath, - fileSize: fileSize, - width: w, - height: h - ) + let prepared = try MediaSendPreparation.preparePhoto(source, content: content, target: target) + let localPath = UUID().uuidString + prepared.format.toExt() + let fileURL = FileHelpers.getLocalCacheDirectory(for: .photos).appendingPathComponent(localPath) + try prepared.data.write(to: fileURL, options: .atomic) + do { + return try AppDatabase.shared.dbWriter.write { db in + try Photo.createLocalPhoto( + db, + format: prepared.format, + localPath: localPath, + fileSize: prepared.data.count, + width: prepared.width, + height: prepared.height + ) + } + } catch { + try? removeLocalCacheFile(fileURL) + throw error } + } - return photoInfo + /// Stores a decoded image as a local photo, prepared like any sent photo. Prefer + /// `savePreparedPhoto(.file(_:))` when the encoded source exists: it reads the camera + /// details that pick the size and never decodes more pixels than it sends. + public static func savePhoto( + image: PlatformImage, + content: MediaSendPreparation.PhotoContent? = nil, + target: MediaSendPreparation.PhotoTarget? = nil + ) throws -> InlineKit.PhotoInfo { + try savePreparedPhoto(.platformImage(image), content: content, target: target) } // Note: this does synchronous disk/thumbnail/DB work; avoid calling on MainActor for large assets. @@ -827,7 +816,7 @@ public actor FileCache: Sendable { try Task.checkCancellation() let thumbnailInfo: PhotoInfo? = if let image = thumbImage { - try? savePhoto(image: image, preferredFormat: .jpeg) + try? savePhoto(image: image, target: MediaSendPreparation.videoThumbnailTarget) } else { nil } let video = try MediaHelpers.shared.createLocalVideo( @@ -863,7 +852,7 @@ public actor FileCache: Sendable { try FileManager.default.moveItem(at: conversion.url, to: localUrl) let thumbnailInfo: PhotoInfo? = if let thumbnail = conversion.thumbnail { - try? savePhoto(image: thumbnail, preferredFormat: .jpeg) + try? savePhoto(image: thumbnail, target: MediaSendPreparation.videoThumbnailTarget) } else { nil } @@ -1099,6 +1088,41 @@ public actor FileCache: Sendable { } } + /// Removes a photo that was prepared locally and never sent (its file and rows). + public static func discardLocalPhoto(_ photoInfo: PhotoInfo) async { + let photoDirectory = FileHelpers.getLocalCacheDirectory(for: .photos) + do { + try await Task.detached(priority: .utility) { + try discardLocalThumbnail(photoInfo, database: AppDatabase.shared, photoDirectory: photoDirectory) + }.value + } catch { + Log.shared.error("Failed to discard unsent local photo", error: error) + } + } + + /// Removes a video that was copied locally and never sent (its file, thumbnail and rows). + public static func discardLocalVideo(_ videoInfo: VideoInfo) async { + let videoDirectory = FileHelpers.getLocalCacheDirectory(for: .videos) + let photoDirectory = FileHelpers.getLocalCacheDirectory(for: .photos) + do { + try await Task.detached(priority: .utility) { + guard videoInfo.video.videoId < 0 else { return } + try AppDatabase.shared.dbWriter.write { db in + _ = try Video.filter(Video.Columns.videoId == videoInfo.video.videoId).deleteAll(db) + } + if let thumbnail = videoInfo.thumbnail { + try discardLocalThumbnail(thumbnail, database: AppDatabase.shared, photoDirectory: photoDirectory) + } + if let localPath = videoInfo.video.localPath, + let fileURL = localCacheURL(localPath: localPath, directory: videoDirectory) { + try removeLocalCacheFile(fileURL) + } + }.value + } catch { + Log.shared.error("Failed to discard unsent local video", error: error) + } + } + static func discardLocalDocument(_ documentInfo: DocumentInfo) async { await discardLocalDocument( documentInfo, diff --git a/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift b/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift index 9ebd3721fb..5770886526 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift @@ -687,17 +687,20 @@ public actor FileUploader { uploadUrl = staged break } - do { - let options = mimeType.lowercased().contains("png") - ? ImageCompressionOptions.defaultPNG - : ImageCompressionOptions.defaultPhoto - uploadUrl = try await ImageCompressor.shared.compressImage(at: localUrl, options: options) - if uploadUrl != localUrl { - temporaryArtifacts.append(uploadUrl) - } - } catch { - // Fallback to original URL if compression fails - uploadUrl = localUrl + // Photos are prepared when attached, so this is normally a header read. Anything still too + // large or carrying camera, place or time details (a draft from an older build) is prepared + // here, before staging and hashing; it is never uploaded as it is. + if MediaSendPreparation.photoNeedsPreparation(at: localUrl) { + let prepared = try await Task.detached(priority: .userInitiated) { + try MediaSendPreparation.preparePhoto(.file(localUrl)) + }.value + let preparedURL = FileHelpers.getTrueTemporaryDirectory() + .appendingPathComponent("inline-upload-photo-\(UUID().uuidString)\(prepared.format.toExt())") + try prepared.data.write(to: preparedURL, options: .atomic) + temporaryArtifacts.append(preparedURL) + uploadUrl = preparedURL + uploadMimeType = prepared.format.toMimeType() + uploadFileName = (fileName as NSString).deletingPathExtension + prepared.format.toExt() } case .video: let prepared = try await prepareVideoForUpload( @@ -1189,17 +1192,18 @@ public actor FileUploader { private func prepareVideoForUploadUnstaged( uploadId: String, localUrl: URL, inputMimeType: String, metadata: ApiClient.VideoUploadMetadata? ) async throws -> PreparedVideoUploadPayload { - let requiresMp4Output = inputMimeType.lowercased() != "video/mp4" - let resolvedMetadata = try await resolveVideoUploadMetadata( localUrl: localUrl, fallback: metadata ) + // Every video is re-encoded or remuxed into a new file without location or device details; + // if that fails the upload fails rather than send the original. + let content = await VideoCompressor.content(of: localUrl) do { let result = try await VideoCompressor.shared.compressVideo( at: localUrl, - options: VideoCompressionOptions.uploadDefault(forceTranscode: requiresMp4Output) + options: .upload(for: content) ) let compressedMetadata = ApiClient.VideoUploadMetadata( width: result.width, @@ -1210,43 +1214,18 @@ public actor FileUploader { isAnimated: resolvedMetadata.isAnimated, hasAudio: resolvedMetadata.hasAudio ) - let preparedFileName = "\(uploadId).mp4" return PreparedVideoUploadPayload( url: result.url, - fileName: preparedFileName, + fileName: "\(uploadId).mp4", mimeType: "video/mp4", metadata: compressedMetadata, cleanupAfterUpload: true ) } catch is CancellationError { throw FileUploadError.uploadCancelled - } catch VideoCompressionError.compressionNotNeeded { - return PreparedVideoUploadPayload( - url: localUrl, - fileName: localUrl.lastPathComponent, - mimeType: inputMimeType, - metadata: resolvedMetadata, - cleanupAfterUpload: false - ) - } catch VideoCompressionError.compressionNotEffective { - return PreparedVideoUploadPayload( - url: localUrl, - fileName: localUrl.lastPathComponent, - mimeType: inputMimeType, - metadata: resolvedMetadata, - cleanupAfterUpload: false - ) } catch { - Log.shared.warning( - "[FileUploader] Video preprocessing failed for \(uploadId); uploading original (\(error.localizedDescription))" - ) - return PreparedVideoUploadPayload( - url: localUrl, - fileName: localUrl.lastPathComponent, - mimeType: inputMimeType, - metadata: resolvedMetadata, - cleanupAfterUpload: false - ) + Log.shared.error("[FileUploader] Video preparation failed for \(uploadId)", error: error) + throw FileUploadError.invalidVideo } } diff --git a/apple/InlineKit/Sources/InlineKit/Files/ImageCompression.swift b/apple/InlineKit/Sources/InlineKit/Files/ImageCompression.swift deleted file mode 100644 index 024e31310a..0000000000 --- a/apple/InlineKit/Sources/InlineKit/Files/ImageCompression.swift +++ /dev/null @@ -1,224 +0,0 @@ -import Foundation -import Logger - -#if canImport(AppKit) -import AppKit -#elseif canImport(UIKit) -import UIKit -#endif - -public enum ImageCompressionError: Error { - case invalidImage - case compressionFailed - case fileCreationFailed - case compressionNotEffective -} - -public struct ImageCompressionOptions: Sendable { - public let maxDimension: CGFloat - public let compressionQuality: CGFloat - public let isPNG: Bool - public let minimumCompressionRatio: Double // Minimum ratio of compressed size to original size - - public static let defaultPhoto = ImageCompressionOptions( - maxDimension: 1_600, - compressionQuality: 0.87, - isPNG: false, - minimumCompressionRatio: 0.8 - ) - public static let defaultPNG = ImageCompressionOptions( - maxDimension: 1_280, - compressionQuality: 0.9, - isPNG: true, - minimumCompressionRatio: 0.9 - ) -} - -public actor ImageCompressor { - public static let shared = ImageCompressor() - private let log = Log.scoped("ImageCompressor") - - private init() {} - - public func compressImage(at sourceURL: URL, options: ImageCompressionOptions) async throws -> URL { - log.debug("Starting image compression for \(sourceURL.lastPathComponent)") - - // Get original file size - let originalSize = try FileManager.default.attributesOfItem(atPath: sourceURL.path)[.size] as? Int64 ?? 0 - log.debug("Original file size: \(ByteCountFormatter.string(fromByteCount: originalSize, countStyle: .file))") - - #if canImport(AppKit) - guard let image = NSImage(contentsOf: sourceURL) else { - log.error("Failed to load image from URL", error: ImageCompressionError.invalidImage) - throw ImageCompressionError.invalidImage - } - #elseif canImport(UIKit) - guard let image = UIImage(contentsOfFile: sourceURL.path) else { - log.error("Failed to load image from URL", error: ImageCompressionError.invalidImage) - throw ImageCompressionError.invalidImage - } - #endif - - log.debug("Original image size: \(image.size.width)x\(image.size.height)") - - // Resize image if needed - let resizedImage = try await resizeImage(image, maxDimension: options.maxDimension) - log.debug("Resized image size: \(resizedImage.size.width)x\(resizedImage.size.height)") - - // Create temporary file URL - let tempDir = FileManager.default.temporaryDirectory - let fileName = "compressed_\(UUID().uuidString).\(options.isPNG ? "png" : "jpg")" - let outputURL = tempDir.appendingPathComponent(fileName) - log.debug("Created temporary file at: \(outputURL.path)") - - // Compress and save - #if canImport(AppKit) - // Create bitmap representation with exact dimensions - guard let bitmapRep = NSBitmapImageRep( - bitmapDataPlanes: nil, - pixelsWide: Int(resizedImage.size.width), - pixelsHigh: Int(resizedImage.size.height), - bitsPerSample: 8, - samplesPerPixel: 4, - hasAlpha: true, - isPlanar: false, - colorSpaceName: .deviceRGB, - bytesPerRow: 0, - bitsPerPixel: 0 - ) else { - log.error("Failed to create bitmap representation", error: ImageCompressionError.compressionFailed) - throw ImageCompressionError.compressionFailed - } - - // Draw the image into the bitmap context with high quality - NSGraphicsContext.saveGraphicsState() - NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmapRep) - NSGraphicsContext.current?.imageInterpolation = .high - resizedImage.draw(at: .zero, from: .zero, operation: .copy, fraction: 1.0) - NSGraphicsContext.restoreGraphicsState() - - // Get the data in the specified format with optimized properties - let properties: [NSBitmapImageRep.PropertyKey: Any] = [ - .compressionFactor: options.compressionQuality, - .interlaced: false, - ] - - guard let imageData = bitmapRep.representation( - using: options.isPNG ? .png : .jpeg, - properties: properties - ) else { - log.error("Failed to generate image data", error: ImageCompressionError.compressionFailed) - throw ImageCompressionError.compressionFailed - } - - try imageData.write(to: outputURL) - #elseif canImport(UIKit) - if options.isPNG { - guard let pngData = resizedImage.pngData() else { - log.error("Failed to compress PNG image", error: ImageCompressionError.compressionFailed) - throw ImageCompressionError.compressionFailed - } - try pngData.write(to: outputURL) - } else { - guard let jpegData = resizedImage.jpegData(compressionQuality: options.compressionQuality) else { - log.error("Failed to compress JPEG image", error: ImageCompressionError.compressionFailed) - throw ImageCompressionError.compressionFailed - } - try jpegData.write(to: outputURL) - } - #endif - - // Check if compression was effective - let compressedSize = try FileManager.default.attributesOfItem(atPath: outputURL.path)[.size] as? Int64 ?? 0 - let compressionRatio = Double(compressedSize) / Double(originalSize) - - log.debug(""" - Compression results: - - Original size: \(ByteCountFormatter.string(fromByteCount: originalSize, countStyle: .file)) - - Compressed size: \(ByteCountFormatter.string(fromByteCount: compressedSize, countStyle: .file)) - - Compression ratio: \(String(format: "%.2f", compressionRatio)) - """) - - // If compression didn't reduce size enough, return original - if compressionRatio > options.minimumCompressionRatio { - log - .warning( - "Compression not effective enough (ratio: \(String(format: "%.2f", compressionRatio))), using original image" - ) - try? FileManager.default.removeItem(at: outputURL) - throw ImageCompressionError.compressionNotEffective - } - - log.debug("Successfully compressed \(options.isPNG ? "PNG" : "JPEG") image to \(outputURL.path)") - return outputURL - } - - private func resizeImage(_ image: PlatformImage, maxDimension: CGFloat) async throws -> PlatformImage { - let size = image.size - let widthRatio = maxDimension / size.width - let heightRatio = maxDimension / size.height - let ratio = min(widthRatio, heightRatio) - - // If image is already smaller than max dimension, return original - if ratio >= 1 { - log.debug("Image already smaller than max dimension (\(maxDimension)), skipping resize") - return image - } - - let newSize = CGSize(width: size.width * ratio, height: size.height * ratio) - log.debug("Resizing image from \(size.width)x\(size.height) to \(newSize.width)x\(newSize.height)") - - #if canImport(AppKit) - // Create a new image with the desired size - let resizedImage = NSImage(size: newSize) - - // Create bitmap representation with exact dimensions - guard let bitmapRep = NSBitmapImageRep( - bitmapDataPlanes: nil, - pixelsWide: Int(newSize.width), - pixelsHigh: Int(newSize.height), - bitsPerSample: 8, - samplesPerPixel: 4, - hasAlpha: true, - isPlanar: false, - colorSpaceName: .deviceRGB, - bytesPerRow: 0, - bitsPerPixel: 0 - ) else { - log.error("Failed to create bitmap representation for resizing", error: ImageCompressionError.compressionFailed) - throw ImageCompressionError.compressionFailed - } - - // Draw the image into the bitmap context with high quality - NSGraphicsContext.saveGraphicsState() - NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmapRep) - NSGraphicsContext.current?.imageInterpolation = .high - image.draw( - in: NSRect(origin: .zero, size: newSize), - from: NSRect(origin: .zero, size: size), - operation: .copy, - fraction: 1.0 - ) - NSGraphicsContext.restoreGraphicsState() - - // Create final image from bitmap - let finalImage = NSImage(size: newSize) - finalImage.addRepresentation(bitmapRep) - - log.debug("Resized image size: \(finalImage.size.width)x\(finalImage.size.height)") - return finalImage - #elseif canImport(UIKit) - let format = UIGraphicsImageRendererFormat() - format.scale = 1.0 // Force 1:1 scale to ensure exact dimensions - format.preferredRange = .standard - - let renderer = UIGraphicsImageRenderer(size: newSize, format: format) - let resizedImage = renderer.image { _ in - image.draw(in: CGRect(origin: .zero, size: newSize)) - } - - log.debug("Resized image scale: \(resizedImage.scale), size: \(resizedImage.size)") - return resizedImage - #endif - } -} diff --git a/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift b/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift new file mode 100644 index 0000000000..da012aeb8e --- /dev/null +++ b/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift @@ -0,0 +1,370 @@ +import CoreGraphics +import Foundation +import ImageIO +import UniformTypeIdentifiers + +#if canImport(UIKit) +import UIKit +#elseif canImport(AppKit) +import AppKit +#endif + +/// Turns a picked photo into the bytes Inline sends, the way Telegram's compressed send does: +/// one decode, resized for what the photo is, pixels upright, and no metadata written. Camera +/// photos rarely need more than a full-screen view and are expensive in bytes; screenshots and +/// other graphics need resolution for small text and stay cheap, so each gets its own size. +/// +/// Native uploads are published byte for byte, so this is the only place metadata is removed for +/// photos sent from the apps. The prepared file is what gets staged, hashed and uploaded. +public enum MediaSendPreparation { + /// What a photo shows, which decides how large it is sent. + public enum PhotoContent: String, Sendable, Equatable { + /// Taken by a camera: the file names the camera that made it. + case camera + /// Screenshots, pasted, exported or downloaded images: no camera recorded in the file. + case graphic + } + + public struct PhotoTarget: Sendable, Equatable { + public let maxPixelSize: Int + public let jpegQuality: Double + } + + public static func target(for content: PhotoContent) -> PhotoTarget { + switch content { + case .camera: PhotoTarget(maxPixelSize: 1_600, jpegQuality: 0.8) + case .graphic: PhotoTarget(maxPixelSize: 2_560, jpegQuality: 0.8) + } + } + + /// Video thumbnails show in a bubble and the server makes smaller copies from them. + public static let videoThumbnailTarget = PhotoTarget(maxPixelSize: 1_280, jpegQuality: 0.8) + + /// The longest edge any prepared photo can have. Anything larger was not prepared here. + static var largestPreparedPixelSize: Int { target(for: .graphic).maxPixelSize } + + public enum PhotoSource: @unchecked Sendable { + /// A file on disk, read without decoding more than the resized output needs. + case file(URL) + /// Encoded image bytes, such as a pasteboard or Photos library representation. + case data(Data) + /// Pixels that are already upright and carry no metadata. + case cgImage(CGImage) + /// A decoded platform image, drawn upright. Used when no encoded source exists. + case platformImage(PlatformImage) + } + + public struct PreparedPhoto: Sendable { + public let data: Data + public let format: ImageFormat + public let width: Int + public let height: Int + public let content: PhotoContent + } + + public enum PreparationError: Error, Equatable { + case unreadableImage + case encodeFailed + } + + /// Prepares a photo for sending. `content` overrides the classification read from the file, + /// for callers that know better (a camera capture handed over as pixels, for example). + public static func preparePhoto( + _ source: PhotoSource, + content: PhotoContent? = nil, + target explicitTarget: PhotoTarget? = nil + ) throws -> PreparedPhoto { + switch source { + case let .file(url): + guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, sourceOptions) else { + throw PreparationError.unreadableImage + } + return try prepare(imageSource: imageSource, content: content, target: explicitTarget) + case let .data(data): + guard let imageSource = CGImageSourceCreateWithData(data as CFData, sourceOptions) else { + throw PreparationError.unreadableImage + } + return try prepare(imageSource: imageSource, content: content, target: explicitTarget) + case let .cgImage(image): + let resolved = content ?? .graphic + let target = explicitTarget ?? target(for: resolved) + let resized = try resize(image, maxPixelSize: target.maxPixelSize) + return try encode(resized, target: target, content: resolved) + case let .platformImage(image): + let resolved = content ?? .graphic + let target = explicitTarget ?? target(for: resolved) + guard let upright = renderUpright(image, maxPixelSize: target.maxPixelSize) else { + throw PreparationError.unreadableImage + } + return try encode(upright, target: target, content: resolved) + } + } + + /// Reads only the header: whether a photo file still needs preparing before it can be sent. + /// A file this type prepared is already within size and carries nothing identifying. + public static func photoNeedsPreparation(at url: URL) -> Bool { + guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, sourceOptions), + let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [CFString: Any] + else { + return true + } + let (width, height) = orientedPixelSize(properties) + if max(width, height) > largestPreparedPixelSize { return true } + if let orientation = properties[kCGImagePropertyOrientation] as? Int, orientation != 1 { return true } + return carriesIdentifyingMetadata(properties) + } + + /// Images too thin or too tiny to show as a photo are sent as files. The server rejects photos + /// with an aspect ratio over 20. + public static func shouldSendAsDocument(width: Int, height: Int) -> Bool { + let width = max(width, 1), height = max(height, 1) + let ratio = Double(max(width, height)) / Double(min(width, height)) + return ratio > 20 || (width < 50 && height < 50) + } + + /// Upright pixel size of a source, read from the header for encoded sources. + public static func pixelSize(of source: PhotoSource) -> (width: Int, height: Int)? { + let imageSource: CGImageSource? + switch source { + case let .file(url): + imageSource = CGImageSourceCreateWithURL(url as CFURL, sourceOptions) + case let .data(data): + imageSource = CGImageSourceCreateWithData(data as CFData, sourceOptions) + case let .cgImage(image): + return (image.width, image.height) + case let .platformImage(image): + #if canImport(UIKit) + return (Int((image.size.width * image.scale).rounded()), Int((image.size.height * image.scale).rounded())) + #else + let representation = image.representations.first { $0 is NSBitmapImageRep } + return (representation?.pixelsWide ?? Int(image.size.width), representation?.pixelsHigh ?? Int(image.size.height)) + #endif + } + guard let imageSource, + let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [CFString: Any] + else { + return nil + } + let size = orientedPixelSize(properties) + return size.width > 0 && size.height > 0 ? size : nil + } + + /// The usual file extension for encoded image bytes ("heic", "jpeg", "png"). + public static func fileExtension(of data: Data) -> String? { + guard let imageSource = CGImageSourceCreateWithData(data as CFData, sourceOptions), + let type = CGImageSourceGetType(imageSource) + else { + return nil + } + return UTType(type as String)?.preferredFilenameExtension + } + + // MARK: - Classification + + static func classify(_ properties: [CFString: Any]) -> PhotoContent { + let exif = properties[kCGImagePropertyExifDictionary] as? [CFString: Any] + if let comment = exif?[kCGImagePropertyExifUserComment] as? String, + comment.trimmingCharacters(in: .whitespacesAndNewlines).caseInsensitiveCompare("Screenshot") == .orderedSame + { + return .graphic + } + let tiff = properties[kCGImagePropertyTIFFDictionary] as? [CFString: Any] + if nonEmpty(tiff?[kCGImagePropertyTIFFMake]) || nonEmpty(tiff?[kCGImagePropertyTIFFModel]) { + return .camera + } + if nonEmpty(exif?[kCGImagePropertyExifLensModel]) || exif?[kCGImagePropertyExifExposureTime] != nil + || exif?[kCGImagePropertyExifFNumber] != nil + { + return .camera + } + return .graphic + } + + static func carriesIdentifyingMetadata(_ properties: [CFString: Any]) -> Bool { + if let gps = properties[kCGImagePropertyGPSDictionary] as? [CFString: Any], !gps.isEmpty { return true } + if let iptc = properties[kCGImagePropertyIPTCDictionary] as? [CFString: Any], !iptc.isEmpty { return true } + if let apple = properties[kCGImagePropertyMakerAppleDictionary] as? [CFString: Any], !apple.isEmpty { return true } + let tiff = properties[kCGImagePropertyTIFFDictionary] as? [CFString: Any] + for key in [kCGImagePropertyTIFFMake, kCGImagePropertyTIFFModel, kCGImagePropertyTIFFDateTime, + kCGImagePropertyTIFFSoftware, kCGImagePropertyTIFFArtist, kCGImagePropertyTIFFHostComputer] + where nonEmpty(tiff?[key]) + { + return true + } + let exif = properties[kCGImagePropertyExifDictionary] as? [CFString: Any] + for key in [kCGImagePropertyExifDateTimeOriginal, kCGImagePropertyExifDateTimeDigitized, + kCGImagePropertyExifLensModel, kCGImagePropertyExifBodySerialNumber, + kCGImagePropertyExifCameraOwnerName, kCGImagePropertyExifUserComment] + where nonEmpty(exif?[key]) + { + return true + } + return false + } + + private static func nonEmpty(_ value: Any?) -> Bool { + guard let value else { return false } + if let string = value as? String { + return !string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + return true + } + + // MARK: - Decode and resize + + private static var sourceOptions: CFDictionary { [kCGImageSourceShouldCache: false] as CFDictionary } + + private static func prepare( + imageSource: CGImageSource, + content: PhotoContent?, + target explicitTarget: PhotoTarget? + ) throws -> PreparedPhoto { + guard CGImageSourceGetCount(imageSource) > 0 else { throw PreparationError.unreadableImage } + let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [CFString: Any] ?? [:] + let resolved = content ?? classify(properties) + let target = explicitTarget ?? target(for: resolved) + let (width, height) = orientedPixelSize(properties) + let longEdge = max(width, height) + let maxPixelSize = longEdge > 0 ? min(target.maxPixelSize, longEdge) : target.maxPixelSize + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maxPixelSize, + kCGImageSourceShouldCacheImmediately: true, + ] + guard let image = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary) else { + throw PreparationError.unreadableImage + } + return try encode(image, target: target, content: resolved) + } + + /// Pixel size with EXIF orientations 5–8 (rotated a quarter turn) swapped. + static func orientedPixelSize(_ properties: [CFString: Any]) -> (width: Int, height: Int) { + let width = (properties[kCGImagePropertyPixelWidth] as? Int) ?? 0 + let height = (properties[kCGImagePropertyPixelHeight] as? Int) ?? 0 + let orientation = (properties[kCGImagePropertyOrientation] as? Int) ?? 1 + return orientation >= 5 ? (height, width) : (width, height) + } + + static func fittedSize(width: Int, height: Int, maxPixelSize: Int) -> (width: Int, height: Int) { + let longEdge = max(width, height) + guard longEdge > maxPixelSize, longEdge > 0 else { return (width, height) } + let scale = Double(maxPixelSize) / Double(longEdge) + return (max(1, Int((Double(width) * scale).rounded())), max(1, Int((Double(height) * scale).rounded()))) + } + + private static func resize(_ image: CGImage, maxPixelSize: Int) throws -> CGImage { + let (width, height) = fittedSize(width: image.width, height: image.height, maxPixelSize: maxPixelSize) + guard width != image.width || height != image.height else { return image } + guard let context = drawingContext(width: width, height: height, like: image) else { + throw PreparationError.encodeFailed + } + context.interpolationQuality = .high + context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) + guard let resized = context.makeImage() else { throw PreparationError.encodeFailed } + return resized + } + + private static func drawingContext(width: Int, height: Int, like image: CGImage?) -> CGContext? { + let colorSpace = image?.colorSpace.flatMap { $0.model == .rgb ? $0 : nil } + ?? CGColorSpace(name: CGColorSpace.sRGB)! + return CGContext( + data: nil, + width: width, + height: height, + bitsPerComponent: 8, + bytesPerRow: 0, + space: colorSpace, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + ) + } + + #if canImport(UIKit) + private static func renderUpright(_ image: UIImage, maxPixelSize: Int) -> CGImage? { + let pixelWidth = Int((image.size.width * image.scale).rounded()) + let pixelHeight = Int((image.size.height * image.scale).rounded()) + let (width, height) = fittedSize(width: pixelWidth, height: pixelHeight, maxPixelSize: maxPixelSize) + if image.imageOrientation == .up, let cgImage = image.cgImage { + return try? resize(cgImage, maxPixelSize: maxPixelSize) + } + let format = UIGraphicsImageRendererFormat() + format.scale = 1 + format.opaque = false + let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: format) + return renderer.image { _ in + image.draw(in: CGRect(x: 0, y: 0, width: width, height: height)) + }.cgImage + } + #elseif canImport(AppKit) + private static func renderUpright(_ image: NSImage, maxPixelSize: Int) -> CGImage? { + let representation = image.representations.first { $0 is NSBitmapImageRep } + let pixelWidth = representation?.pixelsWide ?? Int(image.size.width) + let pixelHeight = representation?.pixelsHigh ?? Int(image.size.height) + guard pixelWidth > 0, pixelHeight > 0 else { return nil } + let (width, height) = fittedSize(width: pixelWidth, height: pixelHeight, maxPixelSize: maxPixelSize) + let source = image.cgImage(forProposedRect: nil, context: nil, hints: nil) + guard let context = drawingContext(width: width, height: height, like: source) else { return nil } + context.interpolationQuality = .high + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false) + image.draw(in: NSRect(x: 0, y: 0, width: width, height: height), from: .zero, operation: .copy, fraction: 1) + NSGraphicsContext.restoreGraphicsState() + return context.makeImage() + } + #endif + + // MARK: - Encode + + /// JPEG unless some pixel is actually see-through. Screenshots often carry an alpha channel + /// that is fully opaque; sending those as PNG made them several times larger. + private static func encode(_ image: CGImage, target: PhotoTarget, content: PhotoContent) throws -> PreparedPhoto { + let format: ImageFormat = hasVisibleTransparency(image) ? .png : .jpeg + let data = NSMutableData() + let type = format == .png ? UTType.png.identifier : UTType.jpeg.identifier + guard let destination = CGImageDestinationCreateWithData(data as CFMutableData, type as CFString, 1, nil) else { + throw PreparationError.encodeFailed + } + // Only the encoder setting is passed: a CGImage carries no metadata, so nothing about the + // camera, place or time is written. The color profile travels with the image itself. + let properties: [CFString: Any] = format == .jpeg + ? [kCGImageDestinationLossyCompressionQuality: target.jpegQuality] + : [:] + CGImageDestinationAddImage(destination, image, properties as CFDictionary) + guard CGImageDestinationFinalize(destination), data.length > 0 else { throw PreparationError.encodeFailed } + return PreparedPhoto(data: data as Data, format: format, width: image.width, height: image.height, content: content) + } + + static func hasVisibleTransparency(_ image: CGImage) -> Bool { + switch image.alphaInfo { + case .none, .noneSkipFirst, .noneSkipLast: + return false + default: + break + } + let width = image.width, height = image.height + guard width > 0, height > 0, + let context = CGContext( + data: nil, + width: width, + height: height, + bitsPerComponent: 8, + bytesPerRow: width, + space: CGColorSpaceCreateDeviceGray(), + bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue + ) + else { + return true + } + context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) + guard let pixels = context.data else { return true } + let bytesPerRow = context.bytesPerRow + let buffer = pixels.bindMemory(to: UInt8.self, capacity: bytesPerRow * height) + for row in 0 ..< height { + let start = buffer + row * bytesPerRow + for column in 0 ..< width where start[column] < 255 { + return true + } + } + return false + } +} diff --git a/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift b/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift new file mode 100644 index 0000000000..c4726c2746 --- /dev/null +++ b/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift @@ -0,0 +1,145 @@ +import Foundation +import Logger + +/// Keeps the untouched file behind an attached photo or video until its message goes out, so +/// the composer's Original toggle can send that file instead of the compressed copy. Copies are +/// clones on APFS, so keeping them costs almost no space. They live in the temporary directory: +/// if the system clears it, the item is simply sent compressed. +public enum OriginalMediaStore { + public static var directory: URL { + FileHelpers.getTrueTemporaryDirectory().appendingPathComponent("inline-originals", isDirectory: true) + } + + /// Originals older than this belong to drafts nobody sent. + static let maximumAge: TimeInterval = 3 * 24 * 60 * 60 + + private static let log = Log.scoped("OriginalMediaStore") + + /// The folder for one attachment: named after its local file, which is unique per attachment. + static func folder(for media: FileMediaItem, in root: URL = directory) -> URL? { + guard let localPath = media.getLocalPath() else { return nil } + let stem = ((localPath as NSString).lastPathComponent as NSString).deletingPathExtension + guard !stem.isEmpty, !stem.contains("/") else { return nil } + return root.appendingPathComponent(stem, isDirectory: true) + } + + /// Keeps a copy of `url` as the original behind `media`, under its own file name. + static func retain(copyOf url: URL, fileName: String? = nil, for media: FileMediaItem, in root: URL = directory) throws { + guard let folder = folder(for: media, in: root) else { return } + let hasAccess = url.startAccessingSecurityScopedResource() + defer { if hasAccess { url.stopAccessingSecurityScopedResource() } } + let destination = try prepareFolder(folder).appendingPathComponent(safeFileName(fileName ?? url.lastPathComponent)) + try FileManager.default.copyItem(at: url, to: destination) + } + + /// Keeps encoded bytes as the original behind `media`. + static func retain(data: Data, fileName: String, for media: FileMediaItem, in root: URL = directory) throws { + guard let folder = folder(for: media, in: root) else { return } + let destination = try prepareFolder(folder).appendingPathComponent(safeFileName(fileName)) + try data.write(to: destination, options: .atomic) + } + + /// The kept original for `media`, if there is one. + public static func original(for media: FileMediaItem, in root: URL = directory) -> URL? { + guard let folder = folder(for: media, in: root), + let names = try? FileManager.default.contentsOfDirectory(atPath: folder.path) + else { + return nil + } + return names.sorted().first { !$0.hasPrefix(".") }.map { folder.appendingPathComponent($0) } + } + + public static func discard(for media: FileMediaItem, in root: URL = directory) { + guard let folder = folder(for: media, in: root) else { return } + try? FileManager.default.removeItem(at: folder) + } + + /// Removes originals left behind by drafts that were never sent. + static func sweep(now: Date = Date(), in root: URL = directory) { + let fileManager = FileManager.default + guard let folders = try? fileManager.contentsOfDirectory( + at: root, + includingPropertiesForKeys: [.contentModificationDateKey], + options: [.skipsHiddenFiles] + ) else { + return + } + for folder in folders { + let modified = (try? folder.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate + if let modified, now.timeIntervalSince(modified) > maximumAge { + try? fileManager.removeItem(at: folder) + } + } + } + + private static func prepareFolder(_ folder: URL) throws -> URL { + let fileManager = FileManager.default + if fileManager.fileExists(atPath: folder.path) { + try fileManager.removeItem(at: folder) + } + try fileManager.createDirectory(at: folder, withIntermediateDirectories: true) + return folder + } + + static func safeFileName(_ name: String) -> String { + let cleaned = (name as NSString).lastPathComponent + .replacingOccurrences(of: "/", with: "-") + .replacingOccurrences(of: ":", with: "-") + .trimmingCharacters(in: .whitespacesAndNewlines) + return cleaned.isEmpty || cleaned == "." || cleaned == ".." ? "original" : cleaned + } +} + +public extension FileMediaItem { + /// Whether the composer's Original toggle changes how this item is sent. + var canSendAsOriginal: Bool { + switch self { + case .photo, .video: true + case .document, .voice: false + } + } + + /// The composer's send with Original on: each photo and video is swapped for its untouched + /// file, in order. An item whose original is gone is sent as it is. + static func withOriginals(_ items: [FileMediaItem]) async -> [FileMediaItem] { + var result: [FileMediaItem] = [] + result.reserveCapacity(items.count) + for item in items { + guard item.canSendAsOriginal else { + result.append(item) + continue + } + do { + result.append(try await item.replacedWithOriginalDocument() ?? item) + } catch { + Log.shared.error("Couldn't send the original file; sending the compressed one", error: error) + result.append(item) + } + } + return result + } + + /// The untouched file behind a photo or video, saved as a document to send in its place, the + /// way Telegram's Send as File works: same bytes, same metadata. The compressed item is + /// removed. Returns nil when there is no original to send (the item is then sent as it is). + func replacedWithOriginalDocument() async throws -> FileMediaItem? { + switch self { + case let .photo(photoInfo): + guard let original = OriginalMediaStore.original(for: self) else { return nil } + let document = try await FileCache.saveDocumentWithThumbnail(url: original) + OriginalMediaStore.discard(for: self) + await FileCache.discardLocalPhoto(photoInfo) + return .document(document) + case let .video(videoInfo): + // The cached video is already an untouched copy; a kept original adds its real file name. + let original = OriginalMediaStore.original(for: self) ?? localFileURL() + guard let original, FileManager.default.fileExists(atPath: original.path) else { return nil } + let document = try await FileCache.saveDocumentWithThumbnail(url: original) + OriginalMediaStore.discard(for: self) + await FileCache.discardLocalVideo(videoInfo) + return .document(document) + case .document, .voice: + return nil + } + } +} diff --git a/apple/InlineKit/Sources/InlineKit/Files/VideoCompression.swift b/apple/InlineKit/Sources/InlineKit/Files/VideoCompression.swift index eedb69a20c..b873639fd3 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/VideoCompression.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/VideoCompression.swift @@ -5,27 +5,48 @@ import Logger public enum VideoCompressionError: Error { case invalidAsset - case compressionNotNeeded - case compressionNotEffective case exportFailed case unsupportedOutputType } -public struct VideoCompressionOptions: Sendable { +/// What a video shows, which decides how it is encoded. Screen recordings carry code and UI text +/// and cost little at high resolution, because the encoder only spends bits where pixels change. +/// Camera footage changes everywhere, so resolution costs real bytes and send time. +public enum VideoContent: String, Sendable, Equatable { + /// The file names the camera that recorded it. + case camera + /// Screen recordings, and anything else with no camera recorded in the file. + case screenRecording +} + +public struct VideoCompressionOptions: Sendable, Equatable { + /// Longest edge of the output. public let maxDimension: Int - public let minFileSizeBytes: Int64 - public let maxBitrateMbps: Double - public let minimumCompressionRatio: Double + /// Average video bitrate when re-encoding. + public let videoBitrateKbps: Int + public let audioBitrateKbps: Int + /// Re-encode even a source within limits (one whose codec can't go in an MP4 as is). public let forceTranscode: Bool - public static func uploadDefault(forceTranscode: Bool = false) -> VideoCompressionOptions { - VideoCompressionOptions( - maxDimension: 1_280, - minFileSizeBytes: 8_000_000, - maxBitrateMbps: 3.0, - minimumCompressionRatio: 0.94, - forceTranscode: forceTranscode - ) + public init(maxDimension: Int, videoBitrateKbps: Int, audioBitrateKbps: Int = 128, forceTranscode: Bool = false) { + self.maxDimension = maxDimension + self.videoBitrateKbps = videoBitrateKbps + self.audioBitrateKbps = audioBitrateKbps + self.forceTranscode = forceTranscode + } + + public static func upload(for content: VideoContent, forceTranscode: Bool = false) -> VideoCompressionOptions { + switch content { + case .camera: + VideoCompressionOptions(maxDimension: 1_280, videoBitrateKbps: 3_000, forceTranscode: forceTranscode) + case .screenRecording: + VideoCompressionOptions(maxDimension: 1_920, videoBitrateKbps: 5_000, forceTranscode: forceTranscode) + } + } + + /// A source at or under this total bitrate is sent without re-encoding. + var passthroughBitrateMbps: Double { + Double(videoBitrateKbps + audioBitrateKbps) * 1.15 / 1_000 } } @@ -151,32 +172,29 @@ public actor VideoCompressor { } } + /// Always returns a new file with no location, device or date metadata: the source is either + /// remuxed as is (already H.264 within size and bitrate, so nothing to wait for) or re-encoded. + /// It never hands back the source itself. private func compressVideoUnbounded(at sourceURL: URL, asset: AVURLAsset, options: VideoCompressionOptions) async throws -> VideoCompressionResult { let metadata = try await loadMetadata(for: asset) let sourceFileSize = fileSize(for: sourceURL) let maxDimension = max(metadata.width, metadata.height) let bitrateMbps = estimatedBitrateMbps(fileSize: sourceFileSize, duration: metadata.duration) + let isH264 = await Self.isH264(asset) + let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: asset) - let shouldCompress = options.forceTranscode - || maxDimension > options.maxDimension - || sourceFileSize >= options.minFileSizeBytes - || bitrateMbps > options.maxBitrateMbps + let canPassThrough = !options.forceTranscode + && isH264 + && maxDimension <= options.maxDimension + && bitrateMbps <= options.passthroughBitrateMbps + && compatiblePresets.contains(AVAssetExportPresetPassthrough) log.debug( - "Video compression check for \(sourceURL.lastPathComponent): size=\(sourceFileSize) bytes, max=\(maxDimension), bitrate=\(String(format: "%.2f", bitrateMbps)) Mbps, shouldCompress=\(shouldCompress)" + "Video check for \(sourceURL.lastPathComponent): size=\(sourceFileSize) bytes, max=\(maxDimension), bitrate=\(String(format: "%.2f", bitrateMbps)) Mbps, h264=\(isH264), passthrough=\(canPassThrough)" ) - guard shouldCompress else { - throw VideoCompressionError.compressionNotNeeded - } - - let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: asset) - let tempURL = FileManager.default.temporaryDirectory .appendingPathComponent("compressed_\(UUID().uuidString).mp4") - if FileManager.default.fileExists(atPath: tempURL.path) { - try FileManager.default.removeItem(at: tempURL) - } var shouldCleanupTemp = true defer { if shouldCleanupTemp, FileManager.default.fileExists(atPath: tempURL.path) { @@ -184,64 +202,39 @@ public actor VideoCompressor { } } - if shouldAttemptPassthroughTranscode( - options: options, - maxDimension: maxDimension, - sourceFileSize: sourceFileSize, - bitrateMbps: bitrateMbps, - compatiblePresets: compatiblePresets - ) { + var wrote = false + if canPassThrough { do { try await export(asset: asset, presetName: AVAssetExportPresetPassthrough, destinationURL: tempURL) - let outputSize = fileSize(for: tempURL) - let outputMetadata = try await loadMetadata(for: AVURLAsset(url: tempURL)) - shouldCleanupTemp = false - - log.debug( - "Video fast MP4 conversion result: original=\(sourceFileSize) bytes, converted=\(outputSize) bytes" - ) - - return VideoCompressionResult( - url: tempURL, - width: outputMetadata.width, - height: outputMetadata.height, - duration: outputMetadata.duration, - fileSize: outputSize - ) + wrote = true } catch is CancellationError { throw CancellationError() } catch { - log.debug("Passthrough MP4 conversion failed, falling back to encoded export") + log.debug("Passthrough MP4 remux failed, re-encoding instead") } } - do { - try await transcodeTelegramStyle(asset: asset, options: options, destinationURL: tempURL) - } catch is CancellationError { - throw CancellationError() - } catch { - log.warning("Telegram-style transcode failed, falling back to export preset: \(error.localizedDescription)") - PerformanceTrace.healthEvent("app.fallback", data: ["fallback_kind": "video_transcode_export_preset"]) - guard let presetName = selectPreset( - maxDimension: maxDimension, - targetMaxDimension: options.maxDimension, - compatiblePresets: compatiblePresets - ) else { - throw VideoCompressionError.exportFailed + if !wrote { + do { + try await transcodeTelegramStyle(asset: asset, options: options, destinationURL: tempURL) + } catch is CancellationError { + throw CancellationError() + } catch { + log.warning("Video transcode failed, falling back to export preset: \(error.localizedDescription)") + PerformanceTrace.healthEvent("app.fallback", data: ["fallback_kind": "video_transcode_export_preset"]) + guard let presetName = selectPreset( + maxDimension: maxDimension, + targetMaxDimension: options.maxDimension, + compatiblePresets: compatiblePresets + ) else { + throw VideoCompressionError.exportFailed + } + try await export(asset: asset, presetName: presetName, destinationURL: tempURL) } - try await export(asset: asset, presetName: presetName, destinationURL: tempURL) } let outputSize = fileSize(for: tempURL) - let compressionRatio = Double(outputSize) / Double(max(sourceFileSize, 1)) - - log.debug( - "Video compression result: original=\(sourceFileSize) bytes, compressed=\(outputSize) bytes, ratio=\(String(format: "%.2f", compressionRatio))" - ) - - if !options.forceTranscode && compressionRatio > options.minimumCompressionRatio { - throw VideoCompressionError.compressionNotEffective - } + log.debug("Video prepared: original=\(sourceFileSize) bytes, sent=\(outputSize) bytes, remuxed=\(wrote)") let outputMetadata = try await loadMetadata(for: AVURLAsset(url: tempURL)) shouldCleanupTemp = false @@ -255,18 +248,34 @@ public actor VideoCompressor { ) } - private func shouldAttemptPassthroughTranscode( - options: VideoCompressionOptions, - maxDimension: Int, - sourceFileSize: Int64, - bitrateMbps: Double, - compatiblePresets: [String] - ) -> Bool { - guard options.forceTranscode else { return false } - guard compatiblePresets.contains(AVAssetExportPresetPassthrough) else { return false } - return maxDimension <= options.maxDimension - && sourceFileSize < options.minFileSizeBytes - && bitrateMbps <= options.maxBitrateMbps + /// Whether the file records the camera that made it, which marks camera footage. + public static func content(of url: URL) async -> VideoContent { + let asset = AVURLAsset(url: url) + guard let items = try? await asset.load(.metadata) else { return .screenRecording } + for item in items { + let isCameraKey = item.identifier == .quickTimeMetadataMake + || item.identifier == .quickTimeMetadataModel + || item.identifier == .quickTimeUserDataMake + || item.identifier == .quickTimeUserDataModel + || item.commonKey == .commonKeyMake + || item.commonKey == .commonKeyModel + guard isCameraKey else { continue } + if let value = try? await item.load(.stringValue), + !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + { + return .camera + } + } + return .screenRecording + } + + static func isH264(_ asset: AVAsset) async -> Bool { + guard let track = try? await asset.loadTracks(withMediaType: .video).first, + let format = try? await track.load(.formatDescriptions).first + else { + return false + } + return CMFormatDescriptionGetMediaSubType(format) == kCMVideoCodecType_H264 } private func export(asset: AVAsset, presetName: String, destinationURL: URL) async throws { @@ -285,6 +294,8 @@ public actor VideoCompressor { exportSession.outputURL = destinationURL exportSession.outputFileType = .mp4 exportSession.shouldOptimizeForNetworkUse = true + // Drops where and on what device it was recorded, and other personal details. + exportSession.metadataItemFilter = AVMetadataItemFilter.forSharing() let sessionBox = ExportSessionBox(exportSession) try await withTaskCancellationHandler { @@ -329,9 +340,8 @@ public actor VideoCompressor { throw VideoCompressionError.invalidAsset } - let telegramPreset = telegramPreset(for: options) - let outputSize = targetRenderSize(for: sourceDisplaySize, maxDimension: telegramPreset.maxDimension) - let frameRate = targetFrameRate(for: sourceVideoTrack, capTo30FPS: telegramPreset.capsFrameRateTo30FPS) + let outputSize = targetRenderSize(for: sourceDisplaySize, maxDimension: options.maxDimension) + let frameRate = targetFrameRate(for: sourceVideoTrack, capTo30FPS: true) let duration = try await asset.load(.duration) guard duration.isValid, duration.seconds > 0 else { throw VideoCompressionError.invalidAsset @@ -400,7 +410,7 @@ public actor VideoCompressor { outputSettings: makeTelegramVideoSettings( dimensions: outputSize, frameRate: frameRate, - targetVideoBitrate: telegramPreset.videoBitrateKbps * 1_000 + targetVideoBitrate: options.videoBitrateKbps * 1_000 ) ) videoInput.expectsMediaDataInRealTime = false @@ -411,7 +421,7 @@ public actor VideoCompressor { var audioOutput: AVAssetReaderTrackOutput? var audioInput: AVAssetWriterInput? - if let compositionAudioTrack, let telegramAudioSettings = makeTelegramAudioSettings(preset: telegramPreset) { + if let compositionAudioTrack, let telegramAudioSettings = makeAudioSettings(bitrateKbps: options.audioBitrateKbps) { let output = AVAssetReaderTrackOutput( track: compositionAudioTrack, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM] @@ -597,20 +607,16 @@ public actor VideoCompressor { ] } - private func makeTelegramAudioSettings(preset: TelegramVideoCompressionPreset) -> [String: Any]? { - guard preset.audioBitrateKbps > 0, preset.audioChannels > 0 else { - return nil - } - + private func makeAudioSettings(bitrateKbps: Int) -> [String: Any]? { + guard bitrateKbps > 0 else { return nil } var layout = AudioChannelLayout() - layout.mChannelLayoutTag = preset.audioChannels > 1 ? kAudioChannelLayoutTag_Stereo : kAudioChannelLayoutTag_Mono - + layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo return [ AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 44_100, - AVEncoderBitRateKey: preset.audioBitrateKbps * 1_000, - AVNumberOfChannelsKey: preset.audioChannels, - AVChannelLayoutKey: Data(bytes: &layout, count: MemoryLayout.size) + AVEncoderBitRateKey: bitrateKbps * 1_000, + AVNumberOfChannelsKey: 2, + AVChannelLayoutKey: Data(bytes: &layout, count: MemoryLayout.size), ] } @@ -647,10 +653,6 @@ public actor VideoCompressor { return capTo30FPS ? max(1, min(frameRate, 30)) : max(1, frameRate) } - private func telegramPreset(for options: VideoCompressionOptions) -> TelegramVideoCompressionPreset { - TelegramVideoCompressionPreset.from(maxDimension: options.maxDimension, maxBitrateMbps: options.maxBitrateMbps) - } - private func waitForGroup(_ group: DispatchGroup) async { await withCheckedContinuation { continuation in group.notify(queue: DispatchQueue.global(qos: .userInitiated)) { @@ -884,77 +886,3 @@ private final class StreamCompletionState: @unchecked Sendable { } } } - -private enum TelegramVideoCompressionPreset: Sendable { - case compressedVeryLow - case compressedLow - case compressedMedium - case compressedHigh - case compressedVeryHigh - - var maxDimension: Int { - switch self { - case .compressedVeryLow: - return 480 - case .compressedLow: - return 640 - case .compressedMedium: - return 848 - case .compressedHigh: - return 1_280 - case .compressedVeryHigh: - return 1_920 - } - } - - var videoBitrateKbps: Int { - switch self { - case .compressedVeryLow: - return 400 - case .compressedLow: - return 700 - case .compressedMedium: - return 1_600 - case .compressedHigh: - return 2_800 - case .compressedVeryHigh: - return 6_600 - } - } - - var audioBitrateKbps: Int { - switch self { - case .compressedVeryLow, .compressedLow: - return 32 - case .compressedMedium, .compressedHigh, .compressedVeryHigh: - return 64 - } - } - - var audioChannels: Int { - switch self { - case .compressedVeryLow, .compressedLow: - return 1 - case .compressedMedium, .compressedHigh, .compressedVeryHigh: - return 2 - } - } - - var capsFrameRateTo30FPS: Bool { - self != .compressedVeryHigh - } - - static func from(maxDimension: Int, maxBitrateMbps: Double) -> TelegramVideoCompressionPreset { - if maxDimension >= 1_920 || maxBitrateMbps >= 6.6 { - return .compressedVeryHigh - } else if maxDimension >= 1_280 || maxBitrateMbps >= 3.0 { - return .compressedHigh - } else if maxDimension >= 848 || maxBitrateMbps >= 1.6 { - return .compressedMedium - } else if maxDimension >= 640 || maxBitrateMbps >= 0.7 { - return .compressedLow - } else { - return .compressedVeryLow - } - } -} diff --git a/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift b/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift new file mode 100644 index 0000000000..d5c215f147 --- /dev/null +++ b/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift @@ -0,0 +1,240 @@ +import CoreGraphics +import Foundation +import ImageIO +import Testing +import UniformTypeIdentifiers +@testable import InlineKit + +@Suite("Media send preparation") +struct MediaSendPreparationTests { + @Test("a camera photo is sized to 1600, turned upright, and keeps nothing identifying") + func cameraPhoto() throws { + // Stored 4000×3000 with orientation 6: shown as 3000×4000 (portrait). + let source = try makeJPEG(width: 4000, height: 3000, orientation: 6, camera: true, gps: true) + + let prepared = try MediaSendPreparation.preparePhoto(.data(source)) + + #expect(prepared.content == .camera) + #expect(prepared.format == .jpeg) + #expect(prepared.width == 1200) + #expect(prepared.height == 1600) + let properties = try #require(properties(of: prepared.data)) + #expect(properties[kCGImagePropertyGPSDictionary] == nil) + let tiff = properties[kCGImagePropertyTIFFDictionary] as? [CFString: Any] + #expect(tiff?[kCGImagePropertyTIFFMake] == nil) + #expect(tiff?[kCGImagePropertyTIFFModel] == nil) + #expect((properties[kCGImagePropertyOrientation] as? Int ?? 1) == 1) + let exif = properties[kCGImagePropertyExifDictionary] as? [CFString: Any] + #expect(exif?[kCGImagePropertyExifDateTimeOriginal] == nil) + } + + @Test("the prepared file needs no further preparation before upload") + func preparedIsFinal() throws { + let source = try makeJPEG(width: 3000, height: 2000, orientation: 1, camera: true, gps: true) + let sourceURL = try write(source, ext: "jpg") + defer { try? FileManager.default.removeItem(at: sourceURL) } + #expect(MediaSendPreparation.photoNeedsPreparation(at: sourceURL)) + + let prepared = try MediaSendPreparation.preparePhoto(.file(sourceURL)) + let preparedURL = try write(prepared.data, ext: "jpg") + defer { try? FileManager.default.removeItem(at: preparedURL) } + + #expect(!MediaSendPreparation.photoNeedsPreparation(at: preparedURL)) + } + + @Test("a screenshot keeps up to 2560 and goes as JPEG when its alpha channel is fully opaque") + func opaqueScreenshot() throws { + let source = try makePNG(width: 3456, height: 2234, transparentCorner: false) + + let prepared = try MediaSendPreparation.preparePhoto(.data(source)) + + #expect(prepared.content == .graphic) + #expect(prepared.format == .jpeg) + #expect(prepared.width == 2560) + #expect(prepared.height == 1655) + } + + @Test("an image with see-through pixels stays PNG") + func transparentImage() throws { + let source = try makePNG(width: 400, height: 300, transparentCorner: true) + + let prepared = try MediaSendPreparation.preparePhoto(.data(source)) + + #expect(prepared.format == .png) + #expect(prepared.width == 400) + } + + @Test("small photos are never enlarged") + func noUpscaling() throws { + let source = try makeJPEG(width: 800, height: 600, orientation: 1, camera: true, gps: false) + + let prepared = try MediaSendPreparation.preparePhoto(.data(source)) + + #expect(prepared.width == 800) + #expect(prepared.height == 600) + } + + @Test("a screenshot marker wins over camera details") + func screenshotComment() { + let properties: [CFString: Any] = [ + kCGImagePropertyTIFFDictionary: [kCGImagePropertyTIFFMake: "Apple"] as [CFString: Any], + kCGImagePropertyExifDictionary: [kCGImagePropertyExifUserComment: "Screenshot"] as [CFString: Any], + ] + #expect(MediaSendPreparation.classify(properties) == .graphic) + #expect(MediaSendPreparation.classify([:]) == .graphic) + #expect(MediaSendPreparation.classify([ + kCGImagePropertyExifDictionary: [kCGImagePropertyExifFNumber: 1.8] as [CFString: Any], + ]) == .camera) + } + + @Test("pixels without a file are prepared like a graphic and resized") + func pixelsOnly() throws { + let image = try #require(makeImage(width: 5000, height: 1000, alpha: false)) + + let prepared = try MediaSendPreparation.preparePhoto(.cgImage(image)) + + #expect(prepared.content == .graphic) + #expect(prepared.width == 2560) + #expect(prepared.height == 512) + } + + @Test("very thin or tiny images go as files") + func documentRule() { + #expect(MediaSendPreparation.shouldSendAsDocument(width: 1170, height: 25_000)) + #expect(MediaSendPreparation.shouldSendAsDocument(width: 40, height: 30)) + #expect(!MediaSendPreparation.shouldSendAsDocument(width: 1170, height: 20_000)) + #expect(!MediaSendPreparation.shouldSendAsDocument(width: 40, height: 60)) + } + + @Test("the source extension is read from the bytes") + func fileExtension() throws { + #expect(MediaSendPreparation.fileExtension(of: try makePNG(width: 10, height: 10, transparentCorner: false)) == "png") + let jpeg = try makeJPEG(width: 10, height: 10, orientation: 1, camera: false, gps: false) + #expect(["jpeg", "jpg"].contains(MediaSendPreparation.fileExtension(of: jpeg) ?? "")) + } +} + +@Suite("Original media store") +struct OriginalMediaStoreTests { + @Test("keeps, finds and discards the original behind a photo") + func roundTrip() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("originals-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: root) } + let media = photoItem(localPath: "\(UUID().uuidString).jpg") + let source = try write(Data("heic bytes".utf8), ext: "heic") + defer { try? FileManager.default.removeItem(at: source) } + + try OriginalMediaStore.retain(copyOf: source, fileName: "IMG_4821.HEIC", for: media, in: root) + + let original = try #require(OriginalMediaStore.original(for: media, in: root)) + #expect(original.lastPathComponent == "IMG_4821.HEIC") + #expect(try Data(contentsOf: original) == Data("heic bytes".utf8)) + + OriginalMediaStore.discard(for: media, in: root) + #expect(OriginalMediaStore.original(for: media, in: root) == nil) + } + + @Test("sweeps originals from drafts nobody sent") + func sweep() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("originals-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: root) } + let media = photoItem(localPath: "\(UUID().uuidString).jpg") + try OriginalMediaStore.retain(data: Data([1, 2, 3]), fileName: "Photo.jpeg", for: media, in: root) + + OriginalMediaStore.sweep(now: Date(), in: root) + #expect(OriginalMediaStore.original(for: media, in: root) != nil) + + OriginalMediaStore.sweep(now: Date().addingTimeInterval(OriginalMediaStore.maximumAge + 60), in: root) + #expect(OriginalMediaStore.original(for: media, in: root) == nil) + } + + @Test("file names can't escape the folder") + func safeNames() { + #expect(OriginalMediaStore.safeFileName("../../etc/passwd") == "passwd") + #expect(OriginalMediaStore.safeFileName("a:b.jpg") == "a-b.jpg") + #expect(OriginalMediaStore.safeFileName("..") == "original") + } + + @Test("only photos and videos can be sent as originals") + func eligibility() { + #expect(photoItem(localPath: "a.jpg").canSendAsOriginal) + } +} + +// MARK: - Fixtures + +private func photoItem(localPath: String) -> FileMediaItem { + .photo(PhotoInfo(photo: Photo(photoId: -7, format: .jpeg), sizes: [ + PhotoSize(photoId: -7, type: "f", width: 10, height: 10, localPath: localPath), + ])) +} + +private func properties(of data: Data) -> [CFString: Any]? { + guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } + return CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] +} + +private func write(_ data: Data, ext: String) throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("prep-\(UUID().uuidString).\(ext)") + try data.write(to: url) + return url +} + +private func makeImage(width: Int, height: Int, alpha: Bool, transparentCorner: Bool = false) -> CGImage? { + guard let context = CGContext( + data: nil, + width: width, + height: height, + bitsPerComponent: 8, + bytesPerRow: 0, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: (alpha ? CGImageAlphaInfo.premultipliedLast : CGImageAlphaInfo.noneSkipLast).rawValue + ) else { + return nil + } + context.setFillColor(CGColor(red: 0.2, green: 0.5, blue: 0.8, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + context.setFillColor(CGColor(red: 0.9, green: 0.3, blue: 0.1, alpha: 1)) + context.fill(CGRect(x: width / 4, y: height / 4, width: width / 2, height: height / 2)) + if transparentCorner { + context.clear(CGRect(x: 0, y: 0, width: max(1, width / 10), height: max(1, height / 10))) + } + return context.makeImage() +} + +private func makeJPEG(width: Int, height: Int, orientation: Int, camera: Bool, gps: Bool) throws -> Data { + let image = try #require(makeImage(width: width, height: height, alpha: false)) + var properties: [CFString: Any] = [kCGImagePropertyOrientation: orientation] + if camera { + properties[kCGImagePropertyTIFFDictionary] = [ + kCGImagePropertyTIFFMake: "Apple", + kCGImagePropertyTIFFModel: "iPhone 17 Pro", + ] as [CFString: Any] + properties[kCGImagePropertyExifDictionary] = [ + kCGImagePropertyExifDateTimeOriginal: "2026:11:20 10:00:00", + kCGImagePropertyExifFNumber: 1.8, + ] as [CFString: Any] + } + if gps { + properties[kCGImagePropertyGPSDictionary] = [ + kCGImagePropertyGPSLatitude: 35.7, + kCGImagePropertyGPSLatitudeRef: "N", + kCGImagePropertyGPSLongitude: 51.4, + kCGImagePropertyGPSLongitudeRef: "E", + ] as [CFString: Any] + } + return try encode(image, type: .jpeg, properties: properties) +} + +private func makePNG(width: Int, height: Int, transparentCorner: Bool) throws -> Data { + let image = try #require(makeImage(width: width, height: height, alpha: true, transparentCorner: transparentCorner)) + return try encode(image, type: .png, properties: [:]) +} + +private func encode(_ image: CGImage, type: UTType, properties: [CFString: Any]) throws -> Data { + let data = NSMutableData() + let destination = try #require(CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil)) + CGImageDestinationAddImage(destination, image, properties as CFDictionary) + #expect(CGImageDestinationFinalize(destination)) + return data as Data +} diff --git a/apple/InlineKit/Tests/InlineKitTests/VideoCompressionTests.swift b/apple/InlineKit/Tests/InlineKitTests/VideoCompressionTests.swift index 1d77a3b39f..ce8926de3b 100644 --- a/apple/InlineKit/Tests/InlineKitTests/VideoCompressionTests.swift +++ b/apple/InlineKit/Tests/InlineKitTests/VideoCompressionTests.swift @@ -21,27 +21,45 @@ struct VideoCompressionTests { #expect(result.fileSize > 0) } - @Test("returns compressionNotNeeded when thresholds are high") - func testCompressionNotNeededForSmallVideo() async throws { - let videoURL = try await makeTestVideoURL() + @Test("an H.264 video within limits is remuxed, not re-encoded, and loses its location") + func remuxesWithinLimits() async throws { + let videoURL = try await makeTestVideoURL(fileType: .mov, metadata: cameraMetadata()) defer { try? FileManager.default.removeItem(at: videoURL) } + #expect(await VideoCompressor.content(of: videoURL) == .camera) + + let result = try await VideoCompressor.shared.compressVideo(at: videoURL, options: .upload(for: .camera)) + defer { try? FileManager.default.removeItem(at: result.url) } + + #expect(result.url != videoURL) + #expect(result.url.pathExtension == "mp4") + #expect(result.width == 64) + #expect(try await identifyingMetadata(at: result.url).isEmpty) + } - let options = VideoCompressionOptions( - maxDimension: 4096, - minFileSizeBytes: Int64.max, - maxBitrateMbps: 1000, - minimumCompressionRatio: 0.99, - forceTranscode: false + @Test("a video over the size limit is re-encoded smaller and loses its location") + func reencodesOversize() async throws { + let videoURL = try await makeTestVideoURL( + size: CGSize(width: 1600, height: 896), + fileType: .mov, + metadata: cameraMetadata() ) + defer { try? FileManager.default.removeItem(at: videoURL) } - do { - _ = try await VideoCompressor.shared.compressVideo(at: videoURL, options: options) - #expect(Bool(false)) - } catch VideoCompressionError.compressionNotNeeded { - // Expected - } catch { - #expect(Bool(false)) - } + let result = try await VideoCompressor.shared.compressVideo(at: videoURL, options: .upload(for: .camera)) + defer { try? FileManager.default.removeItem(at: result.url) } + + #expect(max(result.width, result.height) <= 1_280) + #expect(try await identifyingMetadata(at: result.url).isEmpty) + } + + @Test("a video with no camera recorded is treated as a screen recording") + func screenRecordingContent() async throws { + let videoURL = try await makeTestVideoURL() + defer { try? FileManager.default.removeItem(at: videoURL) } + + #expect(await VideoCompressor.content(of: videoURL) == .screenRecording) + #expect(VideoCompressionOptions.upload(for: .screenRecording).maxDimension == 1_920) + #expect(VideoCompressionOptions.upload(for: .camera).maxDimension == 1_280) } @Test("throws for empty file") @@ -51,20 +69,39 @@ struct VideoCompressionTests { try Data().write(to: tempURL, options: .atomic) defer { try? FileManager.default.removeItem(at: tempURL) } - do { - _ = try await VideoCompressor.shared.compressVideo( - at: tempURL, - options: VideoCompressionOptions.uploadDefault(forceTranscode: true) - ) - #expect(Bool(false)) - } catch VideoCompressionError.compressionNotNeeded { - #expect(Bool(false)) - } catch { - // Expected: invalid input should fail compression. + await #expect(throws: (any Error).self) { + _ = try await VideoCompressor.shared.compressVideo(at: tempURL, options: .upload(for: .camera)) } } } +private func cameraMetadata() -> [AVMetadataItem] { + func item(_ identifier: AVMetadataIdentifier, _ value: String) -> AVMetadataItem { + let item = AVMutableMetadataItem() + item.identifier = identifier + item.value = value as NSString + item.dataType = kCMMetadataBaseDataType_UTF8 as String + return item + } + return [ + item(.quickTimeMetadataLocationISO6709, "+35.7000+051.4000/"), + item(.quickTimeMetadataMake, "Apple"), + item(.quickTimeMetadataModel, "iPhone 17 Pro"), + ] +} + +private func identifyingMetadata(at url: URL) async throws -> [AVMetadataItem] { + let items = try await AVURLAsset(url: url).load(.metadata) + return items.filter { + $0.identifier == .quickTimeMetadataLocationISO6709 + || $0.identifier == .quickTimeMetadataMake + || $0.identifier == .quickTimeMetadataModel + || $0.commonKey == .commonKeyLocation + || $0.commonKey == .commonKeyMake + || $0.commonKey == .commonKeyModel + } +} + private enum VideoTestError: Error { case writerSetupFailed case pixelBufferPoolUnavailable @@ -85,7 +122,8 @@ private func makeTestVideoURL( size: CGSize = CGSize(width: 64, height: 64), frameCount: Int = 2, fps: Int32 = 10, - fileType: AVFileType = .mp4 + fileType: AVFileType = .mp4, + metadata: [AVMetadataItem] = [] ) async throws -> URL { let pathExtension = fileType == .mov ? "mov" : "mp4" let outputURL = FileManager.default.temporaryDirectory @@ -95,6 +133,7 @@ private func makeTestVideoURL( } let writer = try AVAssetWriter(outputURL: outputURL, fileType: fileType) + writer.metadata = metadata let videoSettings: [String: Any] = [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: Int(size.width), diff --git a/apple/InlineMacUI/Sources/InlineMacUI/DraftAttachmentImporter.swift b/apple/InlineMacUI/Sources/InlineMacUI/DraftAttachmentImporter.swift index 1d8e37df7a..46f0d18bfe 100644 --- a/apple/InlineMacUI/Sources/InlineMacUI/DraftAttachmentImporter.swift +++ b/apple/InlineMacUI/Sources/InlineMacUI/DraftAttachmentImporter.swift @@ -21,7 +21,15 @@ protocol DraftAttachmentWriting: AnyObject { func addImage( peer: Peer, image: PlatformImage, - preferredFormat: ImageFormat?, + sourceURL: URL?, + onComplete: Drafts2AttachmentCompletion? + ) -> String + + @discardableResult + func addPhoto( + peer: Peer, + source: MediaSendPreparation.PhotoSource, + originalFileName: String?, onComplete: Drafts2AttachmentCompletion? ) -> String @@ -158,10 +166,6 @@ public enum DraftAttachmentImporter { case failed(String) } - private struct SendableCGImage: @unchecked Sendable { - let value: CGImage - } - private static func importPreparedAttachment( _ attachment: PreparedPasteboardAttachment, into peer: Peer, @@ -171,14 +175,12 @@ public enum DraftAttachmentImporter { guard !Task.isCancelled, mutationAllowed(mutationToken) else { return .ignored } switch attachment { case let .imageFile(url): - let decoded = await Task.detached(priority: .userInitiated) { - guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), - let image = CGImageSourceCreateImageAtIndex(source, 0, nil) - else { return nil as SendableCGImage? } - return SendableCGImage(value: image) + // Read only the header; the photo is prepared from the file without decoding it here. + let readable = await Task.detached(priority: .userInitiated) { + MediaSendPreparation.pixelSize(of: .file(url)) != nil }.value guard !Task.isCancelled, mutationAllowed(mutationToken) else { return .ignored } - guard let decoded else { + guard readable else { return outcome(from: await importFile( url, peer: peer, @@ -186,13 +188,11 @@ public enum DraftAttachmentImporter { mutationToken: mutationToken )) } - let image = NSImage(cgImage: decoded.value, size: .zero) - let preferredFormat: ImageFormat? = url.pathExtension.lowercased() == "png" ? .png : nil let result = await awaitResult(mutationToken: mutationToken) { completion in - _ = writer.addImage( + _ = writer.addPhoto( peer: peer, - image: image, - preferredFormat: preferredFormat, + source: .file(url), + originalFileName: url.lastPathComponent, onComplete: completion ) } @@ -250,12 +250,11 @@ public enum DraftAttachmentImporter { guard !Task.isCancelled, mutationAllowed(mutationToken) else { return .ignored } switch attachment { case let .image(image, sourceURL): - let preferredFormat: ImageFormat? = sourceURL?.pathExtension.lowercased() == "png" ? .png : nil let result = await awaitResult(mutationToken: mutationToken) { completion in _ = writer.addImage( peer: peer, image: image, - preferredFormat: preferredFormat, + sourceURL: sourceURL, onComplete: completion ) } diff --git a/apple/InlineMacUI/Tests/InlineMacUITests/DraftAttachmentImporterTests.swift b/apple/InlineMacUI/Tests/InlineMacUITests/DraftAttachmentImporterTests.swift index 52431420e4..a00a47986c 100644 --- a/apple/InlineMacUI/Tests/InlineMacUITests/DraftAttachmentImporterTests.swift +++ b/apple/InlineMacUI/Tests/InlineMacUITests/DraftAttachmentImporterTests.swift @@ -149,7 +149,16 @@ private final class FakeDraftAttachmentWriter: DraftAttachmentWriting { func addImage( peer: Peer, image: PlatformImage, - preferredFormat: ImageFormat?, + sourceURL: URL?, + onComplete: Drafts2AttachmentCompletion? + ) -> String { + complete(.image, peer: peer, onComplete: onComplete) + } + + func addPhoto( + peer: Peer, + source: MediaSendPreparation.PhotoSource, + originalFileName: String?, onComplete: Drafts2AttachmentCompletion? ) -> String { complete(.image, peer: peer, onComplete: onComplete) From 7971878305bc523234e3e8c009a0d256e2cef9f2 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sat, 21 Nov 2026 00:41:13 +0330 Subject: [PATCH 02/14] ios: add an original toggle to the composer and prepare photos off the main thread An Original chip leads the attachment strip when photos or videos are attached. With it on, each one is sent as its untouched file, and it resets after the send. Picked photos are read from their files so camera details choose the size and the original is kept; paste, recent photos and the camera prepare in the background. The unused photo preview screens are gone, and the share extension uses the shared photo and video preparation. --- .../Compose/ComposeView+UIViews.swift | 34 ++ .../Features/Compose/ComposeView.swift | 21 +- .../Features/Compose/PhotoUtils.swift | 458 +++++------------- apple/InlineShareExtension/ShareState.swift | 366 ++------------ 4 files changed, 219 insertions(+), 660 deletions(-) diff --git a/apple/InlineIOS/Features/Compose/ComposeView+UIViews.swift b/apple/InlineIOS/Features/Compose/ComposeView+UIViews.swift index 0a726ee953..195fbf63f6 100644 --- a/apple/InlineIOS/Features/Compose/ComposeView+UIViews.swift +++ b/apple/InlineIOS/Features/Compose/ComposeView+UIViews.swift @@ -355,6 +355,40 @@ extension ComposeView { return view } + /// The strip's Original chip. Off: photos and videos are sent compressed, with no location or + /// camera details. On: they go as their untouched files, the way Telegram's Send as File works. + func makeOriginalToggleButton() -> UIButton { + let button = UIButton(type: .custom) + button.translatesAutoresizingMaskIntoConstraints = false + button.isSelected = sendsMediaAsOriginal + button.configurationUpdateHandler = { button in + var configuration: UIButton.Configuration = button.isSelected ? .filled() : .gray() + configuration.cornerStyle = .capsule + configuration.image = UIImage(systemName: button.isSelected ? "checkmark.circle.fill" : "circle") + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13, weight: .semibold) + configuration.imagePadding = 5 + configuration.contentInsets = NSDirectionalEdgeInsets(top: 7, leading: 10, bottom: 7, trailing: 12) + var title = AttributedString("Original") + title.font = UIFont.systemFont(ofSize: 14, weight: .semibold) + configuration.attributedTitle = title + if !button.isSelected { + configuration.baseForegroundColor = .secondaryLabel + } + button.configuration = configuration + button.accessibilityValue = button.isSelected ? "On" : "Off" + } + button.addAction(UIAction { [weak self] _ in + guard let self else { return } + sendsMediaAsOriginal.toggle() + UISelectionFeedbackGenerator().selectionChanged() + }, for: .primaryActionTriggered) + button.accessibilityLabel = "Send originals" + button.accessibilityHint = "Sends photos and videos as files, unchanged, including their location and camera details." + button.setContentHuggingPriority(.required, for: .horizontal) + button.setContentCompressionResistancePriority(.required, for: .horizontal) + return button + } + func makeAttachmentScrollView() -> UIScrollView { let view = UIScrollView() view.translatesAutoresizingMaskIntoConstraints = false diff --git a/apple/InlineIOS/Features/Compose/ComposeView.swift b/apple/InlineIOS/Features/Compose/ComposeView.swift index 6dfd0af7b1..bdec74a15d 100644 --- a/apple/InlineIOS/Features/Compose/ComposeView.swift +++ b/apple/InlineIOS/Features/Compose/ComposeView.swift @@ -98,6 +98,12 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { var attachmentItems: [String: FileMediaItem] = [:] { didSet { attachmentOrder = Self.updatedAttachmentOrder(attachmentOrder, items: attachmentItems) } } + /// The strip's Original chip: photos and videos go as their untouched files. Resets once the + /// attachments are sent or cleared, so it never carries over to a later message. + var sendsMediaAsOriginal = false { + didSet { originalToggleButton?.isSelected = sendsMediaAsOriginal } + } + weak var originalToggleButton: UIButton? /// Keys of `attachmentItems` in the order they were added: the order they are sent in, and so /// the order of an album's photos. private(set) var attachmentOrder: [String] = [] @@ -412,7 +418,7 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { let replyToMsgId = ChatState.shared.getState(peer: peerId).replyingMessageId Task.detached(priority: .userInitiated) { @MainActor in - let photoInfo = try FileCache.savePhoto(image: image, optimize: true) + let photoInfo = try FileCache.savePhoto(image: image) let mediaItem = FileMediaItem.photo(photoInfo) await Transactions.shared.mutate( @@ -1213,6 +1219,7 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { ) let hasText = !rawText.isEmpty let attachmentItemsSnapshot = attachmentItems + let sendsOriginalsSnapshot = sendsMediaAsOriginal let hasAttachmentItems = !attachmentItemsSnapshot.isEmpty let hasForward = forwardContext != nil @@ -1356,7 +1363,7 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { } } else { // In the order they were added; neighbouring photos and videos go out as albums. - let attachments = orderedAttachmentsToSend.filter { attachment in + var attachments = orderedAttachmentsToSend.filter { attachment in // Verify attachment has valid local path before sending guard attachment.getLocalPath() != nil else { log.error("Attachment has no local path, skipping: \(attachment)") @@ -1364,6 +1371,9 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { } return true } + if sendsOriginalsSnapshot { + attachments = await FileMediaItem.withOriginals(attachments) + } for send in TransactionSendMessage.sends( text: text, peerId: peerId, @@ -2133,6 +2143,7 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { } attachmentItems.removeAll() pendingVideoAttachments.removeAll() + sendsMediaAsOriginal = false handleAttachmentItemsChanged( animated: false, shouldUpdateSendButtonVisibility: shouldUpdateSendButtonVisibility, @@ -2348,6 +2359,12 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { guard hasAttachments else { return } + if !pendingVideoAttachments.isEmpty || attachmentItems.values.contains(where: \.canSendAsOriginal) { + let toggle = makeOriginalToggleButton() + originalToggleButton = toggle + attachmentStackView.addArrangedSubview(toggle) + } + for pending in pendingVideoAttachments { let preview = ComposeAttachmentPreviewItemView( pendingVideoId: pending.id, diff --git a/apple/InlineIOS/Features/Compose/PhotoUtils.swift b/apple/InlineIOS/Features/Compose/PhotoUtils.swift index 01ce6c5a77..9f97a66c17 100644 --- a/apple/InlineIOS/Features/Compose/PhotoUtils.swift +++ b/apple/InlineIOS/Features/Compose/PhotoUtils.swift @@ -43,120 +43,6 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe } } - private func shouldSendAsFile(_ image: UIImage) -> Bool { - let width = max(image.size.width, 1) - let height = max(image.size.height, 1) - let ratio = max(width / height, height / width) - return ratio > 20 || (width < 50 && height < 50) - } - - private func makeImageAttachment(_ image: UIImage, optimizePhoto: Bool) throws -> FileMediaItem { - if shouldSendAsFile(image) { - let tempDirectory = FileHelpers.getTrueTemporaryDirectory() - let fileName = "image-\(UUID().uuidString).jpg" - let (_, tempURL) = try image.save(to: tempDirectory, withName: fileName, format: .jpeg) - defer { try? FileManager.default.removeItem(at: tempURL) } - return .document(try FileCache.saveDocumentWithImmediateThumbnail(url: tempURL)) - } - - return .photo(try FileCache.savePhoto(image: image, optimize: optimizePhoto)) - } - - private func resetComposeStateAfterPreviewSend() { - autocompleteManager?.dismissCompletion() - if let attributed = textView.attributedText?.mutableCopy() as? NSMutableAttributedString { - let marker = "\u{FFFC}" as NSString - var range = (attributed.string as NSString).range(of: marker as String) - while range.location != NSNotFound { - attributed.replaceCharacters(in: range, with: "") - range = (attributed.string as NSString).range(of: marker as String) - } - textView.attributedText = attributed - } - - textView.resetTypingAttributesToDefault() - textView.font = .systemFont(ofSize: 17) - textView.typingAttributes[.font] = UIFont.systemFont(ofSize: 17) - - let normalizedText = (textView.text ?? "").replacingOccurrences(of: "\u{FFFC}", with: "") - let isEmpty = normalizedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - (textView as? ComposeTextView)?.showPlaceholder(isEmpty) - updateSendButtonVisibility() - } - - private func presentSingleImagePreview(_ image: UIImage, presenter: UIViewController? = nil) { - guard !previewViewModel.isPresented, !multiPhotoPreviewViewModel.isPresented else { return } - guard let resolvedPresenter = presenter ?? attachmentFlowPresenter() else { return } - - selectedImage = image - previewViewModel.isPresented = true - currentPreviewUsesAttachmentPicker = attachmentPickerViewController != nil - - let previewView = SwiftUIPhotoPreviewView( - image: image, - caption: Binding( - get: { [weak self] in self?.previewViewModel.caption ?? "" }, - set: { [weak self] newValue in self?.previewViewModel.caption = newValue } - ), - isPresented: Binding( - get: { [weak self] in self?.previewViewModel.isPresented ?? false }, - set: { [weak self] newValue in - self?.previewViewModel.isPresented = newValue - if !newValue { - self?.dismissPreview() - } - } - ), - onSend: { [weak self] image, caption in - self?.sendImage(image, caption: caption) - }, - onAddMorePhotos: { [weak self] in - self?.presentPicker() - } - ) - - let previewVC = UIHostingController(rootView: previewView) - previewVC.modalPresentationStyle = .fullScreen - previewVC.modalTransitionStyle = .crossDissolve - - resolvedPresenter.present(previewVC, animated: true) - } - - private func presentMultiImagePreview(_ images: [UIImage], presenter: UIViewController? = nil) { - guard !images.isEmpty else { return } - guard !previewViewModel.isPresented, !multiPhotoPreviewViewModel.isPresented else { return } - guard let resolvedPresenter = presenter ?? attachmentFlowPresenter() else { return } - - multiPhotoPreviewViewModel.setPhotos(images) - multiPhotoPreviewViewModel.isPresented = true - currentPreviewUsesAttachmentPicker = attachmentPickerViewController != nil - - let multiPreviewView = SwiftUIPhotoPreviewView( - viewModel: multiPhotoPreviewViewModel, - isPresented: Binding( - get: { [weak self] in self?.multiPhotoPreviewViewModel.isPresented ?? false }, - set: { [weak self] newValue in - self?.multiPhotoPreviewViewModel.isPresented = newValue - if !newValue { - self?.dismissMultiPreview() - } - } - ), - onSend: { [weak self] photoItems in - self?.sendMultipleImages(photoItems) - }, - onAddMorePhotos: { [weak self] in - self?.presentPicker() - } - ) - - let previewVC = UIHostingController(rootView: multiPreviewView) - previewVC.modalPresentationStyle = .fullScreen - previewVC.modalTransitionStyle = .crossDissolve - - resolvedPresenter.present(previewVC, animated: true) - } - // MARK: - UIImagePickerControllerDelegate func presentPicker() { @@ -233,175 +119,6 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe addImages(images) } - func dismissPreview(dismissAttachmentPicker: Bool = false) { - var responder: UIResponder? = self - var currentVC: UIViewController? - - while let nextResponder = responder?.next { - if let viewController = nextResponder as? UIViewController { - currentVC = viewController - break - } - responder = nextResponder - } - - guard let currentVC else { return } - - var topmostVC = currentVC - while let presentedVC = topmostVC.presentedViewController { - topmostVC = presentedVC - } - - let picker = topmostVC.presentingViewController as? PHPickerViewController - - let finalizeDismissal: () -> Void = { [weak self] in - guard let self else { return } - self.selectedImage = nil - self.previewViewModel.caption = "" - self.previewViewModel.isPresented = false - self.currentPreviewUsesAttachmentPicker = false - - if dismissAttachmentPicker { - self.dismissAttachmentPickerIfPresented(animated: true) - } - } - - topmostVC.dismiss(animated: true) { [weak self] in - if let picker { - picker.dismiss(animated: true) { [weak self] in - self?.isPickerPresented = false - finalizeDismissal() - } - } else { - finalizeDismissal() - } - } - } - - func dismissMultiPreview(dismissAttachmentPicker: Bool = false) { - var responder: UIResponder? = self - var currentVC: UIViewController? - - while let nextResponder = responder?.next { - if let viewController = nextResponder as? UIViewController { - currentVC = viewController - break - } - responder = nextResponder - } - - guard let currentVC else { return } - - var topmostVC = currentVC - while let presentedVC = topmostVC.presentedViewController { - topmostVC = presentedVC - } - - let picker = topmostVC.presentingViewController as? PHPickerViewController - - let finalizeDismissal: () -> Void = { [weak self] in - guard let self else { return } - self.multiPhotoPreviewViewModel.photoItems.removeAll() - self.multiPhotoPreviewViewModel.currentIndex = 0 - self.multiPhotoPreviewViewModel.isPresented = false - self.currentPreviewUsesAttachmentPicker = false - - if dismissAttachmentPicker { - self.dismissAttachmentPickerIfPresented(animated: true) - } - } - - topmostVC.dismiss(animated: true) { [weak self] in - if let picker { - picker.dismiss(animated: true) { [weak self] in - self?.isPickerPresented = false - finalizeDismissal() - } - } else { - finalizeDismissal() - } - } - } - - func sendImage(_ image: UIImage, caption: String) { - guard let peerId else { return } - - clearAttachments() - - do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: false) - let uniqueId = mediaItem.getItemUniqueId() - attachmentItems[uniqueId] = mediaItem - } catch { - Log.shared.error("Failed to save photo", error: error) - } - - let didPrepareImage = !attachmentItems.isEmpty - for (_, attachment) in attachmentItems { - Transactions.shared.mutate( - transaction: .sendMessage( - .init( - text: caption, - peerId: peerId, - chatId: chatId ?? 0, - mediaItems: [attachment], - replyToMsgId: ChatState.shared.getState(peer: peerId).replyingMessageId, - isSticker: nil, - entities: nil - ) - ) - ) - } - - if didPrepareImage, let chatId { - IntentDonationCoordinator.donateOutgoing(peerId: peerId, chatId: chatId) - } - - resetComposeStateAfterPreviewSend() - dismissPreview(dismissAttachmentPicker: currentPreviewUsesAttachmentPicker) - clearAttachments() - // sendMessageHaptic() - } - - func sendMultipleImages(_ photoItems: [PhotoItem]) { - guard let peerId else { return } - - let replyToMessageId = ChatState.shared.getState(peer: peerId).replyingMessageId - - var items: [AlbumSendItem] = [] - for (index, photoItem) in photoItems.enumerated() { - do { - let mediaItem = try makeImageAttachment(photoItem.image, optimizePhoto: true) - // Each photo keeps its own caption; the album shows the first one. - let captionText = photoItem.caption?.trimmingCharacters(in: .whitespacesAndNewlines) - items.append(AlbumSendItem(media: mediaItem, text: captionText?.isEmpty == false ? captionText : nil)) - } catch { - Log.shared.error("Failed to save and send photo \(index + 1)", error: error) - } - } - // Photos picked together go out as albums of up to ten. - for send in TransactionSendMessage.sends( - peerId: peerId, - chatId: chatId ?? 0, - items: items, - replyToMsgId: replyToMessageId - ) { - Transactions.shared.mutate(transaction: .sendMessage(send)) - } - let didSendImage = !items.isEmpty - - if didSendImage, let chatId { - IntentDonationCoordinator.donateOutgoing(peerId: peerId, chatId: chatId) - } - - // Clear state and dismiss - resetComposeStateAfterPreviewSend() - dismissMultiPreview(dismissAttachmentPicker: currentPreviewUsesAttachmentPicker) - clearAttachments() - ChatState.shared.clearReplyingMessageId(peer: peerId) - // sendMessageHaptic() - } - func handlePastedImage() { if let gifData = UIPasteboard.general.data(forPasteboardType: UTType.gif.identifier) ?? UIPasteboard.general.data(forPasteboardType: "com.compuserve.gif") ?? @@ -419,7 +136,15 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe } } - guard let image = UIPasteboard.general.image else { return } + // Encoded bytes keep the camera details that pick the size, and serve as the original. + let pasteboard = UIPasteboard.general + for type in [UTType.heic, UTType.jpeg, UTType.png, UTType.webP, UTType.tiff] { + if let data = pasteboard.data(forPasteboardType: type.identifier) { + addPhotos([(.data(data), nil)]) + return + } + } + guard let image = pasteboard.image else { return } addImages([image]) } @@ -427,24 +152,52 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe addImages([image]) } - func addImages(_ images: [UIImage]) { - guard !images.isEmpty else { return } + func addImages(_ images: [UIImage], content: MediaSendPreparation.PhotoContent? = nil) { + addPhotos(images.map { (MediaSendPreparation.PhotoSource.platformImage($0), nil) }, content: content) + } - var didAddAny = false - for image in images { - do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: true) - let uniqueId = mediaItem.getItemUniqueId() - attachmentItems[uniqueId] = mediaItem - didAddAny = true - Log.shared.debug("Added image attachment with uniqueId: \(uniqueId)") - } catch { - Log.shared.error("Failed to save photo in attachments", error: error) + /// Prepares photos off the main thread (resized for their content, no metadata) and adds them + /// in the order given. + func addPhotos( + _ sources: [(source: MediaSendPreparation.PhotoSource, fileName: String?)], + content: MediaSendPreparation.PhotoContent? = nil + ) { + guard !sources.isEmpty else { return } + Task { [weak self] in + let items = await Self.preparePhotos(sources, content: content) + guard let self, !items.isEmpty else { return } + for item in items { + attachmentItems[item.getItemUniqueId()] = item } + handleAttachmentItemsChanged(animated: false) } + } - if didAddAny { - handleAttachmentItemsChanged(animated: false) + nonisolated static func preparePhotos( + _ sources: [(source: MediaSendPreparation.PhotoSource, fileName: String?)], + content: MediaSendPreparation.PhotoContent? = nil + ) async -> [FileMediaItem] { + await withTaskGroup(of: (Int, FileMediaItem?).self) { group in + for (index, entry) in sources.enumerated() { + group.addTask { + do { + let item = try await AttachmentMediaMaterializer.photo( + entry.source, + originalFileName: entry.fileName, + content: content + ) + return (index, item) + } catch { + Log.shared.error("Failed to save photo in attachments", error: error) + return (index, nil) + } + } + } + var prepared: [(Int, FileMediaItem)] = [] + for await (index, item) in group { + if let item { prepared.append((index, item)) } + } + return prepared.sorted { $0.0 < $1.0 }.map(\.1) } } @@ -564,28 +317,25 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe } } } catch AnimatedImageVideoConversionError.notAnimated { + // A still image after all: send it as a photo, prepared from the file. + let mediaItem = try? await AttachmentMediaMaterializer.photo(.file(url), originalFileName: url.lastPathComponent) await MainActor.run { [weak self] in guard let self else { return } guard !isPendingVideoAttachmentCanceled(pendingId) else { finishPendingVideoAttachmentProcessing(pendingId) + if case let .photo(photoInfo)? = mediaItem { + Task { await FileCache.discardLocalPhoto(photoInfo) } + } return } - - guard let image = UIImage(contentsOfFile: url.path) else { + guard let mediaItem else { + Log.shared.error("Failed to save animated image fallback") cancelQueuedPendingVideoSend() completePendingVideoAttachments([pendingId]) return } - - do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: true) - attachmentItems[mediaItem.getItemUniqueId()] = mediaItem - completePendingVideoAttachments([pendingId]) - } catch { - Log.shared.error("Failed to save animated image fallback", error: error) - cancelQueuedPendingVideoSend() - completePendingVideoAttachments([pendingId]) - } + attachmentItems[mediaItem.getItemUniqueId()] = mediaItem + completePendingVideoAttachments([pendingId]) } } catch { Log.shared.error("Failed to save animated image as video", error: error) @@ -689,12 +439,14 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe return .failure(.message("Unsupported recent media type.")) } - guard let image = await loadRecentImage(from: asset) else { + guard let data = await loadRecentImageData(from: asset) else { return .failure(.message("Couldn't open that recent photo.")) } do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: true) + let fileName = PHAssetResource.assetResources(for: asset) + .first { $0.type == .photo || $0.type == .fullSizePhoto }?.originalFilename + let mediaItem = try await AttachmentMediaMaterializer.photo(.data(data), originalFileName: fileName) return .success(mediaItem) } catch { Log.shared.error("Failed to save photo in attachments", error: error) @@ -702,7 +454,7 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe } } - private func loadRecentImage(from asset: PHAsset) async -> UIImage? { + private func loadRecentImageData(from asset: PHAsset) async -> Data? { let options = PHImageRequestOptions() options.deliveryMode = .highQualityFormat options.resizeMode = .none @@ -716,12 +468,7 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe return } - guard let data, let image = UIImage(data: data) else { - continuation.resume(returning: nil) - return - } - - continuation.resume(returning: image) + continuation.resume(returning: data) } } } @@ -800,7 +547,7 @@ extension ComposeView: PHPickerViewControllerDelegate { } private enum LibraryPickerItem { - case image(UIImage) + case photo(FileMediaItem) case video(FileMediaItem) } @@ -856,15 +603,8 @@ extension ComposeView: PHPickerViewControllerDelegate { for entry in sortedEntries { let item = entry.item switch item { - case let .image(image): - do { - let mediaItem = try makeImageAttachment(image, optimizePhoto: true) - let uniqueId = mediaItem.getItemUniqueId() - attachmentItems[uniqueId] = mediaItem - } catch { - Log.shared.error("Failed to save photo in attachments", error: error) - cancelQueuedPendingVideoSend() - } + case let .photo(mediaItem): + attachmentItems[mediaItem.getItemUniqueId()] = mediaItem case let .video(videoItem): if let pendingId = pendingVideoIdsByIndex[entry.index], isPendingVideoAttachmentCanceled(pendingId) { continue @@ -974,8 +714,8 @@ extension ComposeView: PHPickerViewControllerDelegate { if let item = await loadAnimatedImageVideoItem(from: result) { return .video(item) } - if let image = await loadImageItem(from: result) { - return .image(image) + if let item = await loadPhotoItem(from: result) { + return .photo(item) } case .none, .some(.unknown): break @@ -983,8 +723,8 @@ extension ComposeView: PHPickerViewControllerDelegate { break } - if let image = await loadImageItem(from: result) { - return .image(image) + if let item = await loadPhotoItem(from: result) { + return .photo(item) } if let item = await loadVideoItem(from: result) { @@ -1057,16 +797,56 @@ extension ComposeView: PHPickerViewControllerDelegate { } } - private func loadImageItem(from result: PHPickerResult) async -> UIImage? { - await withCheckedContinuation { continuation in - result.itemProvider.loadObject(ofClass: UIImage.self) { object, error in + /// Loads the picked file itself (HEIC, JPEG, PNG…): its camera details pick the size it's + /// sent at, and it is kept as the original. Falls back to a decoded image. + private nonisolated func loadPhotoItem(from result: PHPickerResult) async -> FileMediaItem? { + let provider = result.itemProvider + if let typeIdentifier = provider.registeredTypeIdentifiers.first(where: { + UTType($0)?.conforms(to: .image) == true + }), + let file = await loadPhotoFileRepresentation(provider, typeIdentifier: typeIdentifier) + { + defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) } + do { + return try await AttachmentMediaMaterializer.photo(.file(file), originalFileName: file.lastPathComponent) + } catch { + Log.shared.error("Failed to prepare picked photo file", error: error) + } + } + + let image: UIImage? = await withCheckedContinuation { continuation in + provider.loadObject(ofClass: UIImage.self) { object, error in if let error { Log.shared.error("Failed to load image from picker", error: error) + } + continuation.resume(returning: object as? UIImage) + } + } + guard let image else { return nil } + return try? await AttachmentMediaMaterializer.photo(.platformImage(image)) + } + + /// Copies the provider's file before its callback returns, when the system deletes it. + private nonisolated func loadPhotoFileRepresentation(_ provider: NSItemProvider, typeIdentifier: String) async -> URL? { + await withCheckedContinuation { continuation in + provider.loadFileRepresentation(forTypeIdentifier: typeIdentifier) { url, error in + guard let url else { + if let error { Log.shared.error("Failed to load picked photo file", error: error) } continuation.resume(returning: nil) return } - - continuation.resume(returning: object as? UIImage) + let folder = FileHelpers.getTrueTemporaryDirectory() + .appendingPathComponent("picked-\(UUID().uuidString)", isDirectory: true) + do { + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let copy = folder.appendingPathComponent(url.lastPathComponent) + try FileManager.default.copyItem(at: url, to: copy) + continuation.resume(returning: copy) + } catch { + Log.shared.error("Failed to copy picked photo file", error: error) + try? FileManager.default.removeItem(at: folder) + continuation.resume(returning: nil) + } } } } @@ -1251,7 +1031,7 @@ extension ComposeView { } picker.dismiss(animated: true) { [weak self] in - self?.addImages([image]) + self?.addImages([image], content: .camera) self?.dismissAttachmentPickerIfPresented(animated: true) } } else if mediaType == UTType.movie.identifier { diff --git a/apple/InlineShareExtension/ShareState.swift b/apple/InlineShareExtension/ShareState.swift index 8524a715b3..94956f876c 100644 --- a/apple/InlineShareExtension/ShareState.swift +++ b/apple/InlineShareExtension/ShareState.swift @@ -146,7 +146,6 @@ class ShareState: ObservableObject { private nonisolated static let maxUrls = 10 private nonisolated static let imageCompressionQuality: CGFloat = 0.52 private nonisolated static let maxPhotoUploadDimension = 1280 - private nonisolated static let photoOptimizationThresholdBytes = 1_500_000 private nonisolated static let maxFileSizeBytes: Int64 = 100 * 1024 * 1024 private nonisolated static let maxVideoFileSizeBytes: Int64 = maxFileSizeBytes private nonisolated static func maxFileSizeDisplay(for bytes: Int64) -> String { @@ -270,46 +269,6 @@ class ShareState: ObservableObject { return MIMEType(text: "application/octet-stream") } - private nonisolated func shouldTranscodePhotoToJpeg( - suggestedName: String?, - typeIdentifier: String?, - mimeType: MIMEType? - ) -> Bool { - if let typeIdentifier, - let utType = UTType(typeIdentifier), - utType.conforms(to: .heic) || utType.conforms(to: .heif) - { - return true - } - - if let suggestedName { - let ext = (suggestedName as NSString).pathExtension.lowercased() - if ext == "heic" || ext == "heif" { - return true - } - } - - if let mimeType { - let lowercased = mimeType.text.lowercased() - if lowercased == "image/heic" || - lowercased == "image/heif" || - lowercased == "image/heic-sequence" || - lowercased == "image/heif-sequence" - { - return true - } - } - - return false - } - - private nonisolated func jpegFileName(from fileName: String?) -> String { - let baseName = (fileName ?? "shared_image") as NSString - let stem = baseName.deletingPathExtension - let safeStem = stem.isEmpty ? "shared_image" : stem - return "\(safeStem).jpg" - } - private nonisolated func imageFileName( from fileName: String?, typeIdentifier: String @@ -338,33 +297,6 @@ class ShareState: ObservableObject { return identifier } - private nonisolated func writeThumbnailJpeg(from source: CGImageSource, to destinationURL: URL) -> Bool { - autoreleasepool { - let options: [CFString: Any] = [ - kCGImageSourceShouldCache: false, - kCGImageSourceShouldCacheImmediately: true, - kCGImageSourceCreateThumbnailFromImageAlways: true, - kCGImageSourceCreateThumbnailWithTransform: true, - kCGImageSourceThumbnailMaxPixelSize: Self.maxPhotoUploadDimension, - ] - guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary), - let destination = CGImageDestinationCreateWithURL( - destinationURL as CFURL, - UTType.jpeg.identifier as CFString, - 1, - nil - ) - else { - return false - } - let properties: [CFString: Any] = [ - kCGImageDestinationLossyCompressionQuality: Self.imageCompressionQuality, - ] - CGImageDestinationAddImage(destination, cgImage, properties as CFDictionary) - return CGImageDestinationFinalize(destination) - } - } - private nonisolated func jpegData( from cgImage: CGImage, compressionQuality: CGFloat = ShareState.imageCompressionQuality @@ -388,172 +320,38 @@ class ShareState: ObservableObject { } } - private nonisolated func photoPixelSize(from url: URL) -> CGSize? { - guard let source = CGImageSourceCreateWithURL(url as CFURL, imageSourceReadOptions()) else { - return nil - } - return photoPixelSize(from: source) - } - - private nonisolated func photoPixelSize(from source: CGImageSource) -> CGSize? { - guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, imageSourceReadOptions()) as? [CFString: Any] else { - return nil - } - - guard let width = properties[kCGImagePropertyPixelWidth] as? NSNumber, - let height = properties[kCGImagePropertyPixelHeight] as? NSNumber - else { - return nil - } - return CGSize(width: CGFloat(truncating: width), height: CGFloat(truncating: height)) - } - - private nonisolated func optimizedPhotoUploadFile( - from url: URL, - suggestedName: String?, - cleanupURLs: [URL] - ) throws -> PreparedSharedFile? { - guard let source = CGImageSourceCreateWithURL(url as CFURL, imageSourceReadOptions()), - let pixelSize = photoPixelSize(from: source) - else { - return nil - } - - let fileSize = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize - let largestDimension = max(pixelSize.width, pixelSize.height) - let shouldOptimize = largestDimension > CGFloat(Self.maxPhotoUploadDimension) || - (fileSize ?? 0) > Self.photoOptimizationThresholdBytes - guard shouldOptimize else { return nil } - - return try downsampledPhotoFile( - from: source, - fileName: jpegFileName(from: suggestedName), - cleanupURLs: cleanupURLs, - originalFileSize: fileSize.map { Int64($0) } - ) - } - - private nonisolated func downsampledPhotoFile( + private nonisolated func preparedPhotoFile( from url: URL, fileName: String, cleanupURLs: [URL] - ) throws -> PreparedSharedFile? { - guard let source = CGImageSourceCreateWithURL(url as CFURL, imageSourceReadOptions()) else { - return nil - } - return try downsampledPhotoFile( - from: source, - fileName: fileName, - cleanupURLs: cleanupURLs, - originalFileSize: nil - ) - } - - private nonisolated func downsampledPhotoFile( - from source: CGImageSource, - fileName: String, - cleanupURLs: [URL], - originalFileSize: Int64? - ) throws -> PreparedSharedFile? { - let tempURL = temporaryURL( - suggestedName: fileName, - typeIdentifier: UTType.jpeg.identifier - ) - guard writeThumbnailJpeg(from: source, to: tempURL) else { - try? FileManager.default.removeItem(at: tempURL) - return nil - } - - let size = fileSize(for: tempURL) ?? 0 - if let originalFileSize, size >= originalFileSize { - try? FileManager.default.removeItem(at: tempURL) - return nil - } - - return PreparedSharedFile( - url: tempURL, - fileName: sanitizedFileName( - suggestedName: fileName, - fallbackURL: tempURL, - typeIdentifier: UTType.jpeg.identifier - ), - mimeType: MIMEType(text: "image/jpeg"), - fileType: .photo, - fileSize: size, - isAnimatedImage: false, - videoMetadata: nil, - cleanupURLs: cleanupURLs + [tempURL] - ) - } - - /// JPEG and PNG photos can embed EXIF GPS; GIF cannot. - private nonisolated func canCarryPhotoLocation(mimeType: MIMEType) -> Bool { - let lowercased = mimeType.text.lowercased() - return lowercased == "image/jpeg" || lowercased == "image/jpg" || lowercased == "image/png" - } - - /// A photo sent at its original size must not carry where it was taken. Its metadata is - /// rewritten without GPS and its pixels and orientation tag are copied untouched; if ImageIO - /// cannot rewrite it, it is re-encoded with the orientation applied and no metadata at all. - private nonisolated func locationFreePhotoFile( - from url: URL, - fileName: String, - mimeType: MIMEType, - cleanupURLs: [URL] - ) throws -> PreparedSharedFile? { - guard let source = CGImageSourceCreateWithURL(url as CFURL, imageSourceReadOptions()), - let sourceType = CGImageSourceGetType(source) - else { - return nil - } - - let tempURL = temporaryURL(suggestedName: fileName, typeIdentifier: sourceType as String) - let copied: Bool = autoreleasepool { - guard let destination = CGImageDestinationCreateWithURL(tempURL as CFURL, sourceType, 1, nil) else { - return false - } - let options: [CFString: Any] = [kCGImageMetadataShouldExcludeGPS: true] - // Writes the destination itself; it must not be finalized afterwards. - return CGImageDestinationCopyImageSource(destination, source, options as CFDictionary, nil) - } - guard copied else { - try? FileManager.default.removeItem(at: tempURL) - return try downsampledPhotoFile( - from: source, - fileName: jpegFileName(from: fileName), - cleanupURLs: cleanupURLs, - originalFileSize: nil + ) -> PreparedSharedFile? { + do { + let prepared = try MediaSendPreparation.preparePhoto(.file(url)) + let baseName = (fileName as NSString).deletingPathExtension + let preparedName = (baseName.isEmpty ? "photo" : baseName) + prepared.format.toExt() + let preparedURL = temporaryURL(suggestedName: preparedName, typeIdentifier: prepared.format == .png + ? UTType.png.identifier + : UTType.jpeg.identifier) + try prepared.data.write(to: preparedURL, options: .atomic) + return PreparedSharedFile( + url: preparedURL, + fileName: preparedName, + mimeType: MIMEType(text: prepared.format.toMimeType()), + fileType: .photo, + fileSize: Int64(prepared.data.count), + isAnimatedImage: false, + videoMetadata: nil, + cleanupURLs: cleanupURLs + [preparedURL] ) + } catch { + log.warning(tagged("Photo preparation failed error=\(error.localizedDescription)")) + return nil } - - return PreparedSharedFile( - url: tempURL, - fileName: fileName, - mimeType: mimeType, - fileType: .photo, - fileSize: fileSize(for: tempURL) ?? 0, - isAnimatedImage: false, - videoMetadata: nil, - cleanupURLs: cleanupURLs + [tempURL] - ) } private nonisolated func shouldSendPhotoAsDocument(at url: URL) -> Bool { - guard let pixelSize = photoPixelSize(from: url) else { return false } - let width = max(pixelSize.width, 1) - let height = max(pixelSize.height, 1) - let ratio = max(width / height, height / width) - return ratio > 20 || (width < 50 && height < 50) - } - - private nonisolated func isSupportedPhotoMimeType(_ mimeType: MIMEType) -> Bool { - let lowercased = mimeType.text.lowercased() - return lowercased == "image/jpeg" || lowercased == "image/png" || lowercased == "image/gif" - } - - private nonisolated func shouldOptimizePhotoUpload(mimeType: MIMEType) -> Bool { - let lowercased = mimeType.text.lowercased() - return lowercased == "image/jpeg" || lowercased == "image/jpg" + guard let size = MediaSendPreparation.pixelSize(of: .file(url)) else { return false } + return MediaSendPreparation.shouldSendAsDocument(width: size.width, height: size.height) } private nonisolated func isGIF( @@ -1376,56 +1174,19 @@ class ShareState: ObservableObject { isAnimatedImage = true } - if resolvedFileType == .photo && - (shouldTranscodePhotoToJpeg( - suggestedName: fileName, - typeIdentifier: file.typeIdentifier, - mimeType: mimeType - ) || !isSupportedPhotoMimeType(mimeType)) - { - if let photoFile = try downsampledPhotoFile( - from: file.url, - fileName: jpegFileName(from: fileName), - cleanupURLs: file.cleanupURLs - ) { - return photoFile - } - - if shouldTranscodePhotoToJpeg( - suggestedName: fileName, - typeIdentifier: file.typeIdentifier, - mimeType: mimeType - ) { - log.warning(tagged("Failed to transcode HEIC photo; falling back to document")) - ExtensionHealth.record("app.fallback", ["fallback_kind": "share_photo_heic_as_document"]) - } else { - log.warning(tagged("Unsupported photo MIME type; falling back to document (\(mimeType.text))")) - ExtensionHealth.record("app.fallback", ["fallback_kind": "share_photo_mime_as_document"]) - } - resolvedFileType = .document - } - + // Photos go out the way the app sends them: resized for their content, upright, and with no + // camera, place or time details (see MediaSendPreparation). Anything that can't be prepared + // is sent as a file rather than as an unprocessed photo. if resolvedFileType == .photo { if shouldSendPhotoAsDocument(at: file.url) { resolvedFileType = .document log.warning(tagged("Photo aspect ratio is too extreme; sending as document")) - } else if shouldOptimizePhotoUpload(mimeType: mimeType), - let optimized = try optimizedPhotoUploadFile( - from: file.url, - suggestedName: fileName, - cleanupURLs: file.cleanupURLs - ) { - return optimized - } else if canCarryPhotoLocation(mimeType: mimeType) { - if let stripped = try locationFreePhotoFile( - from: file.url, - fileName: fileName, - mimeType: mimeType, - cleanupURLs: file.cleanupURLs - ) { - return stripped - } - log.warning(tagged("Could not remove photo location metadata; uploading the original")) + } else if let photoFile = preparedPhotoFile(from: file.url, fileName: fileName, cleanupURLs: file.cleanupURLs) { + return photoFile + } else { + log.warning(tagged("Couldn't prepare photo; sending as document (\(mimeType.text))")) + ExtensionHealth.record("app.fallback", ["fallback_kind": "share_photo_as_document"]) + resolvedFileType = .document } } @@ -1491,19 +1252,17 @@ class ShareState: ObservableObject { return try await prepareAnimatedImageVideoForUpload(file) } - let needsMp4Transcode = file.url.pathExtension.lowercased() != "mp4" - let options = VideoCompressionOptions.uploadDefault(forceTranscode: needsMp4Transcode) - let originalFileSize = file.fileSize - log.debug(tagged( - "Preparing video upload transcodeRequired=\(needsMp4Transcode) size=\(originalFileSize)" - )) - + // Always a new file: remuxed when already small H.264, otherwise re-encoded for its content. + // Either way it carries no location or device details. A failure fails the share. + let content = await VideoCompressor.content(of: file.url) + log.debug(tagged("Preparing video upload content=\(content.rawValue) size=\(file.fileSize)")) do { - let result = try await VideoCompressor.shared.compressVideo(at: file.url, options: options) + let result = try await VideoCompressor.shared.compressVideo(at: file.url, options: .upload(for: content)) let baseName = (file.fileName as NSString).deletingPathExtension let resolvedName = baseName.isEmpty ? "video.mp4" : "\(baseName).mp4" let mimeType = MIMEType(text: FileHelpers.getMimeType(for: result.url)) - let preparedFile = PreparedSharedFile( + log.debug(tagged("Video preparation completed size=\(result.fileSize)")) + return PreparedSharedFile( url: result.url, fileName: resolvedName, mimeType: mimeType, @@ -1513,45 +1272,14 @@ class ShareState: ObservableObject { videoMetadata: nil, cleanupURLs: file.cleanupURLs + [result.url] ) - log.debug(tagged("Video compression completed size=\(result.fileSize)")) - return preparedFile - } catch VideoCompressionError.compressionNotNeeded, VideoCompressionError.compressionNotEffective { - if needsMp4Transcode { - throw NSError( - domain: "ShareError", - code: 11, - userInfo: [NSLocalizedDescriptionKey: "Failed to convert video to MP4."] - ) - } - log.debug(tagged("Video compression skipped; using original MP4")) - return PreparedSharedFile( - url: file.url, - fileName: file.fileName, - mimeType: file.mimeType, - fileType: .video, - fileSize: originalFileSize, - isAnimatedImage: false, - videoMetadata: file.videoMetadata, - cleanupURLs: file.cleanupURLs - ) + } catch is CancellationError { + throw CancellationError() } catch { - if needsMp4Transcode { - throw NSError( - domain: "ShareError", - code: 12, - userInfo: [NSLocalizedDescriptionKey: "Failed to compress video for upload."] - ) - } - log.debug(tagged("Video compression failed; using original MP4 error=\(error.localizedDescription)")) - return PreparedSharedFile( - url: file.url, - fileName: file.fileName, - mimeType: file.mimeType, - fileType: .video, - fileSize: originalFileSize, - isAnimatedImage: false, - videoMetadata: file.videoMetadata, - cleanupURLs: file.cleanupURLs + log.warning(tagged("Video preparation failed error=\(error.localizedDescription)")) + throw NSError( + domain: "ShareError", + code: 12, + userInfo: [NSLocalizedDescriptionKey: "Failed to prepare video for upload."] ) } } From e4173eac50193275f2adfc6df783e9b5b8491135 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sat, 21 Nov 2026 00:41:13 +0330 Subject: [PATCH 03/14] macos: add an original toggle to the composer attachments An Original checkbox ends the media row when photos or videos are attached, for messages and new threads. With it on, each one is sent as its untouched file, and it resets after the send. Images from a file are prepared from that file, the media picker builds a small preview instead of decoding the full image on the main thread, and GIFs keep their animation. --- .../Views/Compose/ComposeAttachments.swift | 42 ++++++++++++++++- .../Views/Compose/ComposeMenuButton.swift | 22 ++++++++- .../Views/Compose/GlassComposeAppKit.swift | 47 +++++++++++-------- .../Views/Compose/LegacyComposeAppKit.swift | 42 ++++++++++------- .../Compose/NewThreadComposeContext.swift | 28 ++++++++--- 5 files changed, 133 insertions(+), 48 deletions(-) diff --git a/apple/InlineMac/Views/Compose/ComposeAttachments.swift b/apple/InlineMac/Views/Compose/ComposeAttachments.swift index b6a36d77f0..63927961df 100644 --- a/apple/InlineMac/Views/Compose/ComposeAttachments.swift +++ b/apple/InlineMac/Views/Compose/ComposeAttachments.swift @@ -84,6 +84,30 @@ final class ComposeAttachments: NSView { private var documentCollectionHeightConstraint: NSLayoutConstraint! private var mediaTopConstraint: NSLayoutConstraint! private var documentsLeadingConstraint: NSLayoutConstraint! + private var mediaTrailingConstraint: NSLayoutConstraint! + private var mediaTrailingToToggleConstraint: NSLayoutConstraint! + + /// Off: photos and videos go compressed, with no location or camera details. On: they go as + /// their untouched files. Resets when the attachments are cleared, after a send. + private(set) var sendsMediaAsOriginal = false { + didSet { originalToggle.state = sendsMediaAsOriginal ? .on : .off } + } + + private lazy var originalToggle: NSButton = { + let button = NSButton(checkboxWithTitle: "Original", target: self, action: #selector(toggleOriginal)) + button.controlSize = .small + button.font = .systemFont(ofSize: NSFont.smallSystemFontSize) + button.contentTintColor = .secondaryLabelColor + button.toolTip = "Send photos and videos as files, unchanged, including their location and camera details." + button.setAccessibilityLabel("Send originals") + button.translatesAutoresizingMaskIntoConstraints = false + button.isHidden = true + return button + }() + + @objc private func toggleOriginal() { + sendsMediaAsOriginal = originalToggle.state == .on + } private var verticalPadding: CGFloat = Theme.composeAttachmentsVPadding private var isExternallyCollapsed = false @@ -176,6 +200,10 @@ final class ComposeAttachments: NSView { self.documentScrollHeightConstraint.constant = documentViewportHeight self.documentCollectionHeightConstraint.constant = documentContentHeight self.mediaScrollView.isHidden = mediaHeight == 0 + let showsOriginalToggle = mediaHeight > 0 + self.originalToggle.isHidden = !showsOriginalToggle + self.mediaTrailingConstraint.isActive = !showsOriginalToggle + self.mediaTrailingToToggleConstraint.isActive = showsOriginalToggle self.documentScrollView.isHidden = self.isExternallyCollapsed || self.documentModels.isEmpty self.documentLayout.sectionInset = (!self.isExternallyCollapsed && mediaHeight == 0 && !self.documentModels.isEmpty) ? NSEdgeInsets(top: self.verticalPadding, left: 0, bottom: self.verticalPadding, right: 0) @@ -258,6 +286,17 @@ final class ComposeAttachments: NSView { addSubview(mediaScrollView) addSubview(documentScrollView) + addSubview(originalToggle) + + mediaTrailingConstraint = mediaScrollView.trailingAnchor.constraint(equalTo: trailingAnchor) + mediaTrailingToToggleConstraint = mediaScrollView.trailingAnchor.constraint( + equalTo: originalToggle.leadingAnchor, + constant: -8 + ) + NSLayoutConstraint.activate([ + originalToggle.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -horizontalContentInset), + originalToggle.centerYAnchor.constraint(equalTo: mediaScrollView.centerYAnchor), + ]) documentsLeadingConstraint = documentCollectionView.leadingAnchor.constraint( equalTo: documentClipView.leadingAnchor, @@ -271,7 +310,7 @@ final class ComposeAttachments: NSView { documentCollectionHeightConstraint, mediaScrollView.leadingAnchor.constraint(equalTo: leadingAnchor), - mediaScrollView.trailingAnchor.constraint(equalTo: trailingAnchor), + mediaTrailingConstraint, mediaScrollView.topAnchor.constraint(equalTo: topAnchor), documentsLeadingConstraint, @@ -443,6 +482,7 @@ final class ComposeAttachments: NSView { public func clearViews(animated: Bool = false) { attachments.removeAll() + sendsMediaAsOriginal = false videoAttachments.removeAll() orderedMediaIds.removeAll() diff --git a/apple/InlineMac/Views/Compose/ComposeMenuButton.swift b/apple/InlineMac/Views/Compose/ComposeMenuButton.swift index 3275805a3c..73fb78318d 100644 --- a/apple/InlineMac/Views/Compose/ComposeMenuButton.swift +++ b/apple/InlineMac/Views/Compose/ComposeMenuButton.swift @@ -293,8 +293,12 @@ class ComposeMenuButton: NSView { for url in panel.urls { let type = UTType(filenameExtension: url.pathExtension) let isVideo = type?.conforms(to: .movie) == true || type?.conforms(to: .video) == true - if let image = NSImage(contentsOf: url), !isVideo { - delegate?.composeMenuButton(self, didSelectImage: image, url: url) + if type?.conforms(to: .gif) == true { + // The drop path keeps a GIF's animation; decoding it as an image flattened it. + delegate?.composeMenuButton(self, didSelectFiles: [url]) + } else if !isVideo, let preview = Self.previewImage(for: url) { + // A small preview for the attachment strip; the photo itself is prepared from the file. + delegate?.composeMenuButton(self, didSelectImage: preview, url: url) } else { delegate?.composeMenuButton(self, didSelectVideo: url) } @@ -302,6 +306,20 @@ class ComposeMenuButton: NSView { } } + private static func previewImage(for url: URL) -> NSImage? { + guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) + else { + return nil + } + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: 600, + ] + guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } + return NSImage(cgImage: image, size: .zero) + } + @objc private func openFilePicker() { let panel = NSOpenPanel() panel.allowsMultipleSelection = true diff --git a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift index e2a8a603fc..fcd6a8112a 100644 --- a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift @@ -2497,17 +2497,11 @@ class GlassComposeAppKit: NSView { let pendingId: String = switch usage { case .chat: - drafts2.addImage( - peer: peerId, - image: image, - preferredFormat: preferredImageFormat, - fallbackURL: url - ) + drafts2.addImage(peer: peerId, image: image, sourceURL: url) case let .newThread(context): context.attachmentStore.addImage( image, - preferredFormat: preferredImageFormat, - fallbackURL: url, + sourceURL: url, completion: { [weak self] result in self?.handleDraftAttachmentResult(result) } ) } @@ -2727,18 +2721,29 @@ class GlassComposeAppKit: NSView { } let effectiveSendMode = sendMode ?? (state.sendSilently ? .modeSilent : nil) + let sendsOriginals = attachments.sendsMediaAsOriginal func enqueueAttachments(replyToMessageId: Int64?) { - // Neighbouring photos and videos go out as albums; the text is the first one's caption. - for send in TransactionSendMessage.sends( - text: text, - peerId: destinationPeerId, - chatId: destinationChatId, // FIXME: chatId fallback - mediaItems: attachmentItemsSnapshot, - replyToMsgId: replyToMessageId, - entities: entities, - sendMode: effectiveSendMode - ) { - Transactions.shared.mutate(transaction: .sendMessage(send)) + func enqueue(_ mediaItems: [FileMediaItem]) { + // Neighbouring photos and videos go out as albums; the text is the first one's caption. + for send in TransactionSendMessage.sends( + text: text, + peerId: destinationPeerId, + chatId: destinationChatId, // FIXME: chatId fallback + mediaItems: mediaItems, + replyToMsgId: replyToMessageId, + entities: entities, + sendMode: effectiveSendMode + ) { + Transactions.shared.mutate(transaction: .sendMessage(send)) + } + } + guard sendsOriginals else { + enqueue(attachmentItemsSnapshot) + return + } + // Original: each photo and video goes as its untouched file, in the same order. + Task { @MainActor in + enqueue(await FileMediaItem.withOriginals(attachmentItemsSnapshot)) } } @@ -2912,12 +2917,14 @@ class GlassComposeAppKit: NSView { agentContext: context.agentContext() ) guard !draft.isEmpty else { return } + let sendsOriginals = attachments.sendsMediaAsOriginal isSubmittingNewThread = true setNewThreadAuthoringEnabled(false) updateSendButtonIfNeeded() Task { @MainActor [weak self] in + let draft = sendsOriginals ? await draft.withOriginalMedia() : draft let result = await context.submit(draft, intent) // Submission feedback belongs to the host, not this view's lifetime. // An early navigation may tear Compose down while the send is still @@ -3119,7 +3126,7 @@ class GlassComposeAppKit: NSView { Task.detached(priority: .userInitiated) { [weak self] in guard let self else { return } do { - let photoInfo = try FileCache.savePhoto(image: image, optimize: true) + let photoInfo = try FileCache.savePhoto(image: image) let mediaItem = FileMediaItem.photo(photoInfo) Transactions.shared.mutate( diff --git a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift index 1db7135586..8572fdd2c1 100644 --- a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift @@ -1605,12 +1605,7 @@ class LegacyComposeAppKit: NSView { } // Add a placeholder view immediately; Drafts2 owns file-cache persistence. - let pendingId = drafts2.addImage( - peer: peerId, - image: image, - preferredFormat: preferredImageFormat, - fallbackURL: url - ) + let pendingId = drafts2.addImage(peer: peerId, image: image, sourceURL: url) attachments.addImageView(image, id: pendingId) updateHeight(animate: true) } @@ -1775,18 +1770,29 @@ class LegacyComposeAppKit: NSView { } let effectiveSendMode = sendMode ?? (state.sendSilently ? .modeSilent : nil) + let sendsOriginals = attachments.sendsMediaAsOriginal func enqueueAttachments(replyToMessageId: Int64?) { - // Neighbouring photos and videos go out as albums; the text is the first one's caption. - for send in TransactionSendMessage.sends( - text: text, - peerId: destinationPeerId, - chatId: destinationChatId, // FIXME: chatId fallback - mediaItems: attachmentItemsSnapshot, - replyToMsgId: replyToMessageId, - entities: entities, - sendMode: effectiveSendMode - ) { - Transactions.shared.mutate(transaction: .sendMessage(send)) + func enqueue(_ mediaItems: [FileMediaItem]) { + // Neighbouring photos and videos go out as albums; the text is the first one's caption. + for send in TransactionSendMessage.sends( + text: text, + peerId: destinationPeerId, + chatId: destinationChatId, // FIXME: chatId fallback + mediaItems: mediaItems, + replyToMsgId: replyToMessageId, + entities: entities, + sendMode: effectiveSendMode + ) { + Transactions.shared.mutate(transaction: .sendMessage(send)) + } + } + guard sendsOriginals else { + enqueue(attachmentItemsSnapshot) + return + } + // Original: each photo and video goes as its untouched file, in the same order. + Task { @MainActor in + enqueue(await FileMediaItem.withOriginals(attachmentItemsSnapshot)) } } @@ -2079,7 +2085,7 @@ class LegacyComposeAppKit: NSView { Task.detached(priority: .userInitiated) { [weak self] in guard let self else { return } do { - let photoInfo = try FileCache.savePhoto(image: image, optimize: true) + let photoInfo = try FileCache.savePhoto(image: image) let mediaItem = FileMediaItem.photo(photoInfo) Transactions.shared.mutate( diff --git a/apple/InlineMac/Views/Compose/NewThreadComposeContext.swift b/apple/InlineMac/Views/Compose/NewThreadComposeContext.swift index 98535284e9..6602025cb3 100644 --- a/apple/InlineMac/Views/Compose/NewThreadComposeContext.swift +++ b/apple/InlineMac/Views/Compose/NewThreadComposeContext.swift @@ -52,16 +52,11 @@ final class NewThreadComposeAttachmentStore { @discardableResult func addImage( _ image: NSImage, - preferredFormat: ImageFormat?, - fallbackURL: URL?, + sourceURL: URL?, completion: @escaping Drafts2AttachmentCompletion ) -> String { materialize(prefix: "pending_photo", completion: completion) { - try await AttachmentMediaMaterializer.image( - image, - preferredFormat: preferredFormat, - sourceURL: fallbackURL - ) + try await AttachmentMediaMaterializer.image(image, sourceURL: sourceURL) } } @@ -192,6 +187,25 @@ final class DefaultNewThreadComposeMentionSource: NewThreadComposeMentionSource /// The immutable authoring result captured synchronously from the real Glass /// editor before any thread creation or network work starts. +extension PreparedNewThreadDraft { + /// The same draft with each photo and video swapped for its untouched file (Original on). + func withOriginalMedia() async -> PreparedNewThreadDraft { + let media = await FileMediaItem.withOriginals(attachments.map(\.media)) + let swapped = zip(attachments, media).map { attachment, media in + Drafts2Attachment(id: media.getItemUniqueId(), media: media, createdAt: attachment.createdAt) + } + return PreparedNewThreadDraft( + authorUserID: authorUserID, + text: text, + entities: entities, + attachments: swapped, + destination: destination, + sendSilently: sendSilently, + agentContext: agentContext + ) + } +} + struct PreparedNewThreadDraft { let authorUserID: Int64 let text: String From 68ca42ce7718a9b55a3bc2f2e1a9efb5a25fad1d Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sat, 21 Nov 2026 21:44:16 +0000 Subject: [PATCH 04/14] apple: switch attachments between photo and original file - Send as Original is now a conversion. switchedForOriginal turns a photo or video into a document of its kept original, and an image or video document back into a compressed photo or video. discardUnsent removes whichever form isn't kept. - canSwitchOriginal covers photos, videos and image or video files (not GIF or SVG). The menu summary reads size and location for files too. - A switched file joins the album after its photos and videos, as album sends already order files. - Drafts2.replaceAttachment keeps an attachment's place when it switches. - Removes the send-time swap (withOriginals, replacedWithOriginalDocument). --- .../InlineKit/Sources/InlineKit/Drafts2.swift | 21 ++ .../Files/AttachmentMediaMaterializer.swift | 9 +- .../InlineKit/Files/OriginalMediaStore.swift | 192 ++++++++++++++---- .../Tests/InlineKitTests/Drafts2Tests.swift | 22 ++ .../MediaSendPreparationTests.swift | 70 ++++++- 5 files changed, 269 insertions(+), 45 deletions(-) diff --git a/apple/InlineKit/Sources/InlineKit/Drafts2.swift b/apple/InlineKit/Sources/InlineKit/Drafts2.swift index 5625030944..ae6bf7edae 100644 --- a/apple/InlineKit/Sources/InlineKit/Drafts2.swift +++ b/apple/InlineKit/Sources/InlineKit/Drafts2.swift @@ -466,6 +466,27 @@ public final class Drafts2: @unchecked Sendable { } } + /// Puts another form of the same item in an attachment's place (Send as Original switches a + /// photo to its file and back). Returns the new attachment, or nil when `id` has left the + /// draft, for example because it was sent meanwhile. + @discardableResult + public func replaceAttachment(peer: Peer, id: String, with media: FileMediaItem) -> Drafts2Attachment? { + var replacement: Drafts2Attachment? + let snapshot = stage(peer: peer) { draft in + guard let index = draft.attachments.firstIndex(where: { $0.id == id }) else { return } + let attachment = Drafts2Attachment( + id: media.getItemUniqueId(), + media: media, + createdAt: draft.attachments[index].createdAt + ) + draft.attachments[index] = attachment + replacement = attachment + } + guard replacement != nil else { return nil } + persist(snapshot) + return replacement + } + public func removeAttachment(peer: Peer, id: String) { let peerKey = peer.toString() let taskKey = Self.pendingTaskKey(peerKey: peerKey, id: id) diff --git a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift index 9e4d13cf7b..3921549627 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift @@ -5,7 +5,7 @@ import Logger /// ever making that representation a requirement for retaining the source. public enum AttachmentMediaMaterializer { /// Prepares a picked photo for sending (see `MediaSendPreparation`) and keeps its untouched - /// source for the composer's Original toggle. Images too thin or too small to show as a photo + /// source for the item's Send as Original option. Images too thin or too small to show as a photo /// go as a file, as before. public static func photo( _ source: MediaSendPreparation.PhotoSource, @@ -53,7 +53,7 @@ public enum AttachmentMediaMaterializer { case .cgImage, .platformImage: // A camera capture handed over as pixels has no file behind it: keep a full-resolution // copy so Original still sends every pixel. Other pixel-only images (pastes, stickers) - // send the prepared photo even with Original on. + // send the prepared photo even when marked Send as Original. guard content == .camera else { break } let full = try MediaSendPreparation.preparePhoto( source, @@ -119,12 +119,13 @@ public enum AttachmentMediaMaterializer { public static func video( _ url: URL, - thumbnail: PlatformImage? = nil + thumbnail: PlatformImage? = nil, + originalFileName: String? = nil ) async throws -> FileMediaItem { try await withBareFileFallback { let video = FileMediaItem.video(try await FileCache.saveVideo(url: url, thumbnail: thumbnail)) do { - try OriginalMediaStore.retain(copyOf: url, for: video) + try OriginalMediaStore.retain(copyOf: url, fileName: originalFileName, for: video) } catch { Log.shared.warning("Couldn't keep the original video for sending as a file: \(error.localizedDescription)") } diff --git a/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift b/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift index c4726c2746..3712defb0a 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift @@ -1,8 +1,11 @@ +import AVFoundation import Foundation +import ImageIO import Logger +import UniformTypeIdentifiers /// Keeps the untouched file behind an attached photo or video until its message goes out, so -/// the composer's Original toggle can send that file instead of the compressed copy. Copies are +/// Send as Original can switch the item to that file instead of the compressed copy. Copies are /// clones on APFS, so keeping them costs almost no space. They live in the temporary directory: /// if the system clears it, the item is simply sent compressed. public enum OriginalMediaStore { @@ -90,56 +93,169 @@ public enum OriginalMediaStore { } } +/// What sending one photo or video as its original would send, for the menu that offers it. +public struct OriginalMediaSummary: Sendable, Equatable { + public var byteCount: Int64 + public var includesLocation: Bool + + public init(byteCount: Int64, includesLocation: Bool) { + self.byteCount = byteCount + self.includesLocation = includesLocation + } + + /// "2.8 MB · Includes location" + public var detailText: String { + let size = ByteCountFormatter.string(fromByteCount: byteCount, countStyle: .file) + return includesLocation ? "\(size) · Includes location" : size + } +} + +public extension OriginalMediaStore { + /// The size of the untouched file behind `media` and whether it carries a location. Nil when + /// there is nothing to send as original. Reads only file headers. + @concurrent + static func summary(for media: FileMediaItem) async -> OriginalMediaSummary? { + let url: URL? + switch media { + case .photo: + url = original(for: media) + case .video: + url = original(for: media) ?? media.localFileURL() + case .document: + // An image or video file that Send as Original switched to (or that was attached as one). + guard media.canSwitchOriginal else { return nil } + url = media.localFileURL() + case .voice: + return nil + } + guard let url, + let size = (try? FileManager.default.attributesOfItem(atPath: url.path))?[.size] as? NSNumber + else { + return nil + } + let includesLocation = if media.isVideoForOriginal { + await videoIncludesLocation(url) + } else { + imageIncludesLocation(url) + } + return OriginalMediaSummary(byteCount: size.int64Value, includesLocation: includesLocation) + } + + internal static func imageIncludesLocation(_ url: URL) -> Bool { + guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, [kCGImageSourceShouldCache: false] as CFDictionary) + as? [CFString: Any], + let gps = properties[kCGImagePropertyGPSDictionary] as? [CFString: Any] + else { + return false + } + return gps[kCGImagePropertyGPSLatitude] != nil + } + + internal static func videoIncludesLocation(_ url: URL) async -> Bool { + guard let items = try? await AVURLAsset(url: url).load(.metadata) else { return false } + return items.contains { item in + item.commonKey == .commonKeyLocation + || (item.identifier?.rawValue.localizedCaseInsensitiveContains("location") ?? false) + } + } +} + public extension FileMediaItem { - /// Whether the composer's Original toggle changes how this item is sent. - var canSendAsOriginal: Bool { + /// Whether the item's menu offers Send as Original. A photo or video switches to its untouched + /// file; an image or video file switches back to a compressed photo or video. + var canSwitchOriginal: Bool { switch self { - case .photo, .video: true - case .document, .voice: false + case .photo, .video: + true + case let .document(info): + Self.switchableFileTypes(mimeType: info.document.mimeType, fileName: info.document.fileName) + .contains { $0.conforms(to: .movie) || Self.isCompressibleImage($0) } + case .voice: + false } } - /// The composer's send with Original on: each photo and video is swapped for its untouched - /// file, in order. An item whose original is gone is sent as it is. - static func withOriginals(_ items: [FileMediaItem]) async -> [FileMediaItem] { - var result: [FileMediaItem] = [] - result.reserveCapacity(items.count) - for item in items { - guard item.canSendAsOriginal else { - result.append(item) - continue + /// True when the item goes as a file, unchanged: Send as Original is on. + var isSentAsFile: Bool { + if case .document = self { true } else { false } + } + + /// The other form of this attachment, made without touching this item's files. A photo or + /// video becomes a document of its untouched file; an image or video document becomes a + /// compressed photo or video. Nil when it can't switch: no original was kept, or the image + /// can only go as a file. The caller keeps one form and discards the other with + /// `discardUnsent()`. + func switchedForOriginal() async throws -> FileMediaItem? { + switch self { + case .photo: + guard let original = OriginalMediaStore.original(for: self) else { return nil } + return .document(try await FileCache.saveDocumentWithThumbnail(url: original)) + case .video: + // The cached video is an untouched copy too; a kept original adds its real file name. + let original = OriginalMediaStore.original(for: self) ?? localFileURL() + guard let original, FileManager.default.fileExists(atPath: original.path) else { return nil } + return .document(try await FileCache.saveDocumentWithThumbnail(url: original)) + case let .document(info): + guard canSwitchOriginal, let url = localFileURL(), FileManager.default.fileExists(atPath: url.path) else { + return nil } - do { - result.append(try await item.replacedWithOriginalDocument() ?? item) - } catch { - Log.shared.error("Couldn't send the original file; sending the compressed one", error: error) - result.append(item) + let media = if isVideoForOriginal { + try await AttachmentMediaMaterializer.video(url, originalFileName: info.document.fileName) + } else { + try await AttachmentMediaMaterializer.photo(.file(url), originalFileName: info.document.fileName) } + guard !media.isSentAsFile else { + await media.discardUnsent() + return nil + } + return media + case .voice: + return nil } - return result } - /// The untouched file behind a photo or video, saved as a document to send in its place, the - /// way Telegram's Send as File works: same bytes, same metadata. The compressed item is - /// removed. Returns nil when there is no original to send (the item is then sent as it is). - func replacedWithOriginalDocument() async throws -> FileMediaItem? { + /// Removes the local files and rows of an attachment that leaves the composer unsent, such as + /// the form Send as Original switched away from. + func discardUnsent() async { switch self { - case let .photo(photoInfo): - guard let original = OriginalMediaStore.original(for: self) else { return nil } - let document = try await FileCache.saveDocumentWithThumbnail(url: original) + case let .photo(info): OriginalMediaStore.discard(for: self) - await FileCache.discardLocalPhoto(photoInfo) - return .document(document) - case let .video(videoInfo): - // The cached video is already an untouched copy; a kept original adds its real file name. - let original = OriginalMediaStore.original(for: self) ?? localFileURL() - guard let original, FileManager.default.fileExists(atPath: original.path) else { return nil } - let document = try await FileCache.saveDocumentWithThumbnail(url: original) + await FileCache.discardLocalPhoto(info) + case let .video(info): OriginalMediaStore.discard(for: self) - await FileCache.discardLocalVideo(videoInfo) - return .document(document) - case .document, .voice: - return nil + await FileCache.discardLocalVideo(info) + case let .document(info): + await FileCache.discardLocalDocument(info) + case .voice: + break + } + } + + internal var isVideoForOriginal: Bool { + switch self { + case .video: + true + case let .document(info): + Self.switchableFileTypes(mimeType: info.document.mimeType, fileName: info.document.fileName) + .contains { $0.conforms(to: .movie) } + case .photo, .voice: + false } } + + internal static func switchableFileTypes(mimeType: String?, fileName: String?) -> [UTType] { + let fromMime = mimeType.flatMap { UTType(mimeType: $0) } + let fromName = fileName.flatMap { name -> UTType? in + let ext = (name as NSString).pathExtension + return ext.isEmpty ? nil : UTType(filenameExtension: ext) + } + return [fromMime, fromName].compactMap { $0 } + } + + /// A still image the photo preparer can compress. GIFs stay files (they'd lose their motion), + /// and so does vector art. + internal static func isCompressibleImage(_ type: UTType) -> Bool { + type.conforms(to: .image) && !type.conforms(to: .gif) && !type.conforms(to: .svg) + } } diff --git a/apple/InlineKit/Tests/InlineKitTests/Drafts2Tests.swift b/apple/InlineKit/Tests/InlineKitTests/Drafts2Tests.swift index dca4da0166..7123d4cbf9 100644 --- a/apple/InlineKit/Tests/InlineKitTests/Drafts2Tests.swift +++ b/apple/InlineKit/Tests/InlineKitTests/Drafts2Tests.swift @@ -152,6 +152,28 @@ struct Drafts2Tests { #expect(sendSnapshot.mediaItems.count == 1) } + @Test("switching an attachment's form keeps its place and survives storage") + func replaceAttachmentKeepsPlace() async throws { + let db = AppDatabase.empty() + let drafts = Drafts2(database: db) + let peer: InlineKit.Peer = .thread(id: 41) + + let first = drafts.appendAttachment(peer: peer, media: .document(documentInfo(id: -411))) + let switched = drafts.appendAttachment(peer: peer, media: .document(documentInfo(id: -412))) + let last = drafts.appendAttachment(peer: peer, media: .document(documentInfo(id: -413))) + + let replacement = try #require(drafts.replaceAttachment(peer: peer, id: switched.id, with: .document(documentInfo(id: -414)))) + #expect(replacement.id != switched.id) + #expect(replacement.createdAt == switched.createdAt) + await drafts.flush() + + let reloaded = Drafts2(database: db).load(peer: peer)?.attachments.map(\.id) ?? [] + #expect(reloaded == [first.id, replacement.id, last.id]) + + // Sent or removed meanwhile: nothing to replace. + #expect(drafts.replaceAttachment(peer: peer, id: switched.id, with: .document(documentInfo(id: -415))) == nil) + } + @Test("flush stores latest staged text without blocking update calls") func flushStoresLatestStagedText() async throws { let db = AppDatabase.empty() diff --git a/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift b/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift index d5c215f147..3cceed50e9 100644 --- a/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift +++ b/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift @@ -155,9 +155,53 @@ struct OriginalMediaStoreTests { #expect(OriginalMediaStore.safeFileName("..") == "original") } - @Test("only photos and videos can be sent as originals") - func eligibility() { - #expect(photoItem(localPath: "a.jpg").canSendAsOriginal) + + @Test("image and video files can switch back to compressed; GIFs, vectors and other files can't") + func fileEligibility() { + #expect(documentItem("IMG_4821.HEIC", mimeType: "image/heic").canSwitchOriginal) + #expect(documentItem("photo.jpg", mimeType: "application/octet-stream").canSwitchOriginal) + #expect(documentItem("IMG_4822.MOV", mimeType: "video/quicktime").isVideoForOriginal) + #expect(!documentItem("loop.gif", mimeType: "image/gif").canSwitchOriginal) + #expect(!documentItem("logo.svg", mimeType: "image/svg+xml").canSwitchOriginal) + #expect(!documentItem("report.pdf", mimeType: "application/pdf").canSwitchOriginal) + #expect(photoItem(localPath: "a.jpg").canSwitchOriginal) + #expect(!photoItem(localPath: "a.jpg").isSentAsFile) + #expect(documentItem("IMG_4821.HEIC", mimeType: "image/heic").isSentAsFile) + } + + @Test("a photo whose original is gone can't switch") + func switchWithoutOriginal() async throws { + let item = photoItem(localPath: "no-original-\(UUID().uuidString).jpg") + #expect(try await item.switchedForOriginal() == nil) + } + + @Test("the location check reads GPS from the file header") + func locationCheck() throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + + let withLocation = folder.appendingPathComponent("gps.jpg") + try writeJPEG(to: withLocation, properties: [ + kCGImagePropertyGPSDictionary: [ + kCGImagePropertyGPSLatitude: 52.37, + kCGImagePropertyGPSLatitudeRef: "N", + kCGImagePropertyGPSLongitude: 4.89, + kCGImagePropertyGPSLongitudeRef: "E", + ], + ]) + let withoutLocation = folder.appendingPathComponent("plain.jpg") + try writeJPEG(to: withoutLocation, properties: [:]) + + #expect(OriginalMediaStore.imageIncludesLocation(withLocation)) + #expect(!OriginalMediaStore.imageIncludesLocation(withoutLocation)) + } + + @Test("the menu detail names the size and the location") + func summaryText() { + let size = ByteCountFormatter.string(fromByteCount: 2_800_000, countStyle: .file) + #expect(OriginalMediaSummary(byteCount: 2_800_000, includesLocation: true).detailText == "\(size) · Includes location") + #expect(OriginalMediaSummary(byteCount: 2_800_000, includesLocation: false).detailText == size) } } @@ -169,6 +213,26 @@ private func photoItem(localPath: String) -> FileMediaItem { ])) } +private func documentItem(_ fileName: String, mimeType: String) -> FileMediaItem { + .document(DocumentInfo(document: Document( + id: nil, documentId: -11, date: Date(timeIntervalSince1970: 1), fileName: fileName, mimeType: mimeType, + size: 1, cdnUrl: nil, localPath: fileName, thumbnailPhotoId: nil + ))) +} + +private func writeJPEG(to url: URL, properties: [CFString: Any]) throws { + let context = try #require(CGContext( + data: nil, width: 8, height: 8, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue + )) + context.setFillColor(CGColor(red: 0.2, green: 0.4, blue: 0.6, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: 8, height: 8)) + let image = try #require(context.makeImage()) + let destination = try #require(CGImageDestinationCreateWithURL(url as CFURL, "public.jpeg" as CFString, 1, nil)) + CGImageDestinationAddImage(destination, image, properties as CFDictionary) + #expect(CGImageDestinationFinalize(destination)) +} + private func properties(of data: Data) -> [CFString: Any]? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } return CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] From 4fcdce81dfd75b6d56b972f940a0ae0ea8324076 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sat, 21 Nov 2026 21:45:37 +0000 Subject: [PATCH 05/14] ios: switch attachments to their original file from the tile's menu - Removes the Original chip from the attachment strip. - Photo, video and image or video file tiles get a long-press menu: Send as Original (checked on files, with size and location) and Remove. Choosing it switches the item in place, with a spinner and a crossfade. - The strip shows attachments in send order, photos and videos before files. Document tiles with a thumbnail show their extension. - A marked-up photo is prepared like any photo, and its edited file is kept as its original (savePhoto no longer takes optimize). --- .../Compose/ComposeView+UIViews.swift | 34 -- .../Features/Compose/ComposeView.swift | 299 ++++++++++++++++-- 2 files changed, 271 insertions(+), 62 deletions(-) diff --git a/apple/InlineIOS/Features/Compose/ComposeView+UIViews.swift b/apple/InlineIOS/Features/Compose/ComposeView+UIViews.swift index 195fbf63f6..0a726ee953 100644 --- a/apple/InlineIOS/Features/Compose/ComposeView+UIViews.swift +++ b/apple/InlineIOS/Features/Compose/ComposeView+UIViews.swift @@ -355,40 +355,6 @@ extension ComposeView { return view } - /// The strip's Original chip. Off: photos and videos are sent compressed, with no location or - /// camera details. On: they go as their untouched files, the way Telegram's Send as File works. - func makeOriginalToggleButton() -> UIButton { - let button = UIButton(type: .custom) - button.translatesAutoresizingMaskIntoConstraints = false - button.isSelected = sendsMediaAsOriginal - button.configurationUpdateHandler = { button in - var configuration: UIButton.Configuration = button.isSelected ? .filled() : .gray() - configuration.cornerStyle = .capsule - configuration.image = UIImage(systemName: button.isSelected ? "checkmark.circle.fill" : "circle") - configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13, weight: .semibold) - configuration.imagePadding = 5 - configuration.contentInsets = NSDirectionalEdgeInsets(top: 7, leading: 10, bottom: 7, trailing: 12) - var title = AttributedString("Original") - title.font = UIFont.systemFont(ofSize: 14, weight: .semibold) - configuration.attributedTitle = title - if !button.isSelected { - configuration.baseForegroundColor = .secondaryLabel - } - button.configuration = configuration - button.accessibilityValue = button.isSelected ? "On" : "Off" - } - button.addAction(UIAction { [weak self] _ in - guard let self else { return } - sendsMediaAsOriginal.toggle() - UISelectionFeedbackGenerator().selectionChanged() - }, for: .primaryActionTriggered) - button.accessibilityLabel = "Send originals" - button.accessibilityHint = "Sends photos and videos as files, unchanged, including their location and camera details." - button.setContentHuggingPriority(.required, for: .horizontal) - button.setContentCompressionResistancePriority(.required, for: .horizontal) - return button - } - func makeAttachmentScrollView() -> UIScrollView { let view = UIScrollView() view.translatesAutoresizingMaskIntoConstraints = false diff --git a/apple/InlineIOS/Features/Compose/ComposeView.swift b/apple/InlineIOS/Features/Compose/ComposeView.swift index bdec74a15d..1a4c4ac4ad 100644 --- a/apple/InlineIOS/Features/Compose/ComposeView.swift +++ b/apple/InlineIOS/Features/Compose/ComposeView.swift @@ -98,12 +98,12 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { var attachmentItems: [String: FileMediaItem] = [:] { didSet { attachmentOrder = Self.updatedAttachmentOrder(attachmentOrder, items: attachmentItems) } } - /// The strip's Original chip: photos and videos go as their untouched files. Resets once the - /// attachments are sent or cleared, so it never carries over to a later message. - var sendsMediaAsOriginal = false { - didSet { originalToggleButton?.isSelected = sendsMediaAsOriginal } - } - weak var originalToggleButton: UIButton? + /// What Send as Original would send for each photo, video or image file (size, location), + /// for its menu. + private var originalAvailability: [String: OriginalAvailability] = [:] + private var originalSummaryTasks: [String: Task] = [:] + /// Attachments being switched between photo and file by Send as Original. + private var switchingAttachmentIds: Set = [] /// Keys of `attachmentItems` in the order they were added: the order they are sent in, and so /// the order of an album's photos. private(set) var attachmentOrder: [String] = [] @@ -1219,7 +1219,6 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { ) let hasText = !rawText.isEmpty let attachmentItemsSnapshot = attachmentItems - let sendsOriginalsSnapshot = sendsMediaAsOriginal let hasAttachmentItems = !attachmentItemsSnapshot.isEmpty let hasForward = forwardContext != nil @@ -1362,8 +1361,9 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { await sendTextTransaction(transaction) } } else { - // In the order they were added; neighbouring photos and videos go out as albums. - var attachments = orderedAttachmentsToSend.filter { attachment in + // In the order they were added; neighbouring items go out as albums, photos and videos + // before files (originals among them). + let attachments = orderedAttachmentsToSend.filter { attachment in // Verify attachment has valid local path before sending guard attachment.getLocalPath() != nil else { log.error("Attachment has no local path, skipping: \(attachment)") @@ -1371,9 +1371,6 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { } return true } - if sendsOriginalsSnapshot { - attachments = await FileMediaItem.withOriginals(attachments) - } for send in TransactionSendMessage.sends( text: text, peerId: peerId, @@ -2143,7 +2140,6 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { } attachmentItems.removeAll() pendingVideoAttachments.removeAll() - sendsMediaAsOriginal = false handleAttachmentItemsChanged( animated: false, shouldUpdateSendButtonVisibility: shouldUpdateSendButtonVisibility, @@ -2166,6 +2162,7 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { cancelRemovedUploads: Bool = true ) { syncAttachmentUploadTracking(cancelRemovedUploads: cancelRemovedUploads) + syncOriginalMediaState() UIView.performWithoutAnimation { refreshAttachmentPreviews() attachmentStackView.layoutIfNeeded() @@ -2359,12 +2356,6 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { guard hasAttachments else { return } - if !pendingVideoAttachments.isEmpty || attachmentItems.values.contains(where: \.canSendAsOriginal) { - let toggle = makeOriginalToggleButton() - originalToggleButton = toggle - attachmentStackView.addArrangedSubview(toggle) - } - for pending in pendingVideoAttachments { let preview = ComposeAttachmentPreviewItemView( pendingVideoId: pending.id, @@ -2375,7 +2366,10 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { attachmentStackView.addArrangedSubview(preview) } - for id in attachmentOrder { + // As they're sent: photos and videos first, then files (a switched original among them). + let addedIds = attachmentOrder.filter { attachmentItems[$0] != nil } + let displayedIds = TransactionSendMessage.sendOrder(addedIds.compactMap { attachmentItems[$0] }).map { addedIds[$0] } + for id in displayedIds { guard let mediaItem = attachmentItems[id] else { continue } let preview = ComposeAttachmentPreviewItemView( attachmentId: id, @@ -2386,11 +2380,112 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { ) { [weak self] attachmentId in self?.removeAttachment(attachmentId) } + if mediaItem.canSwitchOriginal { + preview.originalMenuState = { [weak self] in + self?.originalMenuState(for: id) ?? .init(isOn: false, detail: nil, isAvailable: false) + } + preview.onSwitchOriginal = { [weak self] in + self?.switchOriginal(attachmentId: id) + } + preview.setSwitching(switchingAttachmentIds.contains(id)) + } preview.setUploadProgress(attachmentUploadProgress[id]) attachmentStackView.addArrangedSubview(preview) } } + // MARK: - Send as Original + + private enum OriginalAvailability { + case loading + case available(OriginalMediaSummary) + case unavailable + } + + /// Send as Original: switches a photo or video to a file of its untouched original, or an + /// image or video file back to a compressed photo or video. The tile changes in place once the + /// other form is ready; files move after the photos and videos, where they're sent. + func switchOriginal(attachmentId: String) { + guard let item = attachmentItems[attachmentId], item.canSwitchOriginal, + !switchingAttachmentIds.contains(attachmentId) + else { return } + switchingAttachmentIds.insert(attachmentId) + previewTile(for: attachmentId)?.setSwitching(true) + UISelectionFeedbackGenerator().selectionChanged() + + Task { [weak self] in + let switched: FileMediaItem? + do { + switched = try await item.switchedForOriginal() + } catch { + Log.shared.error("Couldn't switch the attachment for Send as Original", error: error) + switched = nil + } + guard let self else { + await switched?.discardUnsent() + return + } + self.switchingAttachmentIds.remove(attachmentId) + // Sent or removed while switching: keep nothing new. + guard self.attachmentItems[attachmentId] != nil else { + await switched?.discardUnsent() + return + } + guard let switched else { + self.previewTile(for: attachmentId)?.setSwitching(false) + ToastManager.shared.showToast( + item.isSentAsFile ? "This file can only be sent as a file." : "The original is no longer available.", + type: .error, + systemImage: "exclamationmark.triangle.fill" + ) + return + } + UIView.transition(with: self.attachmentStackView, duration: 0.22, options: .transitionCrossDissolve) { + self.replaceAttachment(attachmentId, with: switched) + } + await item.discardUnsent() + } + } + + private func previewTile(for attachmentId: String) -> ComposeAttachmentPreviewItemView? { + attachmentStackView.arrangedSubviews + .compactMap { $0 as? ComposeAttachmentPreviewItemView } + .first { $0.attachmentIdentifier == attachmentId } + } + + private func originalMenuState(for attachmentId: String) -> ComposeAttachmentPreviewItemView.OriginalMenuState { + let isOn = attachmentItems[attachmentId]?.isSentAsFile == true + let isSwitching = switchingAttachmentIds.contains(attachmentId) + switch originalAvailability[attachmentId] { + case let .available(summary): + return .init(isOn: isOn, detail: summary.detailText, isAvailable: !isSwitching) + case .unavailable: + return .init(isOn: isOn, detail: "The original is no longer available", isAvailable: false) + case .loading, nil: + return .init(isOn: isOn, detail: nil, isAvailable: !isSwitching) + } + } + + /// Forgets removed items and reads what Send as Original would send for each new photo, + /// video or image file (size, location), for its menu. Reads file headers off the main thread. + private func syncOriginalMediaState() { + let ids = Set(attachmentItems.keys) + for id in Set(originalSummaryTasks.keys).subtracting(ids) { + originalSummaryTasks.removeValue(forKey: id)?.cancel() + } + originalAvailability = originalAvailability.filter { ids.contains($0.key) } + + for (id, media) in attachmentItems where media.canSwitchOriginal && originalAvailability[id] == nil { + originalAvailability[id] = .loading + originalSummaryTasks[id] = Task { [weak self] in + let summary = await OriginalMediaStore.summary(for: media) + guard let self, !Task.isCancelled, self.attachmentItems[id] != nil else { return } + self.originalSummaryTasks.removeValue(forKey: id) + self.originalAvailability[id] = summary.map { .available($0) } ?? .unavailable + } + } + } + @discardableResult func addPendingVideoAttachment() -> String { let pendingId = "pending_video_\(UUID().uuidString)" @@ -2482,14 +2577,19 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { } private func applyEditedPhoto(from editedURL: URL, replacing attachmentId: String) { + // Named after the photo it edits, with the edit's own format. + let originalName: String? = attachmentItems[attachmentId] + .flatMap { OriginalMediaStore.original(for: $0) } + .flatMap { ($0.deletingPathExtension().lastPathComponent as NSString).appendingPathExtension(editedURL.pathExtension) } Task { [weak self] in - let result = await Task.detached(priority: .userInitiated) { () -> Result in - defer { try? FileManager.default.removeItem(at: editedURL) } - guard let image = UIImage(contentsOfFile: editedURL.path) else { - return .failure(CocoaError(.fileReadCorruptFile)) - } - return Result { .photo(try FileCache.savePhoto(image: image, optimize: true)) } - }.value + // Prepared like any photo, with the edited file kept as its original for Send as Original. + let result: Result + do { + result = .success(try await AttachmentMediaMaterializer.photo(.file(editedURL), originalFileName: originalName)) + } catch { + result = .failure(error) + } + try? FileManager.default.removeItem(at: editedURL) guard let self else { return } switch result { @@ -2648,9 +2748,43 @@ private final class ComposeQuickLookItem: NSObject, QLPreviewItem { } } -private final class ComposeAttachmentPreviewItemView: UIView { +private final class ComposeAttachmentPreviewItemView: UIView, UIContextMenuInteractionDelegate { static let stripHeight: CGFloat = 92 + /// What the long-press menu's Send as Original item shows. + struct OriginalMenuState { + var isOn: Bool + /// "2.8 MB · Includes location", or why it can't be sent. + var detail: String? + var isAvailable: Bool + } + + /// Set for photos, videos and image or video files: their long-press menu offers Send as + /// Original, checked when the item is a file. + var originalMenuState: (() -> OriginalMenuState)? { + didSet { updateContextMenu() } + } + var onSwitchOriginal: (() -> Void)? + private var contextMenuInteraction: UIContextMenuInteraction? + + /// Shown while Send as Original switches the item between photo and file. + private let switchingIndicator: UIActivityIndicatorView = { + let indicator = UIActivityIndicatorView(style: .medium) + indicator.translatesAutoresizingMaskIntoConstraints = false + indicator.color = .white + indicator.hidesWhenStopped = true + return indicator + }() + + private let switchingDimView: UIView = { + let view = UIView() + view.translatesAutoresizingMaskIntoConstraints = false + view.backgroundColor = UIColor.black.withAlphaComponent(0.35) + view.isHidden = true + view.isUserInteractionEnabled = false + return view + }() + private enum Metrics { static let tileSize: CGFloat = 84 static let cornerRadius: CGFloat = 16 @@ -2823,6 +2957,8 @@ private final class ComposeAttachmentPreviewItemView: UIView { tileContentView.addSubview(centerIconView) tileContentView.addSubview(extensionBadge) tileContentView.addSubview(overlayIconView) + tileContentView.addSubview(switchingDimView) + tileContentView.addSubview(switchingIndicator) addSubview(removeButton) removeButton.addSubview(removeBadgeView) removeBadgeView.addSubview(removeIconView) @@ -2870,6 +3006,14 @@ private final class ComposeAttachmentPreviewItemView: UIView { overlayIconView.centerXAnchor.constraint(equalTo: tileContentView.centerXAnchor), overlayIconView.centerYAnchor.constraint(equalTo: tileContentView.centerYAnchor), + switchingDimView.leadingAnchor.constraint(equalTo: tileContentView.leadingAnchor), + switchingDimView.trailingAnchor.constraint(equalTo: tileContentView.trailingAnchor), + switchingDimView.topAnchor.constraint(equalTo: tileContentView.topAnchor), + switchingDimView.bottomAnchor.constraint(equalTo: tileContentView.bottomAnchor), + + switchingIndicator.centerXAnchor.constraint(equalTo: tileContentView.centerXAnchor), + switchingIndicator.centerYAnchor.constraint(equalTo: tileContentView.centerYAnchor), + removeButton.topAnchor.constraint(equalTo: topAnchor, constant: 6), removeButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -6), removeButton.widthAnchor.constraint(equalToConstant: Metrics.removeButtonSize), @@ -2914,6 +3058,11 @@ private final class ComposeAttachmentPreviewItemView: UIView { usesInternalTinyThumbnail: true, showsLoadingPlaceholder: true ) + // The extension marks it as a file, so a photo switched to Send as Original reads as one. + if let ext = fileExtension(from: documentInfo.document.fileName) { + extensionBadge.text = " \(ext.uppercased()) " + extensionBadge.isHidden = false + } } else { applyFallback( iconName: DocumentIconResolver.symbolName( @@ -2945,6 +3094,100 @@ private final class ComposeAttachmentPreviewItemView: UIView { _ = progress } + // MARK: Send as Original + + func setSwitching(_ isSwitching: Bool) { + switchingDimView.isHidden = !isSwitching + if isSwitching { + switchingIndicator.startAnimating() + } else { + switchingIndicator.stopAnimating() + } + } + + private func updateContextMenu() { + if originalMenuState == nil { + if let contextMenuInteraction { + tileContentView.removeInteraction(contextMenuInteraction) + self.contextMenuInteraction = nil + } + } else if contextMenuInteraction == nil { + let interaction = UIContextMenuInteraction(delegate: self) + tileContentView.addInteraction(interaction) + contextMenuInteraction = interaction + } + updateAccessibility() + } + + private func updateAccessibility() { + guard originalMenuState != nil else { + tileContentView.isAccessibilityElement = false + tileContentView.accessibilityCustomActions = nil + return + } + let isFile = originalMenuState?().isOn == true + tileContentView.isAccessibilityElement = true + tileContentView.accessibilityTraits = .button + tileContentView.accessibilityLabel = "Attachment" + tileContentView.accessibilityValue = isFile ? "Original file" : "Compressed" + tileContentView.accessibilityCustomActions = [ + UIAccessibilityCustomAction(name: isFile ? "Send Compressed" : "Send as Original") { [weak self] _ in + self?.onSwitchOriginal?() + return true + }, + UIAccessibilityCustomAction(name: "Remove") { [weak self] _ in + self?.removeTapped() + return true + }, + ] + } + + func contextMenuInteraction( + _ interaction: UIContextMenuInteraction, + configurationForMenuAtLocation location: CGPoint + ) -> UIContextMenuConfiguration? { + guard let state = originalMenuState?() else { return nil } + return UIContextMenuConfiguration(identifier: attachmentId as NSString, previewProvider: nil) { [weak self] _ in + let original = UIAction( + title: "Send as Original", + subtitle: state.detail, + image: UIImage(systemName: "doc"), + attributes: state.isAvailable ? [] : [.disabled], + state: state.isOn ? .on : .off + ) { [weak self] _ in + self?.onSwitchOriginal?() + } + let remove = UIAction(title: "Remove", image: UIImage(systemName: "trash"), attributes: .destructive) { [weak self] _ in + self?.removeTapped() + } + return UIMenu(children: [UIMenu(options: .displayInline, children: [original]), remove]) + } + } + + func contextMenuInteraction( + _ interaction: UIContextMenuInteraction, + configuration: UIContextMenuConfiguration, + highlightPreviewForItemWithIdentifier identifier: any NSCopying + ) -> UITargetedPreview? { + roundedPreview() + } + + func contextMenuInteraction( + _ interaction: UIContextMenuInteraction, + configuration: UIContextMenuConfiguration, + dismissalPreviewForItemWithIdentifier identifier: any NSCopying + ) -> UITargetedPreview? { + roundedPreview() + } + + private func roundedPreview() -> UITargetedPreview? { + guard tileContentView.window != nil else { return nil } + let parameters = UIPreviewParameters() + parameters.visiblePath = UIBezierPath(roundedRect: tileContentView.bounds, cornerRadius: Metrics.cornerRadius) + parameters.backgroundColor = .clear + return UITargetedPreview(view: tileContentView, parameters: parameters) + } + private func applyPhotoPreview( _ photoInfo: PhotoInfo?, contentMode: PlatformPhotoContentMode = .aspectFill, From c2176bfd1e3bc8c5a3ac8073ff5af0a09885a063 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sat, 21 Nov 2026 21:33:31 +0000 Subject: [PATCH 06/14] macos: switch attachments to their original file from the context menu - Removes the Original checkbox from the media row. - Photo and video tiles and image or video file rows get Send as Original in their menu (video tiles gain a menu with Remove). Switching replaces the draft attachment and moves it between the media row and the file list, in Glass, Legacy and new-thread compose. - Sends no longer swap in originals at send time. --- .../Views/Compose/ComposeAppKit.swift | 2 + .../Views/Compose/ComposeAttachments.swift | 172 +++++++++++++----- .../Views/Compose/GlassComposeAppKit.swift | 94 +++++++--- .../Views/Compose/ImageAttachment.swift | 3 + .../Views/Compose/LegacyComposeAppKit.swift | 85 ++++++--- .../Compose/NewThreadComposeContext.swift | 28 +-- .../Views/Compose/VideoAttachmentView.swift | 13 ++ 7 files changed, 285 insertions(+), 112 deletions(-) diff --git a/apple/InlineMac/Views/Compose/ComposeAppKit.swift b/apple/InlineMac/Views/Compose/ComposeAppKit.swift index 249ed244f9..687a9cc530 100644 --- a/apple/InlineMac/Views/Compose/ComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/ComposeAppKit.swift @@ -24,6 +24,8 @@ protocol ComposeAttachmentOwner: AnyObject { func removeImage(_ id: String) func removeVideo(_ id: String) func removeFile(_ id: String) + /// Send as Original from an item's menu: switches it between a photo or video and its file. + func switchOriginal(attachmentId id: String) /// Called when the attachment strip goes from empty to non-empty or back. func composeAttachmentsDidChangeStaged(_ hasAttachments: Bool) } diff --git a/apple/InlineMac/Views/Compose/ComposeAttachments.swift b/apple/InlineMac/Views/Compose/ComposeAttachments.swift index 63927961df..1af6b15c86 100644 --- a/apple/InlineMac/Views/Compose/ComposeAttachments.swift +++ b/apple/InlineMac/Views/Compose/ComposeAttachments.swift @@ -46,6 +46,11 @@ final class ComposeAttachments: NSView { return false } private var mediaMeta: [String: MediaMeta] = [:] + /// Reads what Send as Original would send for each ready photo, video or image file, for its menu. + private var originalSummaryTasks: [String: Task] = [:] + /// Send as Original for image and video files in the file list, checked: choosing it switches + /// the file back to a compressed photo or video. + private var documentOriginalOptions: [String: SendAsOriginalOption] = [:] private enum MediaSection { case media @@ -84,30 +89,6 @@ final class ComposeAttachments: NSView { private var documentCollectionHeightConstraint: NSLayoutConstraint! private var mediaTopConstraint: NSLayoutConstraint! private var documentsLeadingConstraint: NSLayoutConstraint! - private var mediaTrailingConstraint: NSLayoutConstraint! - private var mediaTrailingToToggleConstraint: NSLayoutConstraint! - - /// Off: photos and videos go compressed, with no location or camera details. On: they go as - /// their untouched files. Resets when the attachments are cleared, after a send. - private(set) var sendsMediaAsOriginal = false { - didSet { originalToggle.state = sendsMediaAsOriginal ? .on : .off } - } - - private lazy var originalToggle: NSButton = { - let button = NSButton(checkboxWithTitle: "Original", target: self, action: #selector(toggleOriginal)) - button.controlSize = .small - button.font = .systemFont(ofSize: NSFont.smallSystemFontSize) - button.contentTintColor = .secondaryLabelColor - button.toolTip = "Send photos and videos as files, unchanged, including their location and camera details." - button.setAccessibilityLabel("Send originals") - button.translatesAutoresizingMaskIntoConstraints = false - button.isHidden = true - return button - }() - - @objc private func toggleOriginal() { - sendsMediaAsOriginal = originalToggle.state == .on - } private var verticalPadding: CGFloat = Theme.composeAttachmentsVPadding private var isExternallyCollapsed = false @@ -200,10 +181,6 @@ final class ComposeAttachments: NSView { self.documentScrollHeightConstraint.constant = documentViewportHeight self.documentCollectionHeightConstraint.constant = documentContentHeight self.mediaScrollView.isHidden = mediaHeight == 0 - let showsOriginalToggle = mediaHeight > 0 - self.originalToggle.isHidden = !showsOriginalToggle - self.mediaTrailingConstraint.isActive = !showsOriginalToggle - self.mediaTrailingToToggleConstraint.isActive = showsOriginalToggle self.documentScrollView.isHidden = self.isExternallyCollapsed || self.documentModels.isEmpty self.documentLayout.sectionInset = (!self.isExternallyCollapsed && mediaHeight == 0 && !self.documentModels.isEmpty) ? NSEdgeInsets(top: self.verticalPadding, left: 0, bottom: self.verticalPadding, right: 0) @@ -286,17 +263,6 @@ final class ComposeAttachments: NSView { addSubview(mediaScrollView) addSubview(documentScrollView) - addSubview(originalToggle) - - mediaTrailingConstraint = mediaScrollView.trailingAnchor.constraint(equalTo: trailingAnchor) - mediaTrailingToToggleConstraint = mediaScrollView.trailingAnchor.constraint( - equalTo: originalToggle.leadingAnchor, - constant: -8 - ) - NSLayoutConstraint.activate([ - originalToggle.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -horizontalContentInset), - originalToggle.centerYAnchor.constraint(equalTo: mediaScrollView.centerYAnchor), - ]) documentsLeadingConstraint = documentCollectionView.leadingAnchor.constraint( equalTo: documentClipView.leadingAnchor, @@ -310,7 +276,7 @@ final class ComposeAttachments: NSView { documentCollectionHeightConstraint, mediaScrollView.leadingAnchor.constraint(equalTo: leadingAnchor), - mediaTrailingConstraint, + mediaScrollView.trailingAnchor.constraint(equalTo: trailingAnchor), mediaScrollView.topAnchor.constraint(equalTo: topAnchor), documentsLeadingConstraint, @@ -331,13 +297,16 @@ final class ComposeAttachments: NSView { public func removeImageView(id: String) { guard attachments.removeValue(forKey: id) != nil else { return } + originalSummaryTasks.removeValue(forKey: id)?.cancel() orderedMediaIds.removeAll { $0 == id } mediaMeta.removeValue(forKey: id) applyMediaSnapshot() updateHeight(animated: true) } - public func addImageView(_ image: NSImage, id: String) { + /// `media` is the ready photo, or nil while it is still being prepared. A ready photo's menu + /// offers Send as Original. + public func addImageView(_ image: NSImage, id: String, media: FileMediaItem? = nil) { if attachments[id] != nil { return } let aspectRatio = image.size.width / max(image.size.height, 1) mediaMeta[id] = .init(kind: .image, aspectRatio: aspectRatio) @@ -354,10 +323,14 @@ final class ComposeAttachments: NSView { attachmentView.translatesAutoresizingMaskIntoConstraints = false attachments[id] = attachmentView + if let media { + offerSendAsOriginal(on: attachmentView.originalOption, id: id, media: media) + } applyMediaSnapshot() updateHeight(animated: true) } + /// A ready video: its menu offers Send as Original. public func addVideoView(_ videoInfo: VideoInfo, id: String) { let thumbnail: NSImage? = { guard let localPath = videoInfo.thumbnail?.sizes.first?.localPath else { return nil } @@ -371,6 +344,27 @@ final class ComposeAttachments: NSView { }() addVideoView(thumbnail: thumbnail, videoURL: videoURL, id: id) + if let view = videoAttachments[id] { + offerSendAsOriginal(on: view.originalOption, id: id, media: .video(videoInfo)) + } + } + + /// Checked for a file, unchecked for a photo or video. Choosing it asks the owner to switch + /// the item to its other form, which replaces this view. + private func offerSendAsOriginal(on option: SendAsOriginalOption, id: String, media: FileMediaItem) { + guard media.canSwitchOriginal else { return } + option.isOffered = true + option.isOn = media.isSentAsFile + option.onChange = { [weak self] in + self?.compose?.switchOriginal(attachmentId: id) + } + originalSummaryTasks[id]?.cancel() + originalSummaryTasks[id] = Task { [weak self, weak option] in + let summary = await OriginalMediaStore.summary(for: media) + guard !Task.isCancelled else { return } + option?.setSummary(summary) + self?.originalSummaryTasks.removeValue(forKey: id) + } } public func addVideoView(thumbnail: NSImage?, videoURL: URL?, id: String) { @@ -405,6 +399,7 @@ final class ComposeAttachments: NSView { public func removeVideoView(id: String) { guard videoAttachments.removeValue(forKey: id) != nil else { return } + originalSummaryTasks.removeValue(forKey: id)?.cancel() orderedMediaIds.removeAll { $0 == id } mediaMeta.removeValue(forKey: id) applyMediaSnapshot() @@ -458,6 +453,12 @@ final class ComposeAttachments: NSView { public func addDocumentView(_ documentInfo: DocumentInfo, id: String) { documentModels[id] = .ready(documentInfo) + let media = FileMediaItem.document(documentInfo) + if media.canSwitchOriginal { + let option = SendAsOriginalOption() + offerSendAsOriginal(on: option, id: id, media: media) + documentOriginalOptions[id] = option + } if !orderedDocumentIds.contains(id) { orderedDocumentIds.append(id) } @@ -467,6 +468,8 @@ final class ComposeAttachments: NSView { public func removeDocumentView(id: String) { guard documentModels.removeValue(forKey: id) != nil else { return } + documentOriginalOptions.removeValue(forKey: id) + originalSummaryTasks.removeValue(forKey: id)?.cancel() orderedDocumentIds.removeAll { $0 == id } applyDocumentSnapshot() updateHeight(animated: true) @@ -474,6 +477,7 @@ final class ComposeAttachments: NSView { public func clearDocumentViews(animated: Bool = false) { documentModels.removeAll() + documentOriginalOptions.removeAll() orderedDocumentIds.removeAll() applyDocumentSnapshot() } @@ -482,7 +486,8 @@ final class ComposeAttachments: NSView { public func clearViews(animated: Bool = false) { attachments.removeAll() - sendsMediaAsOriginal = false + originalSummaryTasks.values.forEach { $0.cancel() } + originalSummaryTasks.removeAll() videoAttachments.removeAll() orderedMediaIds.removeAll() @@ -542,7 +547,7 @@ final class ComposeAttachments: NSView { for: indexPath ) guard let documentItem = item as? DocumentAttachmentCollectionItem else { return item } - documentItem.configure(with: model) { [weak self] in + documentItem.configure(with: model, originalOption: documentOriginalOptions[id]) { [weak self] in self?.compose?.removeFile(id) } return documentItem @@ -661,6 +666,62 @@ extension ComposeAttachments: NSCollectionViewDelegateFlowLayout { // MARK: - Helpers +// MARK: - Send as Original + +/// The Send as Original item in an attachment's menu. Unchecked on a photo or video, which goes +/// compressed without location or camera details; checked on an image or video file, which goes +/// untouched. Choosing it asks the owner to switch the item to its other form. +@MainActor +final class SendAsOriginalOption: NSObject, NSMenuItemValidation { + /// Only ready photos and videos offer it; a tile still being prepared doesn't. + var isOffered = false { + didSet { + menuItem.isHidden = !isOffered + separator.isHidden = !isOffered + } + } + + var isOn = false { + didSet { menuItem.state = isOn ? .on : .off } + } + + var onChange: (() -> Void)? + + /// The untouched file is gone (the system cleared temporary files), so there's nothing to switch to. + private var isMissingOriginal = false + + let menuItem = NSMenuItem(title: "Send as Original", action: #selector(toggle), keyEquivalent: "") + let separator = NSMenuItem.separator() + + override init() { + super.init() + menuItem.target = self + menuItem.image = NSImage(systemSymbolName: "doc", accessibilityDescription: nil) + menuItem.isHidden = true + separator.isHidden = true + } + + /// Puts the item first in `menu`. + func install(in menu: NSMenu) { + menu.insertItem(separator, at: 0) + menu.insertItem(menuItem, at: 0) + } + + /// The original's size and whether it carries a location, or nil when it is gone. + func setSummary(_ summary: OriginalMediaSummary?) { + isMissingOriginal = summary == nil + menuItem.subtitle = summary?.detailText ?? "The original is no longer available" + } + + @objc private func toggle() { + onChange?() + } + + func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { + menuItem !== self.menuItem || !isMissingOriginal + } +} + private struct MediaMeta { enum Kind { case image @@ -747,7 +808,11 @@ private final class DocumentAttachmentCollectionItem: NSCollectionViewItem { (view as? AttachmentHostView)?.host(nil) } - func configure(with model: DocumentAttachmentModel, onRemove: @escaping () -> Void) { + func configure( + with model: DocumentAttachmentModel, + originalOption: SendAsOriginalOption?, + onRemove: @escaping () -> Void + ) { let child: NSView = switch model { case let .pending(presentation): PendingDocumentAttachmentView(presentation: presentation, onRemove: onRemove) @@ -755,6 +820,25 @@ private final class DocumentAttachmentCollectionItem: NSCollectionViewItem { DocumentView(documentInfo: documentInfo, removeAction: onRemove) } (view as? AttachmentHostView)?.host(child) + view.menu = originalOption.map { option in + // An image or video file: Send as Original, checked, switches it back to a photo or video. + let menu = NSMenu() + let removeItem = NSMenuItem(title: "Remove", action: #selector(RemoveTarget.remove), keyEquivalent: "") + let target = RemoveTarget(onRemove) + removeItem.target = target + removeItem.representedObject = target + removeItem.image = NSImage(systemSymbolName: "trash", accessibilityDescription: nil) + menu.addItem(removeItem) + option.install(in: menu) + return menu + } + } + + /// Keeps the Remove action alive for as long as its menu item. + private final class RemoveTarget: NSObject { + let action: () -> Void + init(_ action: @escaping () -> Void) { self.action = action } + @objc func remove() { action() } } } diff --git a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift index fcd6a8112a..fa42178edf 100644 --- a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift @@ -175,6 +175,8 @@ class GlassComposeAppKit: NSView { private var voiceSpaceKeyUnsubscribe: (() -> Void)? // [uniqueId: FileMediaItem] + /// Attachments being switched between photo and file by Send as Original. + private var switchingAttachmentIds: Set = [] private var attachmentItems: [String: FileMediaItem] = [:] { didSet { updateSendButtonIfNeeded() @@ -2721,29 +2723,19 @@ class GlassComposeAppKit: NSView { } let effectiveSendMode = sendMode ?? (state.sendSilently ? .modeSilent : nil) - let sendsOriginals = attachments.sendsMediaAsOriginal func enqueueAttachments(replyToMessageId: Int64?) { - func enqueue(_ mediaItems: [FileMediaItem]) { - // Neighbouring photos and videos go out as albums; the text is the first one's caption. - for send in TransactionSendMessage.sends( - text: text, - peerId: destinationPeerId, - chatId: destinationChatId, // FIXME: chatId fallback - mediaItems: mediaItems, - replyToMsgId: replyToMessageId, - entities: entities, - sendMode: effectiveSendMode - ) { - Transactions.shared.mutate(transaction: .sendMessage(send)) - } - } - guard sendsOriginals else { - enqueue(attachmentItemsSnapshot) - return - } - // Original: each photo and video goes as its untouched file, in the same order. - Task { @MainActor in - enqueue(await FileMediaItem.withOriginals(attachmentItemsSnapshot)) + // Neighbouring items go out as albums, photos and videos before files (Send as Original + // items among them); the text is the caption of the first one sent. + for send in TransactionSendMessage.sends( + text: text, + peerId: destinationPeerId, + chatId: destinationChatId, // FIXME: chatId fallback + mediaItems: attachmentItemsSnapshot, + replyToMsgId: replyToMessageId, + entities: entities, + sendMode: effectiveSendMode + ) { + Transactions.shared.mutate(transaction: .sendMessage(send)) } } @@ -2917,14 +2909,11 @@ class GlassComposeAppKit: NSView { agentContext: context.agentContext() ) guard !draft.isEmpty else { return } - let sendsOriginals = attachments.sendsMediaAsOriginal - isSubmittingNewThread = true setNewThreadAuthoringEnabled(false) updateSendButtonIfNeeded() Task { @MainActor [weak self] in - let draft = sendsOriginals ? await draft.withOriginalMedia() : draft let result = await context.submit(draft, intent) // Submission feedback belongs to the host, not this view's lifetime. // An early navigation may tear Compose down while the send is still @@ -4435,7 +4424,7 @@ extension GlassComposeAppKit { return } attachmentItems[attachment.id] = attachment.media - attachments.addImageView(image, id: attachment.id) + attachments.addImageView(image, id: attachment.id, media: attachment.media) case let .video(videoInfo): attachmentItems[attachment.id] = attachment.media attachments.addVideoView(videoInfo, id: attachment.id) @@ -4470,6 +4459,59 @@ extension GlassComposeAppKit: ComposeImplementation, ComposeAttachmentOwner { self } + /// Send as Original from an item's menu: switches a photo or video to a file of its untouched + /// original, or an image or video file back to a compressed photo or video. The item changes + /// in place once the other form is ready: a file moves to the file list, where it's sent + /// after the photos and videos. + func switchOriginal(attachmentId id: String) { + guard let media = attachmentItems[id], media.canSwitchOriginal, !switchingAttachmentIds.contains(id) else { + return + } + switchingAttachmentIds.insert(id) + Task { @MainActor [weak self] in + let switched: FileMediaItem? + do { + switched = try await media.switchedForOriginal() + } catch { + Log.shared.error("Couldn't switch the attachment for Send as Original", error: error) + switched = nil + } + guard let self else { + await switched?.discardUnsent() + return + } + switchingAttachmentIds.remove(id) + guard let switched else { + if attachmentItems[id] != nil { + ToastCenter.shared.showError( + media.isSentAsFile ? "This file can only be sent as a file." : "The original is no longer available." + ) + } + return + } + // Sent or removed while switching: keep nothing new. + guard attachmentItems[id] != nil, let attachment = replaceStoredAttachment(id: id, with: switched) else { + await switched.discardUnsent() + return + } + attachmentItems.removeValue(forKey: id) + removeDraftAttachmentPlaceholder(id: id) + renderDraftAttachment(attachment) + updateHeight(animate: true) + notifyNewThreadDraftChanged() + await media.discardUnsent() + } + } + + private func replaceStoredAttachment(id: String, with media: FileMediaItem) -> Drafts2Attachment? { + switch usage { + case .chat: + drafts2.replaceAttachment(peer: peerId, id: id, with: media) + case let .newThread(context): + context.attachmentStore.replace(id: id, with: media) + } + } + func composeAttachmentsDidChangeStaged(_: Bool) { syncAttachmentEscHandler() } diff --git a/apple/InlineMac/Views/Compose/ImageAttachment.swift b/apple/InlineMac/Views/Compose/ImageAttachment.swift index f92e9ea8b3..2d20a97ce1 100644 --- a/apple/InlineMac/Views/Compose/ImageAttachment.swift +++ b/apple/InlineMac/Views/Compose/ImageAttachment.swift @@ -13,6 +13,8 @@ class ImageAttachmentView: NSView, QLPreviewItem { private var width: CGFloat = 80 private let closeButtonSize: CGFloat = 20 private var hoverTrackingArea: NSTrackingArea? + /// Send as Original, offered once the photo is ready. + let originalOption = SendAsOriginalOption() init( image: NSImage, @@ -173,6 +175,7 @@ class ImageAttachmentView: NSView, QLPreviewItem { copyItem.image = NSImage(systemSymbolName: "document.on.document", accessibilityDescription: nil) menu.addItem(copyItem) + originalOption.install(in: menu) self.menu = menu } diff --git a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift index 8572fdd2c1..999220b18d 100644 --- a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift @@ -90,6 +90,8 @@ class LegacyComposeAppKit: NSView { private var voiceSpaceKeyUnsubscribe: (() -> Void)? // [uniqueId: FileMediaItem] + /// Attachments being switched between photo and file by Send as Original. + private var switchingAttachmentIds: Set = [] private var attachmentItems: [String: FileMediaItem] = [:] { didSet { updateSendButtonIfNeeded() @@ -1770,29 +1772,19 @@ class LegacyComposeAppKit: NSView { } let effectiveSendMode = sendMode ?? (state.sendSilently ? .modeSilent : nil) - let sendsOriginals = attachments.sendsMediaAsOriginal func enqueueAttachments(replyToMessageId: Int64?) { - func enqueue(_ mediaItems: [FileMediaItem]) { - // Neighbouring photos and videos go out as albums; the text is the first one's caption. - for send in TransactionSendMessage.sends( - text: text, - peerId: destinationPeerId, - chatId: destinationChatId, // FIXME: chatId fallback - mediaItems: mediaItems, - replyToMsgId: replyToMessageId, - entities: entities, - sendMode: effectiveSendMode - ) { - Transactions.shared.mutate(transaction: .sendMessage(send)) - } - } - guard sendsOriginals else { - enqueue(attachmentItemsSnapshot) - return - } - // Original: each photo and video goes as its untouched file, in the same order. - Task { @MainActor in - enqueue(await FileMediaItem.withOriginals(attachmentItemsSnapshot)) + // Neighbouring items go out as albums, photos and videos before files (Send as Original + // items among them); the text is the caption of the first one sent. + for send in TransactionSendMessage.sends( + text: text, + peerId: destinationPeerId, + chatId: destinationChatId, // FIXME: chatId fallback + mediaItems: attachmentItemsSnapshot, + replyToMsgId: replyToMessageId, + entities: entities, + sendMode: effectiveSendMode + ) { + Transactions.shared.mutate(transaction: .sendMessage(send)) } } @@ -3293,7 +3285,7 @@ extension LegacyComposeAppKit { return } attachmentItems[attachment.id] = attachment.media - attachments.addImageView(image, id: attachment.id) + attachments.addImageView(image, id: attachment.id, media: attachment.media) case let .video(videoInfo): attachmentItems[attachment.id] = attachment.media attachments.addVideoView(videoInfo, id: attachment.id) @@ -3328,6 +3320,53 @@ extension LegacyComposeAppKit: ComposeImplementation, ComposeAttachmentOwner { self } + /// Send as Original from an item's menu: switches a photo or video to a file of its untouched + /// original, or an image or video file back to a compressed photo or video. The item changes + /// in place once the other form is ready: a file moves to the file list, where it's sent + /// after the photos and videos. + func switchOriginal(attachmentId id: String) { + guard let media = attachmentItems[id], media.canSwitchOriginal, !switchingAttachmentIds.contains(id) else { + return + } + switchingAttachmentIds.insert(id) + Task { @MainActor [weak self] in + let switched: FileMediaItem? + do { + switched = try await media.switchedForOriginal() + } catch { + Log.shared.error("Couldn't switch the attachment for Send as Original", error: error) + switched = nil + } + guard let self else { + await switched?.discardUnsent() + return + } + switchingAttachmentIds.remove(id) + guard let switched else { + if attachmentItems[id] != nil { + ToastCenter.shared.showError( + media.isSentAsFile ? "This file can only be sent as a file." : "The original is no longer available." + ) + } + return + } + // Sent or removed while switching: keep nothing new. + guard attachmentItems[id] != nil, let attachment = replaceStoredAttachment(id: id, with: switched) else { + await switched.discardUnsent() + return + } + attachmentItems.removeValue(forKey: id) + removeDraftAttachmentPlaceholder(id: id) + renderDraftAttachment(attachment) + updateHeight(animate: true) + await media.discardUnsent() + } + } + + private func replaceStoredAttachment(id: String, with media: FileMediaItem) -> Drafts2Attachment? { + drafts2.replaceAttachment(peer: peerId, id: id, with: media) + } + func composeAttachmentsDidChangeStaged(_: Bool) { syncAttachmentEscHandler() } diff --git a/apple/InlineMac/Views/Compose/NewThreadComposeContext.swift b/apple/InlineMac/Views/Compose/NewThreadComposeContext.swift index 6602025cb3..c876c00ba5 100644 --- a/apple/InlineMac/Views/Compose/NewThreadComposeContext.swift +++ b/apple/InlineMac/Views/Compose/NewThreadComposeContext.swift @@ -101,6 +101,15 @@ final class NewThreadComposeAttachmentStore { attachments.contains { $0.id == id } } + /// Puts another form of the same item in an attachment's place (Send as Original). Nil when + /// `id` has left the draft. + func replace(id: String, with media: FileMediaItem) -> Drafts2Attachment? { + guard let index = attachments.firstIndex(where: { $0.id == id }) else { return nil } + let attachment = Drafts2Attachment(id: media.getItemUniqueId(), media: media, createdAt: attachments[index].createdAt) + attachments[index] = attachment + return attachment + } + func clear() { let activeTasks = Array(tasks.values) tasks.removeAll() @@ -187,25 +196,6 @@ final class DefaultNewThreadComposeMentionSource: NewThreadComposeMentionSource /// The immutable authoring result captured synchronously from the real Glass /// editor before any thread creation or network work starts. -extension PreparedNewThreadDraft { - /// The same draft with each photo and video swapped for its untouched file (Original on). - func withOriginalMedia() async -> PreparedNewThreadDraft { - let media = await FileMediaItem.withOriginals(attachments.map(\.media)) - let swapped = zip(attachments, media).map { attachment, media in - Drafts2Attachment(id: media.getItemUniqueId(), media: media, createdAt: attachment.createdAt) - } - return PreparedNewThreadDraft( - authorUserID: authorUserID, - text: text, - entities: entities, - attachments: swapped, - destination: destination, - sendSilently: sendSilently, - agentContext: agentContext - ) - } -} - struct PreparedNewThreadDraft { let authorUserID: Int64 let text: String diff --git a/apple/InlineMac/Views/Compose/VideoAttachmentView.swift b/apple/InlineMac/Views/Compose/VideoAttachmentView.swift index e569599523..98a7540dc8 100644 --- a/apple/InlineMac/Views/Compose/VideoAttachmentView.swift +++ b/apple/InlineMac/Views/Compose/VideoAttachmentView.swift @@ -14,6 +14,8 @@ final class VideoAttachmentView: NSView, QLPreviewItem { private let closeButtonSize: CGFloat = 20 private let videoURL: URL? private var hoverTrackingArea: NSTrackingArea? + /// Send as Original, offered once the video is ready. + let originalOption = SendAsOriginalOption() init( thumbnail: NSImage?, @@ -59,6 +61,17 @@ final class VideoAttachmentView: NSView, QLPreviewItem { configureCloseButtonBackground(closeButtonBackground) configureCloseButton(closeButton) setupView() + setupContextMenu() + } + + private func setupContextMenu() { + let menu = NSMenu() + let removeItem = NSMenuItem(title: "Remove", action: #selector(removeButtonClicked), keyEquivalent: "") + removeItem.target = self + removeItem.image = NSImage(systemSymbolName: "trash", accessibilityDescription: nil) + menu.addItem(removeItem) + originalOption.install(in: menu) + self.menu = menu } @available(*, unavailable) From efffcad8e11fd37cdb5ed1c036f1d6d6d7c05ee0 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sun, 22 Nov 2026 15:55:42 +0000 Subject: [PATCH 07/14] apple: say pasted images keep no original in the materializer comment --- .../Sources/InlineKit/Files/AttachmentMediaMaterializer.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift index 3921549627..54ba277993 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift @@ -52,8 +52,8 @@ public enum AttachmentMediaMaterializer { try OriginalMediaStore.retain(data: data, fileName: name, for: media) case .cgImage, .platformImage: // A camera capture handed over as pixels has no file behind it: keep a full-resolution - // copy so Original still sends every pixel. Other pixel-only images (pastes, stickers) - // send the prepared photo even when marked Send as Original. + // copy so Send as Original still sends every pixel. Other pixel-only images (pastes, + // stickers) keep no original, so they stay photos. guard content == .camera else { break } let full = try MediaSendPreparation.preparePhoto( source, From 4c3da053024f305b5fd4b8212169176b324e5a13 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sun, 22 Nov 2026 15:55:42 +0000 Subject: [PATCH 08/14] ios: say there's no original file instead of no longer available --- apple/InlineIOS/Features/Compose/ComposeView.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apple/InlineIOS/Features/Compose/ComposeView.swift b/apple/InlineIOS/Features/Compose/ComposeView.swift index 1a4c4ac4ad..02b60f139d 100644 --- a/apple/InlineIOS/Features/Compose/ComposeView.swift +++ b/apple/InlineIOS/Features/Compose/ComposeView.swift @@ -2434,7 +2434,7 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { guard let switched else { self.previewTile(for: attachmentId)?.setSwitching(false) ToastManager.shared.showToast( - item.isSentAsFile ? "This file can only be sent as a file." : "The original is no longer available.", + item.isSentAsFile ? "This file can only be sent as a file." : "There's no original file for this item.", type: .error, systemImage: "exclamationmark.triangle.fill" ) @@ -2460,7 +2460,7 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { case let .available(summary): return .init(isOn: isOn, detail: summary.detailText, isAvailable: !isSwitching) case .unavailable: - return .init(isOn: isOn, detail: "The original is no longer available", isAvailable: false) + return .init(isOn: isOn, detail: "No original file kept", isAvailable: false) case .loading, nil: return .init(isOn: isOn, detail: nil, isAvailable: !isSwitching) } From 24573ed438a8c1fc0b8de135779ec81dadf3cc89 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Sun, 22 Nov 2026 15:55:42 +0000 Subject: [PATCH 09/14] macos: say there's no original file instead of no longer available --- apple/InlineMac/Views/Compose/ComposeAttachments.swift | 4 ++-- apple/InlineMac/Views/Compose/GlassComposeAppKit.swift | 2 +- apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apple/InlineMac/Views/Compose/ComposeAttachments.swift b/apple/InlineMac/Views/Compose/ComposeAttachments.swift index 1af6b15c86..5153af1885 100644 --- a/apple/InlineMac/Views/Compose/ComposeAttachments.swift +++ b/apple/InlineMac/Views/Compose/ComposeAttachments.swift @@ -687,7 +687,7 @@ final class SendAsOriginalOption: NSObject, NSMenuItemValidation { var onChange: (() -> Void)? - /// The untouched file is gone (the system cleared temporary files), so there's nothing to switch to. + /// No untouched file was kept (a paste) or the system cleared it, so there's nothing to switch to. private var isMissingOriginal = false let menuItem = NSMenuItem(title: "Send as Original", action: #selector(toggle), keyEquivalent: "") @@ -710,7 +710,7 @@ final class SendAsOriginalOption: NSObject, NSMenuItemValidation { /// The original's size and whether it carries a location, or nil when it is gone. func setSummary(_ summary: OriginalMediaSummary?) { isMissingOriginal = summary == nil - menuItem.subtitle = summary?.detailText ?? "The original is no longer available" + menuItem.subtitle = summary?.detailText ?? "No original file kept" } @objc private func toggle() { diff --git a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift index fa42178edf..773f71d5b6 100644 --- a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift @@ -4484,7 +4484,7 @@ extension GlassComposeAppKit: ComposeImplementation, ComposeAttachmentOwner { guard let switched else { if attachmentItems[id] != nil { ToastCenter.shared.showError( - media.isSentAsFile ? "This file can only be sent as a file." : "The original is no longer available." + media.isSentAsFile ? "This file can only be sent as a file." : "There's no original file for this item." ) } return diff --git a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift index 999220b18d..af844b6800 100644 --- a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift @@ -3345,7 +3345,7 @@ extension LegacyComposeAppKit: ComposeImplementation, ComposeAttachmentOwner { guard let switched else { if attachmentItems[id] != nil { ToastCenter.shared.showError( - media.isSentAsFile ? "This file can only be sent as a file." : "The original is no longer available." + media.isSentAsFile ? "This file can only be sent as a file." : "There's no original file for this item." ) } return From d15655d4204dc29344e8a400887ddf55d24a8e6f Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 09:18:54 +0000 Subject: [PATCH 10/14] apple: keep metadata out of media sent as files without Send as Original, keep a gif's original, and re-prepare uploads staged by older builds - a photo that goes as a file because it is too thin to show or couldn't be prepared keeps its own bytes only when they carry no camera, place or time details; otherwise it goes as a full-resolution copy without them, or not at all. a video that couldn't be prepared and carries a location is refused instead of sent untouched. - a staged photo body is reused only when it is already prepared, and video staging descriptors carry a version. anything an older build staged (which could be the untouched original) is discarded with its sidecars, so the upload starts over from a prepared body under a new identity. - an animation converted from a gif keeps the gif as its original, so send as original sends the gif instead of the converted video; a gif file switches back to an animation. --- .../Files/AttachmentMediaMaterializer.swift | 53 +++++++++++++++---- .../Sources/InlineKit/Files/FileUpload.swift | 27 +++++++--- .../Files/MediaSendPreparation.swift | 24 +++++++++ .../InlineKit/Files/NativeUpload.swift | 5 ++ .../InlineKit/Files/OriginalMediaStore.swift | 29 +++++++--- .../MediaSendPreparationTests.swift | 47 +++++++++++++++- .../InlineKitTests/NativeUploadTests.swift | 20 +++++++ 7 files changed, 178 insertions(+), 27 deletions(-) diff --git a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift index 54ba277993..a7213119a2 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift @@ -4,6 +4,18 @@ import Logger /// Turns a selected attachment into its preferred rich representation without /// ever making that representation a requirement for retaining the source. public enum AttachmentMediaMaterializer { + public enum MaterializationError: Error, LocalizedError { + /// The video couldn't be prepared, and its file carries a location: it isn't sent as it is + /// unless someone chooses Send as Original. + case videoNotPrepared + + public var errorDescription: String? { + switch self { + case .videoNotPrepared: "This video couldn't be prepared for sending." + } + } + } + /// Prepares a picked photo for sending (see `MediaSendPreparation`) and keeps its untouched /// source for the item's Send as Original option. Images too thin or too small to show as a photo /// go as a file, as before. @@ -67,11 +79,19 @@ public enum AttachmentMediaMaterializer { } } - /// The source as a file and sent as a document, untouched where an encoded source exists. + /// The source as a file and sent as a document, for an image too thin or tiny to show as a photo + /// or one that couldn't be prepared. Nobody chose Send as Original, so an encoded source goes + /// untouched only when it carries no camera, place or time details; otherwise it goes as a + /// full-resolution copy without them, or not at all. private static func document( from source: MediaSendPreparation.PhotoSource, fileName: String? ) async throws -> FileMediaItem { + let stem = { (fallback: String) in fileName.map { ($0 as NSString).deletingPathExtension } ?? fallback } + if let copy = try MediaSendPreparation.anonymizedFileCopy(of: source) { + let name = stem("image-\(UUID().uuidString)") + copy.format.toExt() + return try await documentFromTemporaryFile(named: name) { try copy.data.write(to: $0, options: .atomic) } + } switch source { case let .file(url): return .document(try await FileCache.saveDocumentWithThumbnail(url: url)) @@ -79,13 +99,8 @@ public enum AttachmentMediaMaterializer { let name = fileName ?? "image-\(UUID().uuidString)." + (MediaSendPreparation.fileExtension(of: data) ?? "png") return try await documentFromTemporaryFile(named: name) { try data.write(to: $0, options: .atomic) } case .cgImage, .platformImage: - // Full resolution: a long screenshot sent as a file must stay readable. - let full = try MediaSendPreparation.preparePhoto( - source, - target: .init(maxPixelSize: 100_000, jpegQuality: 0.92) - ) - let name = (fileName.map { ($0 as NSString).deletingPathExtension } ?? "image-\(UUID().uuidString)") - + full.format.toExt() + let full = try MediaSendPreparation.preparePhoto(source, target: MediaSendPreparation.fileCopyTarget) + let name = stem("image-\(UUID().uuidString)") + full.format.toExt() return try await documentFromTemporaryFile(named: name) { try full.data.write(to: $0, options: .atomic) } } } @@ -131,18 +146,34 @@ public enum AttachmentMediaMaterializer { } return video } fallback: { - .document(try await FileCache.saveDocumentWithThumbnail(url: url)) + // Nobody chose Send as Original: a file with a location doesn't go as it is. + guard !(await OriginalMediaStore.videoIncludesLocation(url)) else { + throw MaterializationError.videoNotPrepared + } + return .document(try await FileCache.saveDocumentWithThumbnail(url: url)) } } - public static func animatedImage(_ url: URL) async throws -> FileMediaItem { + public static func animatedImage(_ url: URL, originalFileName: String? = nil) async throws -> FileMediaItem { try await withBareFileFallback { - .video(try await FileCache.saveAnimatedImageAsVideo(url: url)) + let video = FileMediaItem.video(try await FileCache.saveAnimatedImageAsVideo(url: url)) + retainAnimationOriginal(url, fileName: originalFileName, for: video) + return video } fallback: { .document(try await FileCache.saveDocumentWithThumbnail(url: url)) } } + /// Keeps the GIF behind an animation converted to video: Send as Original sends the GIF, not + /// the converted video. Call before the source file is removed. + public static func retainAnimationOriginal(_ url: URL, fileName: String? = nil, for video: FileMediaItem) { + do { + try OriginalMediaStore.retain(copyOf: url, fileName: fileName ?? url.lastPathComponent, for: video) + } catch { + Log.shared.warning("Couldn't keep the original animation for sending as a file: \(error.localizedDescription)") + } + } + public static func file(_ url: URL) async throws -> FileMediaItem { let worker = Task.detached(priority: .userInitiated) { try FolderArchive.createIfDirectory(at: url) } let archive = try await withTaskCancellationHandler { diff --git a/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift b/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift index 5770886526..9d559ab469 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift @@ -681,11 +681,18 @@ public actor FileUploader { // would only burn CPU and battery on output that is thrown away. The staging key is // owner-scoped like the coordinator's, and the upload reads the staged (compressed) body, // so its size checks measure what is sent, not the original. - if let owner = Auth.shared.getCurrentUserId(), - let staged = await FileNativeUploadStagingStore.shared.stagedBody(logicalID: "\(owner):\(uploadId)") - { - uploadUrl = staged - break + if let owner = Auth.shared.getCurrentUserId() { + let logicalID = "\(owner):\(uploadId)" + if let staged = await FileNativeUploadStagingStore.shared.stagedBody(logicalID: logicalID) { + // An older build could stage the untouched photo when its compression failed. Reuse only + // a prepared body; otherwise drop it (staging would hand it back), so this upload starts + // over from a prepared one under a new identity, which follows the body's hash. + if !MediaSendPreparation.photoNeedsPreparation(at: staged) { + uploadUrl = staged + break + } + await FileNativeUploadStagingStore.shared.discard(logicalID: logicalID) + } } // Photos are prepared when attached, so this is normally a header read. Anything still too // large or carrying camera, place or time details (a draft from an older build) is prepared @@ -1162,7 +1169,11 @@ public actor FileUploader { publishProgress(uploadId: uploadId, progress: .processing(id: uploadId)) let owner = try Auth.shared.handle.beginAccountMutation() let logicalID = "\(owner.userID):\(uploadId)" - if let (stagedURL, prepared) = try await FileNativeUploadStagingStore.shared.preparedVideo(logicalID: logicalID) { + // Older builds staged the untouched video when compression wasn't needed or failed. Reuse only + // a body this build prepared; drop anything else (staging would hand it back), so the upload + // starts over from a prepared one under a new identity, which follows the body's hash. + let staged = try? await FileNativeUploadStagingStore.shared.preparedVideo(logicalID: logicalID) + if let (stagedURL, prepared) = staged, prepared.version == FileNativeUploadStagingStore.PreparedVideo.currentVersion { try Auth.shared.handle.validateAccountMutation(owner) return PreparedVideoUploadPayload( url: stagedURL, fileName: prepared.fileName, mimeType: prepared.mimeType, @@ -1173,6 +1184,7 @@ public actor FileUploader { ), cleanupAfterUpload: false ) } + await FileNativeUploadStagingStore.shared.discard(logicalID: logicalID) let prepared = try await prepareVideoForUploadUnstaged( uploadId: uploadId, localUrl: localUrl, inputMimeType: inputMimeType, metadata: metadata ) @@ -1180,7 +1192,8 @@ public actor FileUploader { try Auth.shared.handle.validateAccountMutation(owner) try await FileNativeUploadStagingStore.shared.recordPreparedVideo(.init( fileName: prepared.fileName, mimeType: prepared.mimeType, width: prepared.metadata.width, - height: prepared.metadata.height, duration: prepared.metadata.duration + height: prepared.metadata.height, duration: prepared.metadata.duration, + version: FileNativeUploadStagingStore.PreparedVideo.currentVersion ), logicalID: logicalID) return prepared } catch { diff --git a/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift b/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift index da012aeb8e..91f8e81679 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift @@ -114,6 +114,30 @@ public enum MediaSendPreparation { return carriesIdentifyingMetadata(properties) } + /// Full resolution, for an image that goes as a file: a long screenshot must stay readable. + public static let fileCopyTarget = PhotoTarget(maxPixelSize: 100_000, jpegQuality: 0.92) + + /// An image that goes as a file without Send as Original (too thin or tiny to show as a photo, + /// or it couldn't be prepared) keeps its own bytes only when they carry nothing identifying. + /// Otherwise this is a full-resolution copy, upright and without metadata, and it throws rather + /// than let such an image go untouched. Nil: the image can go as it is (no metadata, or not an + /// image ImageIO reads, so nothing it could find). + public static func anonymizedFileCopy(of source: PhotoSource) throws -> PreparedPhoto? { + let imageSource: CGImageSource? = switch source { + case let .file(url): CGImageSourceCreateWithURL(url as CFURL, sourceOptions) + case let .data(data): CGImageSourceCreateWithData(data as CFData, sourceOptions) + // Pixels carry no metadata. + case .cgImage, .platformImage: nil + } + guard let imageSource, + let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [CFString: Any], + carriesIdentifyingMetadata(properties) + else { + return nil + } + return try prepare(imageSource: imageSource, content: nil, target: fileCopyTarget) + } + /// Images too thin or too tiny to show as a photo are sent as files. The server rejects photos /// with an aspect ratio over 20. public static func shouldSendAsDocument(width: Int, height: Int) -> Bool { diff --git a/apple/InlineKit/Sources/InlineKit/Files/NativeUpload.swift b/apple/InlineKit/Sources/InlineKit/Files/NativeUpload.swift index 04de2b49dc..70f7272e09 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/NativeUpload.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/NativeUpload.swift @@ -183,11 +183,16 @@ public actor FileNativeUploadStagingStore: NativeUploadStaging { } struct PreparedVideo: Codable, Sendable { + /// Re-encoded or remuxed without location or device details. Older builds wrote no version + /// and could stage the untouched video. + static let currentVersion = 2 + let fileName: String let mimeType: String let width: Int let height: Int let duration: Int + var version: Int? } func preparedVideo(logicalID: String) throws -> (URL, PreparedVideo)? { diff --git a/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift b/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift index 3712defb0a..c79245d0e8 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift @@ -120,7 +120,7 @@ public extension OriginalMediaStore { case .photo: url = original(for: media) case .video: - url = original(for: media) ?? media.localFileURL() + url = media.originalVideoFile case .document: // An image or video file that Send as Original switched to (or that was attached as one). guard media.canSwitchOriginal else { return nil } @@ -170,7 +170,7 @@ public extension FileMediaItem { true case let .document(info): Self.switchableFileTypes(mimeType: info.document.mimeType, fileName: info.document.fileName) - .contains { $0.conforms(to: .movie) || Self.isCompressibleImage($0) } + .contains { $0.conforms(to: .movie) || $0.conforms(to: .gif) || Self.isCompressibleImage($0) } case .voice: false } @@ -192,9 +192,7 @@ public extension FileMediaItem { guard let original = OriginalMediaStore.original(for: self) else { return nil } return .document(try await FileCache.saveDocumentWithThumbnail(url: original)) case .video: - // The cached video is an untouched copy too; a kept original adds its real file name. - let original = OriginalMediaStore.original(for: self) ?? localFileURL() - guard let original, FileManager.default.fileExists(atPath: original.path) else { return nil } + guard let original = originalVideoFile, FileManager.default.fileExists(atPath: original.path) else { return nil } return .document(try await FileCache.saveDocumentWithThumbnail(url: original)) case let .document(info): guard canSwitchOriginal, let url = localFileURL(), FileManager.default.fileExists(atPath: url.path) else { @@ -202,6 +200,8 @@ public extension FileMediaItem { } let media = if isVideoForOriginal { try await AttachmentMediaMaterializer.video(url, originalFileName: info.document.fileName) + } else if isGIFForOriginal { + try await AttachmentMediaMaterializer.animatedImage(url, originalFileName: info.document.fileName) } else { try await AttachmentMediaMaterializer.photo(.file(url), originalFileName: info.document.fileName) } @@ -232,6 +232,21 @@ public extension FileMediaItem { } } + /// The file Send as Original sends for a video. The cached video is an untouched copy too (a + /// kept original adds its real file name), but an animation's cached video was converted from + /// its GIF, so only the kept GIF will do. + internal var originalVideoFile: URL? { + guard case let .video(info) = self else { return nil } + if let original = OriginalMediaStore.original(for: self) { return original } + return info.video.isAnimated ? nil : localFileURL() + } + + internal var isGIFForOriginal: Bool { + guard case let .document(info) = self else { return false } + return Self.switchableFileTypes(mimeType: info.document.mimeType, fileName: info.document.fileName) + .contains { $0.conforms(to: .gif) } + } + internal var isVideoForOriginal: Bool { switch self { case .video: @@ -253,8 +268,8 @@ public extension FileMediaItem { return [fromMime, fromName].compactMap { $0 } } - /// A still image the photo preparer can compress. GIFs stay files (they'd lose their motion), - /// and so does vector art. + /// A still image the photo preparer can compress. GIFs switch to an animation instead (as a + /// photo they'd lose their motion), and vector art stays a file. internal static func isCompressibleImage(_ type: UTType) -> Bool { type.conforms(to: .image) && !type.conforms(to: .gif) && !type.conforms(to: .svg) } diff --git a/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift b/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift index 3cceed50e9..3eda2ade0b 100644 --- a/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift +++ b/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift @@ -106,6 +106,25 @@ struct MediaSendPreparationTests { #expect(!MediaSendPreparation.shouldSendAsDocument(width: 40, height: 60)) } + @Test("a photo that goes as a file without Send as Original loses its location; a clean one goes as it is") + func fileCopyWithoutMetadata() throws { + // Too thin to show as a photo, so it goes as a file. + let located = try write(makeJPEG(width: 2_100, height: 60, orientation: 1, camera: true, gps: true), ext: "jpg") + defer { try? FileManager.default.removeItem(at: located) } + #expect(MediaSendPreparation.shouldSendAsDocument(width: 2_100, height: 60)) + let copy = try #require(try MediaSendPreparation.anonymizedFileCopy(of: .file(located))) + let sent = try #require(properties(of: copy.data)) + #expect(sent[kCGImagePropertyGPSDictionary] == nil) + #expect((sent[kCGImagePropertyTIFFDictionary] as? [CFString: Any])?[kCGImagePropertyTIFFModel] == nil) + #expect(!MediaSendPreparation.carriesIdentifyingMetadata(sent)) + #expect(copy.width == 2_100 && copy.height == 60) + #expect(try MediaSendPreparation.anonymizedFileCopy(of: .data(Data(contentsOf: located))) != nil) + + let clean = try makePNG(width: 2_100, height: 60, transparentCorner: false) + #expect(try MediaSendPreparation.anonymizedFileCopy(of: .data(clean)) == nil) + #expect(try MediaSendPreparation.anonymizedFileCopy(of: .data(Data("not an image".utf8))) == nil) + } + @Test("the source extension is read from the bytes") func fileExtension() throws { #expect(MediaSendPreparation.fileExtension(of: try makePNG(width: 10, height: 10, transparentCorner: false)) == "png") @@ -156,12 +175,15 @@ struct OriginalMediaStoreTests { } - @Test("image and video files can switch back to compressed; GIFs, vectors and other files can't") + @Test("image, GIF and video files can switch back; vectors and other files can't") func fileEligibility() { #expect(documentItem("IMG_4821.HEIC", mimeType: "image/heic").canSwitchOriginal) #expect(documentItem("photo.jpg", mimeType: "application/octet-stream").canSwitchOriginal) #expect(documentItem("IMG_4822.MOV", mimeType: "video/quicktime").isVideoForOriginal) - #expect(!documentItem("loop.gif", mimeType: "image/gif").canSwitchOriginal) + // A GIF file switches back to an animation, not a photo. + #expect(documentItem("loop.gif", mimeType: "image/gif").canSwitchOriginal) + #expect(documentItem("loop.gif", mimeType: "image/gif").isGIFForOriginal) + #expect(!documentItem("loop.gif", mimeType: "image/gif").isVideoForOriginal) #expect(!documentItem("logo.svg", mimeType: "image/svg+xml").canSwitchOriginal) #expect(!documentItem("report.pdf", mimeType: "application/pdf").canSwitchOriginal) #expect(photoItem(localPath: "a.jpg").canSwitchOriginal) @@ -169,6 +191,23 @@ struct OriginalMediaStoreTests { #expect(documentItem("IMG_4821.HEIC", mimeType: "image/heic").isSentAsFile) } + @Test("an animation sends its kept GIF as original, never the video converted from it") + func animationOriginal() throws { + let stem = "animation-\(UUID().uuidString)" + let animation = videoItem(localPath: "\(stem).mp4", isAnimated: true) + #expect(animation.originalVideoFile == nil) + let video = videoItem(localPath: "video-\(UUID().uuidString).mp4", isAnimated: false) + #expect(video.originalVideoFile == video.localFileURL()) + + let gif = try write(Data("GIF89a".utf8), ext: "gif") + defer { + try? FileManager.default.removeItem(at: gif) + OriginalMediaStore.discard(for: animation) + } + AttachmentMediaMaterializer.retainAnimationOriginal(gif, fileName: "loop.gif", for: animation) + #expect(animation.originalVideoFile?.lastPathComponent == "loop.gif") + } + @Test("a photo whose original is gone can't switch") func switchWithoutOriginal() async throws { let item = photoItem(localPath: "no-original-\(UUID().uuidString).jpg") @@ -213,6 +252,10 @@ private func photoItem(localPath: String) -> FileMediaItem { ])) } +private func videoItem(localPath: String, isAnimated: Bool) -> FileMediaItem { + .video(VideoInfo(video: Video(videoId: -9, date: Date(timeIntervalSince1970: 1), localPath: localPath, isAnimated: isAnimated))) +} + private func documentItem(_ fileName: String, mimeType: String) -> FileMediaItem { .document(DocumentInfo(document: Document( id: nil, documentId: -11, date: Date(timeIntervalSince1970: 1), fileName: fileName, mimeType: mimeType, diff --git a/apple/InlineKit/Tests/InlineKitTests/NativeUploadTests.swift b/apple/InlineKit/Tests/InlineKitTests/NativeUploadTests.swift index 56a2a3fa78..e873ecc6f1 100644 --- a/apple/InlineKit/Tests/InlineKitTests/NativeUploadTests.swift +++ b/apple/InlineKit/Tests/InlineKitTests/NativeUploadTests.swift @@ -1673,3 +1673,23 @@ struct NativeUploadTests { #expect(DurableUploadCoordinator.adaptedPartWindow(2, after: .seconds(20)) == 2) } } + +struct PreparedVideoStagingVersionTests { + @Test("a video descriptor from an older build has no version, so its staged body isn't reused") + func olderDescriptorIsStale() throws { + let older = Data(#"{"fileName":"IMG_1.MOV","mimeType":"video/quicktime","width":1920,"height":1080,"duration":12}"#.utf8) + let decoded = try JSONDecoder().decode(FileNativeUploadStagingStore.PreparedVideo.self, from: older) + #expect(decoded.version == nil) + #expect(decoded.version != FileNativeUploadStagingStore.PreparedVideo.currentVersion) + + let current = FileNativeUploadStagingStore.PreparedVideo( + fileName: "video_1.mp4", mimeType: "video/mp4", width: 1280, height: 720, duration: 12, + version: FileNativeUploadStagingStore.PreparedVideo.currentVersion + ) + let roundTrip = try JSONDecoder().decode( + FileNativeUploadStagingStore.PreparedVideo.self, + from: JSONEncoder().encode(current) + ) + #expect(roundTrip.version == FileNativeUploadStagingStore.PreparedVideo.currentVersion) + } +} From a0de5736097e01f7eca5cd558312c64afb77a8bc Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 09:18:54 +0000 Subject: [PATCH 11/14] ios: send after send as original finishes switching, and hold a tile for photos being prepared - send waits while an item switches between photo and original, so it never goes in the form being left (an original carries its location). a failed switch cancels the waiting send. - pasted, dropped and recent-strip photos hold a pending tile before they are prepared, so a send waits for them and they land in this draft instead of the next one. photos are prepared two at a time, and the library picker loads two items at a time. - the share extension sends a photo that goes as a file without its camera, place or time details. --- .../Features/Compose/ComposeView.swift | 61 ++++++++-- .../Features/Compose/PhotoUtils.swift | 114 ++++++++++++------ apple/InlineShareExtension/ShareState.swift | 40 +++++- 3 files changed, 164 insertions(+), 51 deletions(-) diff --git a/apple/InlineIOS/Features/Compose/ComposeView.swift b/apple/InlineIOS/Features/Compose/ComposeView.swift index 02b60f139d..1cc9efe0ad 100644 --- a/apple/InlineIOS/Features/Compose/ComposeView.swift +++ b/apple/InlineIOS/Features/Compose/ComposeView.swift @@ -90,9 +90,12 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { case videos } + /// A tile held for media still being prepared (a video, or photos from paste, drop or the + /// recent strip), so a send waits for it and it lands in this draft. struct PendingVideoAttachment { let id: String var thumbnailImage: UIImage? + var symbolName = "video.fill" } var attachmentItems: [String: FileMediaItem] = [:] { @@ -728,7 +731,7 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { private func sendQueuedPendingVideoMessageIfReady() { guard pendingMediaSendState.consumeSendIfReady( - hasPendingMedia: !pendingVideoAttachments.isEmpty + hasPendingMedia: !pendingVideoAttachments.isEmpty || !switchingAttachmentIds.isEmpty ) else { return } let queuedSendMode = queuedPendingVideoSendMode queuedPendingVideoSendMode = nil @@ -1205,8 +1208,10 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { return } + // Send as Original still switching an item: it goes once that form is ready, never in the + // form it's leaving (an original would carry its location). if ComposePendingMediaSendBehavior.shouldQueueSendUntilPendingVideosAreReady( - hasPendingVideos: hasPendingVideos + hasPendingVideos: hasPendingVideos || !switchingAttachmentIds.isEmpty ) { queueSendUntilPendingVideosAreReady(sendMode: sendMode) return @@ -2359,7 +2364,8 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { for pending in pendingVideoAttachments { let preview = ComposeAttachmentPreviewItemView( pendingVideoId: pending.id, - thumbnailImage: pending.thumbnailImage + thumbnailImage: pending.thumbnailImage, + symbolName: pending.symbolName ) { [weak self] pendingId in self?.removePendingVideoAttachment(pendingId, userInitiated: true) } @@ -2426,13 +2432,16 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { return } self.switchingAttachmentIds.remove(attachmentId) - // Sent or removed while switching: keep nothing new. + // Removed while switching: keep nothing new, and let a send waiting on it go. guard self.attachmentItems[attachmentId] != nil else { + self.sendQueuedPendingVideoMessageIfReady() await switched?.discardUnsent() return } guard let switched else { self.previewTile(for: attachmentId)?.setSwitching(false) + // A send waiting on the switch would go in the form it was leaving; the person sends again. + self.cancelQueuedPendingVideoSend() ToastManager.shared.showToast( item.isSentAsFile ? "This file can only be sent as a file." : "There's no original file for this item.", type: .error, @@ -2440,8 +2449,13 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { ) return } - UIView.transition(with: self.attachmentStackView, duration: 0.22, options: .transitionCrossDissolve) { + if self.pendingMediaSendState.isAwaitingSend { + // Replacing releases the waiting send, which shouldn't run inside a transition. self.replaceAttachment(attachmentId, with: switched) + } else { + UIView.transition(with: self.attachmentStackView, duration: 0.22, options: .transitionCrossDissolve) { + self.replaceAttachment(attachmentId, with: switched) + } } await item.discardUnsent() } @@ -2487,14 +2501,40 @@ class ComposeView: UIView, NSTextLayoutManagerDelegate { } @discardableResult - func addPendingVideoAttachment() -> String { + func addPendingVideoAttachment(symbolName: String = "video.fill", thumbnailImage: UIImage? = nil) -> String { let pendingId = "pending_video_\(UUID().uuidString)" canceledPendingVideoAttachmentIds.remove(pendingId) - pendingVideoAttachments.append(PendingVideoAttachment(id: pendingId, thumbnailImage: nil)) + pendingVideoAttachments.append(PendingVideoAttachment(id: pendingId, thumbnailImage: thumbnailImage, symbolName: symbolName)) handleAttachmentItemsChanged(animated: false) return pendingId } + /// Fills tiles held by `addPendingVideoAttachment` with what was prepared for them, in order. + /// An item whose tile was removed meanwhile (by the person, or a change of chat) is discarded; + /// one that failed cancels a waiting send, which shouldn't go without it. + func fillPendingAttachments(_ pendingIds: [String], with items: [FileMediaItem?]) { + var unused: [FileMediaItem] = [] + var failed = false + for (pendingId, item) in zip(pendingIds, items) { + guard !isPendingVideoAttachmentCanceled(pendingId) else { + if let item { unused.append(item) } + continue + } + guard let item else { + failed = true + continue + } + attachmentItems[item.getItemUniqueId()] = item + } + if failed { + cancelQueuedPendingVideoSend() + } + completePendingVideoAttachments(pendingIds) + if !unused.isEmpty { + Task { for item in unused { await item.discardUnsent() } } + } + } + func updatePendingVideoAttachmentThumbnail(_ pendingId: String, image: UIImage?) { guard let index = pendingVideoAttachments.firstIndex(where: { $0.id == pendingId }) else { return } pendingVideoAttachments[index].thumbnailImage = image @@ -2921,6 +2961,7 @@ private final class ComposeAttachmentPreviewItemView: UIView, UIContextMenuInter init( pendingVideoId: String, thumbnailImage: UIImage?, + symbolName: String, onRemove: @escaping (String) -> Void ) { attachmentId = pendingVideoId @@ -2929,7 +2970,7 @@ private final class ComposeAttachmentPreviewItemView: UIView, UIContextMenuInter super.init(frame: .zero) accessibilityIdentifier = pendingVideoId setupViews() - configurePendingVideo(thumbnailImage: thumbnailImage) + configurePendingVideo(thumbnailImage: thumbnailImage, symbolName: symbolName) } @available(*, unavailable) @@ -3079,7 +3120,7 @@ private final class ComposeAttachmentPreviewItemView: UIView, UIContextMenuInter } } - private func configurePendingVideo(thumbnailImage: UIImage?) { + private func configurePendingVideo(thumbnailImage: UIImage?, symbolName: String) { setUploadProgress(nil) overlayIconView.isHidden = true extensionBadge.isHidden = true @@ -3087,7 +3128,7 @@ private final class ComposeAttachmentPreviewItemView: UIView, UIContextMenuInter applyPendingThumbnail(thumbnailImage) return } - applyFallback(iconName: "video.fill", badgeText: nil) + applyFallback(iconName: symbolName, badgeText: nil) } func setUploadProgress(_ progress: UploadProgressSnapshot?) { diff --git a/apple/InlineIOS/Features/Compose/PhotoUtils.swift b/apple/InlineIOS/Features/Compose/PhotoUtils.swift index 9f97a66c17..464e315e55 100644 --- a/apple/InlineIOS/Features/Compose/PhotoUtils.swift +++ b/apple/InlineIOS/Features/Compose/PhotoUtils.swift @@ -157,47 +157,64 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe } /// Prepares photos off the main thread (resized for their content, no metadata) and adds them - /// in the order given. + /// in the order given. Each holds a tile from the start, so a send waits for them and they + /// land in this draft, not the next one. func addPhotos( _ sources: [(source: MediaSendPreparation.PhotoSource, fileName: String?)], content: MediaSendPreparation.PhotoContent? = nil ) { guard !sources.isEmpty else { return } + let pendingIds = sources.map { entry in + let thumbnail: UIImage? = if case let .platformImage(image) = entry.source { image } else { nil } + return addPendingVideoAttachment(symbolName: "photo", thumbnailImage: thumbnail) + } Task { [weak self] in let items = await Self.preparePhotos(sources, content: content) - guard let self, !items.isEmpty else { return } - for item in items { - attachmentItems[item.getItemUniqueId()] = item + guard let self else { + for item in items.compactMap({ $0 }) { await item.discardUnsent() } + return } - handleAttachmentItemsChanged(animated: false) + fillPendingAttachments(pendingIds, with: items) } } + /// Photos prepared at once: each holds a decode and an encode in memory. + nonisolated static let photoPreparationConcurrency = 2 + + /// The prepared photos in the order given, nil where one failed. nonisolated static func preparePhotos( _ sources: [(source: MediaSendPreparation.PhotoSource, fileName: String?)], content: MediaSendPreparation.PhotoContent? = nil - ) async -> [FileMediaItem] { + ) async -> [FileMediaItem?] { await withTaskGroup(of: (Int, FileMediaItem?).self) { group in - for (index, entry) in sources.enumerated() { - group.addTask { - do { - let item = try await AttachmentMediaMaterializer.photo( - entry.source, - originalFileName: entry.fileName, - content: content - ) - return (index, item) - } catch { - Log.shared.error("Failed to save photo in attachments", error: error) - return (index, nil) - } + @Sendable func prepare(_ index: Int) async -> (Int, FileMediaItem?) { + let entry = sources[index] + do { + let item = try await AttachmentMediaMaterializer.photo( + entry.source, + originalFileName: entry.fileName, + content: content + ) + return (index, item) + } catch { + Log.shared.error("Failed to save photo in attachments", error: error) + return (index, nil) } } - var prepared: [(Int, FileMediaItem)] = [] + var next = min(photoPreparationConcurrency, sources.count) + for index in 0 ..< next { + group.addTask { await prepare(index) } + } + var prepared = [FileMediaItem?](repeating: nil, count: sources.count) for await (index, item) in group { - if let item { prepared.append((index, item)) } + prepared[index] = item + if next < sources.count { + let index = next + group.addTask { await prepare(index) } + next += 1 + } } - return prepared.sorted { $0.0 < $1.0 }.map(\.1) + return prepared } } @@ -300,6 +317,8 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe do { let videoInfo = try await FileCache.saveAnimatedImageAsVideo(url: url) let mediaItem = FileMediaItem.video(videoInfo) + // The GIF goes with Send as Original, not the video converted from it. + AttachmentMediaMaterializer.retainAnimationOriginal(url, for: mediaItem) await MainActor.run { [weak self] in guard let self else { return } @@ -360,6 +379,8 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe func openRecentAsset(localIdentifier: String) { guard localIdentifier.isEmpty == false else { return } + // Held from the start, so a send waits for it and it lands in this draft. + let pendingId = addPendingVideoAttachment(symbolName: "photo.on.rectangle") Task { [weak self] in guard let self else { return } @@ -371,11 +392,10 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe switch result { case let .success(mediaItem): - let uniqueId = mediaItem.getItemUniqueId() - attachmentItems[uniqueId] = mediaItem - handleAttachmentItemsChanged(animated: false) + fillPendingAttachments([pendingId], with: [mediaItem]) dismissAttachmentPickerIfPresented(animated: true) case let .failure(error): + fillPendingAttachments([pendingId], with: [nil]) showRecentAssetError(message: error.message) } } @@ -387,11 +407,13 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe guard validIdentifiers.isEmpty == false else { return } dismissAttachmentPickerIfPresented(animated: true) + // Held from the start, so a send waits for them and they land in this draft. + let pendingIds = validIdentifiers.map { _ in addPendingVideoAttachment(symbolName: "photo.on.rectangle") } Task { [weak self] in guard let self else { return } - var orderedMediaItems: [FileMediaItem] = [] + var orderedMediaItems: [FileMediaItem?] = [] var firstErrorMessage: String? for identifier in validIdentifiers { @@ -400,6 +422,7 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe case let .success(mediaItem): orderedMediaItems.append(mediaItem) case let .failure(error): + orderedMediaItems.append(nil) let message = error.message if firstErrorMessage == nil { firstErrorMessage = message @@ -410,13 +433,7 @@ extension ComposeView: UIImagePickerControllerDelegate, UINavigationControllerDe await MainActor.run { [weak self] in guard let self else { return } - if orderedMediaItems.isEmpty == false { - for mediaItem in orderedMediaItems { - let uniqueId = mediaItem.getItemUniqueId() - attachmentItems[uniqueId] = mediaItem - } - handleAttachmentItemsChanged(animated: false) - } + fillPendingAttachments(pendingIds, with: orderedMediaItems) if let firstErrorMessage { showRecentAssetError(message: firstErrorMessage) @@ -564,19 +581,30 @@ extension ComposeView: PHPickerViewControllerDelegate { var loadedItems: [(index: Int, item: LibraryPickerItem)] = [] + // A few at a time: each photo holds a decode and an encode in memory. await withTaskGroup(of: (Int, LibraryPickerItem?).self) { group in - for (index, result) in results.enumerated() { + var next = 0 + while next < min(Self.photoPreparationConcurrency, results.count) { + let index = next, result = results[index] group.addTask { [weak self] in guard let self else { return (index, nil) } - let item = await self.loadLibraryItem(from: result) - return (index, item) + return (index, await self.loadLibraryItem(from: result)) } + next += 1 } for await (index, item) in group { if let item { loadedItems.append((index: index, item: item)) } + if next < results.count { + let index = next, result = results[index] + group.addTask { [weak self] in + guard let self else { return (index, nil) } + return (index, await self.loadLibraryItem(from: result)) + } + next += 1 + } } } @@ -891,11 +919,14 @@ extension ComposeView: PHPickerViewControllerDelegate { return } + let originalName = provider.suggestedName.map { ($0 as NSString).appendingPathExtension("gif") ?? $0 } Task { defer { try? FileManager.default.removeItem(at: tempUrl) } do { - let videoInfo = try await FileCache.saveAnimatedImageAsVideo(url: tempUrl) - continuation.resume(returning: .video(videoInfo)) + let media = FileMediaItem.video(try await FileCache.saveAnimatedImageAsVideo(url: tempUrl)) + // The GIF goes with Send as Original, not the video converted from it. + AttachmentMediaMaterializer.retainAnimationOriginal(tempUrl, fileName: originalName, for: media) + continuation.resume(returning: media) } catch AnimatedImageVideoConversionError.notAnimated { continuation.resume(returning: nil) } catch { @@ -936,11 +967,14 @@ extension ComposeView: PHPickerViewControllerDelegate { return } + let originalName = provider.suggestedName.map { ($0 as NSString).appendingPathExtension("gif") ?? $0 } Task { defer { try? FileManager.default.removeItem(at: tempUrl) } do { - let videoInfo = try await FileCache.saveAnimatedImageAsVideo(url: tempUrl) - continuation.resume(returning: .video(videoInfo)) + let media = FileMediaItem.video(try await FileCache.saveAnimatedImageAsVideo(url: tempUrl)) + // The GIF goes with Send as Original, not the video converted from it. + AttachmentMediaMaterializer.retainAnimationOriginal(tempUrl, fileName: originalName, for: media) + continuation.resume(returning: media) } catch AnimatedImageVideoConversionError.notAnimated { continuation.resume(returning: nil) } catch { diff --git a/apple/InlineShareExtension/ShareState.swift b/apple/InlineShareExtension/ShareState.swift index 94956f876c..d6d2875801 100644 --- a/apple/InlineShareExtension/ShareState.swift +++ b/apple/InlineShareExtension/ShareState.swift @@ -349,6 +349,44 @@ class ShareState: ObservableObject { } } + /// A photo that goes as a file here (too thin to show, or it couldn't be prepared): nobody chose + /// to send its original, so it keeps no camera, place or time details. Its own bytes go only + /// when it carries none. + private nonisolated func photoDocumentFile( + from file: TemporarySharedFile, + fileName: String, + mimeType: MIMEType + ) throws -> PreparedSharedFile { + guard let copy = try MediaSendPreparation.anonymizedFileCopy(of: .file(file.url)) else { + return PreparedSharedFile( + url: file.url, + fileName: fileName, + mimeType: mimeType, + fileType: .document, + fileSize: fileSize(for: file.url) ?? 0, + isAnimatedImage: false, + videoMetadata: nil, + cleanupURLs: file.cleanupURLs + ) + } + let baseName = (fileName as NSString).deletingPathExtension + let copyName = (baseName.isEmpty ? "photo" : baseName) + copy.format.toExt() + let copyURL = temporaryURL(suggestedName: copyName, typeIdentifier: copy.format == .png + ? UTType.png.identifier + : UTType.jpeg.identifier) + try copy.data.write(to: copyURL, options: .atomic) + return PreparedSharedFile( + url: copyURL, + fileName: copyName, + mimeType: MIMEType(text: copy.format.toMimeType()), + fileType: .document, + fileSize: Int64(copy.data.count), + isAnimatedImage: false, + videoMetadata: nil, + cleanupURLs: file.cleanupURLs + [copyURL] + ) + } + private nonisolated func shouldSendPhotoAsDocument(at url: URL) -> Bool { guard let size = MediaSendPreparation.pixelSize(of: .file(url)) else { return false } return MediaSendPreparation.shouldSendAsDocument(width: size.width, height: size.height) @@ -1186,8 +1224,8 @@ class ShareState: ObservableObject { } else { log.warning(tagged("Couldn't prepare photo; sending as document (\(mimeType.text))")) ExtensionHealth.record("app.fallback", ["fallback_kind": "share_photo_as_document"]) - resolvedFileType = .document } + return try photoDocumentFile(from: file, fileName: fileName, mimeType: mimeType) } let size = fileSize(for: file.url) ?? 0 From 5d2f56da44d069880feefde617b27a4fa322e60a Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 09:18:54 +0000 Subject: [PATCH 12/14] macos: disable send while send as original switches an attachment send would go with the form being left, and an original carries its location. --- .../Views/Compose/GlassComposeAppKit.swift | 13 +++++++++---- .../Views/Compose/LegacyComposeAppKit.swift | 10 +++++++--- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift index 773f71d5b6..4279bc8e1d 100644 --- a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift @@ -100,10 +100,12 @@ class GlassComposeAppKit: NSView { private var canSend: Bool { switch usage { case .chat: - !drafts2.hasPendingAttachments(peer: peerId) && + switchingAttachmentIds.isEmpty && + !drafts2.hasPendingAttachments(peer: peerId) && (!isEmptyTrimmed || attachmentItems.count > 0 || state.forwardContext != nil) case let .newThread(context): - !context.attachmentStore.hasPendingAttachments && + switchingAttachmentIds.isEmpty && + !context.attachmentStore.hasPendingAttachments && (!isEmptyTrimmed || !context.attachmentStore.attachments.isEmpty) && !isSubmittingNewThread } @@ -175,8 +177,11 @@ class GlassComposeAppKit: NSView { private var voiceSpaceKeyUnsubscribe: (() -> Void)? // [uniqueId: FileMediaItem] - /// Attachments being switched between photo and file by Send as Original. - private var switchingAttachmentIds: Set = [] + /// Attachments being switched between photo and file by Send as Original. Send waits for them: + /// it would go in the form being left, and an original carries its location. + private var switchingAttachmentIds: Set = [] { + didSet { updateSendButtonIfNeeded() } + } private var attachmentItems: [String: FileMediaItem] = [:] { didSet { updateSendButtonIfNeeded() diff --git a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift index af844b6800..bf7b58ac06 100644 --- a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift @@ -45,7 +45,8 @@ class LegacyComposeAppKit: NSView { } private var canSend: Bool { - !drafts2.hasPendingAttachments(peer: peerId) && + switchingAttachmentIds.isEmpty && + !drafts2.hasPendingAttachments(peer: peerId) && (!isEmptyTrimmed || attachmentItems.count > 0 || state.forwardContext != nil) } @@ -90,8 +91,11 @@ class LegacyComposeAppKit: NSView { private var voiceSpaceKeyUnsubscribe: (() -> Void)? // [uniqueId: FileMediaItem] - /// Attachments being switched between photo and file by Send as Original. - private var switchingAttachmentIds: Set = [] + /// Attachments being switched between photo and file by Send as Original. Send waits for them: + /// it would go in the form being left, and an original carries its location. + private var switchingAttachmentIds: Set = [] { + didSet { updateSendButtonIfNeeded() } + } private var attachmentItems: [String: FileMediaItem] = [:] { didSet { updateSendButtonIfNeeded() From 775c35bc6b99bcd9497ac3fa7a4b0b7ab59e2fb1 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 09:38:30 +0000 Subject: [PATCH 13/14] apple: keep a retried upload's name and type, and refuse an unprepared video that may carry details from the pre-merge review: - a photo whose upload had to prepare it is staged in its prepared format. a retry that reuses that body now sends the same name and type, which the server checks against the same upload; it used to send the caller's (a png name for a staged jpeg) and every retry failed the create. - a video that couldn't be prepared goes as its untouched file only when its metadata can be read and carries no camera, place or time details; one that can't be read is refused too. - originals left by unsent drafts are swept when a video is attached as well. --- .../Files/AttachmentMediaMaterializer.swift | 13 ++++++----- .../Sources/InlineKit/Files/FileUpload.swift | 8 +++++++ .../Files/MediaSendPreparation.swift | 13 +++++++++++ .../InlineKit/Files/OriginalMediaStore.swift | 14 ++++++++++++ .../MediaSendPreparationTests.swift | 22 +++++++++++++++++++ 5 files changed, 65 insertions(+), 5 deletions(-) diff --git a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift index a7213119a2..797707a72d 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/AttachmentMediaMaterializer.swift @@ -5,8 +5,8 @@ import Logger /// ever making that representation a requirement for retaining the source. public enum AttachmentMediaMaterializer { public enum MaterializationError: Error, LocalizedError { - /// The video couldn't be prepared, and its file carries a location: it isn't sent as it is - /// unless someone chooses Send as Original. + /// The video couldn't be prepared, and its file carries (or may carry) camera, place or time + /// details: it isn't sent as it is unless someone chooses Send as Original. case videoNotPrepared public var errorDescription: String? { @@ -137,7 +137,9 @@ public enum AttachmentMediaMaterializer { thumbnail: PlatformImage? = nil, originalFileName: String? = nil ) async throws -> FileMediaItem { - try await withBareFileFallback { + // Off this thread: drafts nobody sent may have left originals behind. + Task.detached(priority: .utility) { OriginalMediaStore.sweep() } + return try await withBareFileFallback { let video = FileMediaItem.video(try await FileCache.saveVideo(url: url, thumbnail: thumbnail)) do { try OriginalMediaStore.retain(copyOf: url, fileName: originalFileName, for: video) @@ -146,8 +148,9 @@ public enum AttachmentMediaMaterializer { } return video } fallback: { - // Nobody chose Send as Original: a file with a location doesn't go as it is. - guard !(await OriginalMediaStore.videoIncludesLocation(url)) else { + // Nobody chose Send as Original: a file that may carry camera, place or time details + // doesn't go as it is. + guard !(await OriginalMediaStore.videoMayCarryIdentifyingMetadata(url)) else { throw MaterializationError.videoNotPrepared } return .document(try await FileCache.saveDocumentWithThumbnail(url: url)) diff --git a/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift b/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift index 9d559ab469..de45e937f7 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/FileUpload.swift @@ -689,6 +689,14 @@ public actor FileUploader { // over from a prepared one under a new identity, which follows the body's hash. if !MediaSendPreparation.photoNeedsPreparation(at: staged) { uploadUrl = staged + // Named and typed like the attempt that staged it, which the server checks against the + // same upload: one that had to prepare the photo sent its prepared format. + if MediaSendPreparation.photoNeedsPreparation(at: localUrl), + let format = MediaSendPreparation.preparedFormat(at: staged) + { + uploadMimeType = format.toMimeType() + uploadFileName = (fileName as NSString).deletingPathExtension + format.toExt() + } break } await FileNativeUploadStagingStore.shared.discard(logicalID: logicalID) diff --git a/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift b/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift index 91f8e81679..1d64be2740 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/MediaSendPreparation.swift @@ -114,6 +114,19 @@ public enum MediaSendPreparation { return carriesIdentifyingMetadata(properties) } + /// The format of a prepared photo file, read from its header; nil for anything else. + public static func preparedFormat(at url: URL) -> ImageFormat? { + guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, sourceOptions), + let identifier = CGImageSourceGetType(imageSource) as String?, + let type = UTType(identifier) + else { + return nil + } + if type.conforms(to: .png) { return .png } + if type.conforms(to: .jpeg) { return .jpeg } + return nil + } + /// Full resolution, for an image that goes as a file: a long screenshot must stay readable. public static let fileCopyTarget = PhotoTarget(maxPixelSize: 100_000, jpegQuality: 0.92) diff --git a/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift b/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift index c79245d0e8..995953f1db 100644 --- a/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift +++ b/apple/InlineKit/Sources/InlineKit/Files/OriginalMediaStore.swift @@ -152,6 +152,20 @@ public extension OriginalMediaStore { return gps[kCGImagePropertyGPSLatitude] != nil } + /// Whether a video file carries camera, place or time details, or can't be read to tell. + internal static func videoMayCarryIdentifyingMetadata(_ url: URL) async -> Bool { + guard let items = try? await AVURLAsset(url: url).load(.metadata) else { return true } + let keys: Set = [ + .commonKeyLocation, .commonKeyMake, .commonKeyModel, .commonKeySoftware, .commonKeyCreationDate, + ] + let words = ["location", "make", "model", "creationdate", "software"] + return items.contains { item in + if let key = item.commonKey, keys.contains(key) { return true } + let identifier = item.identifier?.rawValue.lowercased() ?? "" + return words.contains { identifier.contains($0) } + } + } + internal static func videoIncludesLocation(_ url: URL) async -> Bool { guard let items = try? await AVURLAsset(url: url).load(.metadata) else { return false } return items.contains { item in diff --git a/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift b/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift index 3eda2ade0b..b003639b05 100644 --- a/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift +++ b/apple/InlineKit/Tests/InlineKitTests/MediaSendPreparationTests.swift @@ -125,6 +125,28 @@ struct MediaSendPreparationTests { #expect(try MediaSendPreparation.anonymizedFileCopy(of: .data(Data("not an image".utf8))) == nil) } + @Test("a staged photo's format is read from its header, whatever its name") + func preparedFormat() throws { + let jpeg = try write(makeJPEG(width: 40, height: 30, orientation: 1, camera: false, gps: false), ext: "png") + let png = try write(makePNG(width: 40, height: 30, transparentCorner: true), ext: "body") + defer { + try? FileManager.default.removeItem(at: jpeg) + try? FileManager.default.removeItem(at: png) + } + #expect(MediaSendPreparation.preparedFormat(at: jpeg) == .jpeg) + #expect(MediaSendPreparation.preparedFormat(at: png) == .png) + let text = try write(Data("not an image".utf8), ext: "jpg") + defer { try? FileManager.default.removeItem(at: text) } + #expect(MediaSendPreparation.preparedFormat(at: text) == nil) + } + + @Test("a video that can't be read may carry anything, so its untouched file doesn't go") + func unreadableVideoMayCarryMetadata() async throws { + let notVideo = try write(Data("not a video".utf8), ext: "mov") + defer { try? FileManager.default.removeItem(at: notVideo) } + #expect(await OriginalMediaStore.videoMayCarryIdentifyingMetadata(notVideo)) + } + @Test("the source extension is read from the bytes") func fileExtension() throws { #expect(MediaSendPreparation.fileExtension(of: try makePNG(width: 10, height: 10, transparentCorner: false)) == "png") From 95e1bddb0347043ae8ee81b87be51b75d8377f08 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 09:38:30 +0000 Subject: [PATCH 14/14] macos: keep send as original's menu item in one menu, and prepare thin images with a file behind them - a row configured again built a new menu and inserted the same menu item, which appkit refuses while the item is still in the old menu. the item now leaves its old menu first. - an image too thin or tiny to show as a photo, with a file behind it, now goes through the draft's photo preparation, which sends it as a file without camera, place or time details instead of the untouched file. --- .../InlineMac/Views/Compose/ComposeAttachments.swift | 5 ++++- .../InlineMac/Views/Compose/GlassComposeAppKit.swift | 11 ++++------- .../InlineMac/Views/Compose/LegacyComposeAppKit.swift | 11 ++++------- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/apple/InlineMac/Views/Compose/ComposeAttachments.swift b/apple/InlineMac/Views/Compose/ComposeAttachments.swift index 5153af1885..25dfe34839 100644 --- a/apple/InlineMac/Views/Compose/ComposeAttachments.swift +++ b/apple/InlineMac/Views/Compose/ComposeAttachments.swift @@ -701,8 +701,11 @@ final class SendAsOriginalOption: NSObject, NSMenuItemValidation { separator.isHidden = true } - /// Puts the item first in `menu`. + /// Puts the item first in `menu`. A row configured again builds a new menu, and an item can + /// only be in one, so it leaves the old one first. func install(in menu: NSMenu) { + separator.menu?.removeItem(separator) + menuItem.menu?.removeItem(menuItem) menu.insertItem(separator, at: 0) menu.insertItem(menuItem, at: 0) } diff --git a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift index 4279bc8e1d..2f6caa1193 100644 --- a/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/GlassComposeAppKit.swift @@ -2481,13 +2481,10 @@ class GlassComposeAppKit: NSView { url.pathExtension.lowercased() == "png" ? ImageFormat.png : ImageFormat.jpeg } else { nil } - // Check aspect ratio - if shouldSendAsFile(image) { - if let url { - addFile(url) - return - } - + // Too thin or tiny to show as a photo. With a file behind it, the draft prepares it like any + // image, which sends it as a file without camera, place or time details; pixels alone carry + // none, so they go as a file here. + if shouldSendAsFile(image), url == nil { let tempDir = FileHelpers.getTrueTemporaryDirectory() let result = try? image.save( to: tempDir, diff --git a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift index bf7b58ac06..5fa9092401 100644 --- a/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift +++ b/apple/InlineMac/Views/Compose/LegacyComposeAppKit.swift @@ -1589,13 +1589,10 @@ class LegacyComposeAppKit: NSView { url.pathExtension.lowercased() == "png" ? ImageFormat.png : ImageFormat.jpeg } else { nil } - // Check aspect ratio - if shouldSendAsFile(image) { - if let url { - addFile(url) - return - } - + // Too thin or tiny to show as a photo. With a file behind it, the draft prepares it like any + // image, which sends it as a file without camera, place or time details; pixels alone carry + // none, so they go as a file here. + if shouldSendAsFile(image), url == nil { let tempDir = FileHelpers.getTrueTemporaryDirectory() let result = try? image.save( to: tempDir,