Skip to content

Commit 522e253

Browse files
fix(ios): resize oversized shared images (#103860)
* fix(ios): resize oversized shared images * fix(ios): satisfy SwiftFormat await rules * fix(ios): integrate share image processing * fix(ios): type share attachment failures --------- Co-authored-by: lin-hongkuan <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent 93e5b01 commit 522e253

9 files changed

Lines changed: 314 additions & 30 deletions

File tree

‎apps/ios/Resources/Localizable.xcstrings‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5713,6 +5713,142 @@
57135713
}
57145714
}
57155715
},
5716+
"The shared image could not be prepared.": {
5717+
"localizations": {
5718+
"en": {
5719+
"stringUnit": {
5720+
"state": "translated",
5721+
"value": "The shared image could not be prepared."
5722+
}
5723+
},
5724+
"zh-CN": {
5725+
"stringUnit": {
5726+
"state": "translated",
5727+
"value": "无法准备共享的图像。"
5728+
}
5729+
},
5730+
"zh-TW": {
5731+
"stringUnit": {
5732+
"state": "translated",
5733+
"value": "無法準備共享的影像。"
5734+
}
5735+
},
5736+
"pt-BR": {
5737+
"stringUnit": {
5738+
"state": "translated",
5739+
"value": "Não foi possível preparar a imagem compartilhada."
5740+
}
5741+
},
5742+
"de": {
5743+
"stringUnit": {
5744+
"state": "translated",
5745+
"value": "Das geteilte Bild konnte nicht vorbereitet werden."
5746+
}
5747+
},
5748+
"es": {
5749+
"stringUnit": {
5750+
"state": "translated",
5751+
"value": "No se pudo preparar la imagen compartida."
5752+
}
5753+
},
5754+
"ja-JP": {
5755+
"stringUnit": {
5756+
"state": "translated",
5757+
"value": "共有画像を準備できませんでした。"
5758+
}
5759+
},
5760+
"ko": {
5761+
"stringUnit": {
5762+
"state": "translated",
5763+
"value": "공유 이미지를 준비할 수 없습니다."
5764+
}
5765+
},
5766+
"fr": {
5767+
"stringUnit": {
5768+
"state": "translated",
5769+
"value": "Impossible de préparer l’image partagée."
5770+
}
5771+
},
5772+
"hi": {
5773+
"stringUnit": {
5774+
"state": "translated",
5775+
"value": "साझा की गई इमेज तैयार नहीं की जा सकी।"
5776+
}
5777+
},
5778+
"ar": {
5779+
"stringUnit": {
5780+
"state": "translated",
5781+
"value": "تعذّر تجهيز الصورة المشتركة."
5782+
}
5783+
},
5784+
"it": {
5785+
"stringUnit": {
5786+
"state": "translated",
5787+
"value": "Impossibile preparare l’immagine condivisa."
5788+
}
5789+
},
5790+
"tr": {
5791+
"stringUnit": {
5792+
"state": "translated",
5793+
"value": "Paylaşılan görüntü hazırlanamadı."
5794+
}
5795+
},
5796+
"uk": {
5797+
"stringUnit": {
5798+
"state": "translated",
5799+
"value": "Не вдалося підготувати зображення, яким поділилися."
5800+
}
5801+
},
5802+
"id": {
5803+
"stringUnit": {
5804+
"state": "translated",
5805+
"value": "Gambar yang dibagikan tidak dapat disiapkan."
5806+
}
5807+
},
5808+
"pl": {
5809+
"stringUnit": {
5810+
"state": "translated",
5811+
"value": "Nie udało się przygotować udostępnionego obrazu."
5812+
}
5813+
},
5814+
"th": {
5815+
"stringUnit": {
5816+
"state": "translated",
5817+
"value": "ไม่สามารถเตรียมรูปภาพที่แชร์ได้"
5818+
}
5819+
},
5820+
"vi": {
5821+
"stringUnit": {
5822+
"state": "translated",
5823+
"value": "Không thể chuẩn bị hình ảnh được chia sẻ."
5824+
}
5825+
},
5826+
"nl": {
5827+
"stringUnit": {
5828+
"state": "translated",
5829+
"value": "De gedeelde afbeelding kon niet worden voorbereid."
5830+
}
5831+
},
5832+
"fa": {
5833+
"stringUnit": {
5834+
"state": "translated",
5835+
"value": "آماده‌سازی تصویر هم‌رسانی‌شده ممکن نبود."
5836+
}
5837+
},
5838+
"ru": {
5839+
"stringUnit": {
5840+
"state": "translated",
5841+
"value": "Не удалось подготовить отправленное изображение."
5842+
}
5843+
},
5844+
"sv": {
5845+
"stringUnit": {
5846+
"state": "translated",
5847+
"value": "Det gick inte att förbereda den delade bilden."
5848+
}
5849+
}
5850+
}
5851+
},
57165852
"Trust and connect": {
57175853
"localizations": {
57185854
"en": {

‎apps/ios/ShareExtension/ShareComposeState.swift‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ enum ShareComposeStatus: Equatable {
77
case ready
88
case sending
99
case sent
10+
case blocked(String)
1011
case failed(String)
1112
}
1213

@@ -25,6 +26,8 @@ struct ShareComposeControlState: Equatable {
2526
Self(isSendEnabled: false, isCancelEnabled: true, isEditable: false)
2627
case .ready, .failed:
2728
Self(isSendEnabled: hasDraftText, isCancelEnabled: true, isEditable: true)
29+
case .blocked:
30+
Self(isSendEnabled: false, isCancelEnabled: true, isEditable: true)
2831
case .sending, .sent:
2932
Self(isSendEnabled: false, isCancelEnabled: false, isEditable: false)
3033
}

‎apps/ios/ShareExtension/ShareComposeView.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ final class ShareComposeView: UIView, UITextViewDelegate {
100100
text: NSLocalizedString("Sent to OpenClaw.", comment: "Share extension success status"),
101101
icon: (name: "checkmark.circle.fill", tint: .systemGreen),
102102
spinning: false)
103-
case let .failed(message):
103+
case let .blocked(message), let .failed(message):
104104
self.showFooter(
105105
text: message,
106106
icon: (name: "exclamationmark.triangle.fill", tint: .systemOrange),

‎apps/ios/ShareExtension/ShareViewController.swift‎

Lines changed: 44 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,15 @@ final class ShareViewController: UIViewController {
2222
private struct ExtractedShareContent {
2323
var payload: SharedContentPayload
2424
var attachments: [LoadedAttachment]
25+
var attachmentError: ShareImageProcessor.ProcessError?
2526
}
2627

2728
private let logger = Logger(subsystem: "ai.openclawfoundation.app", category: "ShareExtension")
2829
private let composeView = ShareComposeView()
2930
private var didPrepareDraft = false
3031
private var isSending = false
3132
private var pendingAttachments: [ShareAttachment] = []
33+
private var attachmentError: ShareImageProcessor.ProcessError?
3234

3335
override func loadView() {
3436
self.view = self.composeView
@@ -58,6 +60,7 @@ final class ShareViewController: UIViewController {
5860
let extracted = await self.extractSharedContent()
5961
let payload = extracted.payload
6062
self.pendingAttachments = extracted.attachments.map(\.payload)
63+
self.attachmentError = extracted.attachmentError
6164
self.logger.info("share payload trace=\(traceId, privacy: .public)")
6265
self.logger.info(
6366
"share payload title=\(payload.title?.count ?? 0) text=\(payload.text?.count ?? 0)")
@@ -66,11 +69,15 @@ final class ShareViewController: UIViewController {
6669
let message = ShareDraftComposer.compose(from: payload)
6770
self.composeView.setDraft(message)
6871
self.composeView.setAttachmentPreviews(extracted.attachments.map(\.preview))
69-
self.composeView.apply(.ready)
7072
self.composeView.focusDraft()
71-
if message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
73+
if let attachmentError = extracted.attachmentError {
74+
ShareGatewayRelaySettings.saveLastEvent("Share blocked: image processing failed.")
75+
self.composeView.apply(.blocked(self.imageProcessingErrorMessage(attachmentError)))
76+
} else if message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
77+
self.composeView.apply(.ready)
7278
ShareGatewayRelaySettings.saveLastEvent("Share ready: waiting for message input.")
7379
} else {
80+
self.composeView.apply(.ready)
7481
ShareGatewayRelaySettings.saveLastEvent("Share ready: draft prepared.")
7582
}
7683
}
@@ -81,6 +88,10 @@ final class ShareViewController: UIViewController {
8188
}
8289

8390
private func sendCurrentDraft() async {
91+
if let attachmentError = self.attachmentError {
92+
self.composeView.apply(.blocked(self.imageProcessingErrorMessage(attachmentError)))
93+
return
94+
}
8495
let trimmed = self.composeView.draftText.trimmingCharacters(in: .whitespacesAndNewlines)
8596
guard !trimmed.isEmpty else {
8697
ShareGatewayRelaySettings.saveLastEvent("Share blocked: message is empty.")
@@ -270,14 +281,16 @@ final class ShareViewController: UIViewController {
270281
guard let items = self.extensionContext?.inputItems as? [NSExtensionItem] else {
271282
return ExtractedShareContent(
272283
payload: SharedContentPayload(title: nil, url: nil, text: nil),
273-
attachments: [])
284+
attachments: [],
285+
attachmentError: nil)
274286
}
275287

276288
var title: String?
277289
var sharedURL: URL?
278290
var sharedText: String?
279291
var attributedContentText: String?
280292
var attachments: [LoadedAttachment] = []
293+
var attachmentError: ShareImageProcessor.ProcessError?
281294
let maxImageAttachments = 3
282295

283296
for item in items {
@@ -297,11 +310,19 @@ final class ShareViewController: UIViewController {
297310
sharedText = await self.loadText(from: provider)
298311
}
299312

300-
if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier),
301-
attachments.count < maxImageAttachments,
302-
let attachment = await self.loadImageAttachment(from: provider, index: attachments.count)
303-
{
304-
attachments.append(attachment)
313+
if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) {
314+
if attachments.count < maxImageAttachments, attachmentError == nil {
315+
do {
316+
let attachment = try await self.loadImageAttachment(
317+
from: provider,
318+
index: attachments.count)
319+
attachments.append(attachment)
320+
} catch let error as ShareImageProcessor.ProcessError {
321+
attachmentError = error
322+
} catch {
323+
attachmentError = .encodeFailed
324+
}
325+
}
305326
}
306327
}
307328
}
@@ -314,20 +335,21 @@ final class ShareViewController: UIViewController {
314335
sharedURL: sharedURL)
315336
return ExtractedShareContent(
316337
payload: SharedContentPayload(title: title ?? supplementalTitle, url: sharedURL, text: sharedText),
317-
attachments: attachments)
338+
attachments: attachments,
339+
attachmentError: attachmentError)
318340
}
319341

320-
private func loadImageAttachment(from provider: NSItemProvider, index: Int) async -> LoadedAttachment? {
342+
private func loadImageAttachment(from provider: NSItemProvider, index: Int) async throws -> LoadedAttachment {
321343
let imageUTI = self.preferredImageTypeIdentifier(from: provider) ?? UTType.image.identifier
322344
guard let rawData = await self.loadDataValue(from: provider, typeIdentifier: imageUTI) else {
323-
return nil
345+
throw ShareImageProcessor.ProcessError.invalidImage
324346
}
325347

326-
let maxBytes = 5_000_000
327-
guard let image = UIImage(data: rawData),
328-
let data = self.normalizedJPEGData(from: image, maxBytes: maxBytes)
329-
else {
330-
return nil
348+
let data = try await Task.detached(priority: .userInitiated) {
349+
try ShareImageProcessor.processForUpload(data: rawData)
350+
}.value
351+
guard let image = UIImage(data: data) else {
352+
throw ShareImageProcessor.ProcessError.invalidImage
331353
}
332354

333355
return await LoadedAttachment(
@@ -339,6 +361,12 @@ final class ShareViewController: UIViewController {
339361
preview: self.boundedPreview(from: image))
340362
}
341363

364+
private func imageProcessingErrorMessage(_: ShareImageProcessor.ProcessError) -> String {
365+
NSLocalizedString(
366+
"The shared image could not be prepared.",
367+
comment: "Share extension image processing failure")
368+
}
369+
342370
/// Previews are retained for the sheet's lifetime; keep them bounded so
343371
/// three full-resolution photos cannot blow the extension memory cap.
344372
/// Never falls back to the full-size image.
@@ -369,19 +397,6 @@ final class ShareViewController: UIViewController {
369397
return nil
370398
}
371399

372-
private func normalizedJPEGData(from image: UIImage, maxBytes: Int) -> Data? {
373-
var quality: CGFloat = 0.9
374-
while quality >= 0.4 {
375-
if let data = image.jpegData(compressionQuality: quality), data.count <= maxBytes {
376-
return data
377-
}
378-
quality -= 0.1
379-
}
380-
guard let fallback = image.jpegData(compressionQuality: 0.35) else { return nil }
381-
if fallback.count <= maxBytes { return fallback }
382-
return nil
383-
}
384-
385400
private func loadURL(from provider: NSItemProvider) async -> URL? {
386401
if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {
387402
if let url = await self.loadURLValue(

‎apps/ios/Tests/Logic/ShareComposeStateTests.swift‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,9 @@ struct ShareComposeStateTests {
2525
let controls = ShareComposeControlState.resolve(status: .failed("offline"), hasDraftText: true)
2626
#expect(controls == ShareComposeControlState(isSendEnabled: true, isCancelEnabled: true, isEditable: true))
2727
}
28+
29+
@Test func `keeps send blocked when an attachment cannot be prepared`() {
30+
let controls = ShareComposeControlState.resolve(status: .blocked("invalid image"), hasDraftText: true)
31+
#expect(controls == ShareComposeControlState(isSendEnabled: false, isCancelEnabled: true, isEditable: true))
32+
}
2833
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import Foundation
2+
3+
/// Share Extension image policy built on the shared, orientation-normalizing JPEG transcoder.
4+
public enum ShareImageProcessor {
5+
public static let maxLongEdgePx = 2560
6+
public static let jpegQuality = 0.9
7+
public static let maxPayloadBytes = 5_000_000
8+
9+
public enum ProcessError: Error, Equatable, Sendable {
10+
case invalidImage
11+
case encodeFailed
12+
case sizeLimitExceeded
13+
}
14+
15+
public static func processForUpload(data: Data) throws -> Data {
16+
do {
17+
return try JPEGTranscoder.transcodeToJPEG(
18+
imageData: data,
19+
maxLongEdgePx: self.maxLongEdgePx,
20+
quality: self.jpegQuality,
21+
maxBytes: self.maxPayloadBytes).data
22+
} catch JPEGTranscodeError.decodeFailed, JPEGTranscodeError.propertiesMissing {
23+
throw ProcessError.invalidImage
24+
} catch JPEGTranscodeError.sizeLimitExceeded {
25+
throw ProcessError.sizeLimitExceeded
26+
} catch {
27+
throw ProcessError.encodeFailed
28+
}
29+
}
30+
}

‎apps/shared/OpenClawKit/Tests/OpenClawKitTests/JPEGTranscoderTests.swift‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,4 +126,22 @@ import UniformTypeIdentifiers
126126
maxBytes: 180_000)
127127
#expect(out.data.count <= 180_000)
128128
}
129+
130+
@Test func explicitlyFailsWhenSizeLimitCannotBeMet() throws {
131+
let input = try makeSolidJPEG(width: 800, height: 600)
132+
133+
do {
134+
_ = try JPEGTranscoder.transcodeToJPEG(
135+
imageData: input,
136+
maxWidthPx: 800,
137+
quality: 0.9,
138+
maxBytes: 1)
139+
Issue.record("Expected a size-limit error")
140+
} catch JPEGTranscodeError.sizeLimitExceeded(let maxBytes, let actualBytes) {
141+
#expect(maxBytes == 1)
142+
#expect(actualBytes > maxBytes)
143+
} catch {
144+
Issue.record("Unexpected error: \(error)")
145+
}
146+
}
129147
}

0 commit comments

Comments
 (0)