From b5ed89275712923b665e9f34a3ec630825eeda8a Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:19:41 -0800 Subject: [PATCH 01/13] feat: send MCOimg drawings in chat - A channel send uses GROUP_DATA. `im3:` text is rewritten to `im4:` before the row is saved. - Direct messages send v3 text. - The input bar can attach a drawing. The bubble draws a decoded image, and a bad payload shows the error text. --- .gitignore | 1 + MC1/Resources/Generated/L10n.swift | 36 + .../Localization/de.lproj/Chats.strings | 44 + .../Localization/en.lproj/Chats.strings | 44 + .../Localization/es.lproj/Chats.strings | 44 + .../Localization/fr.lproj/Chats.strings | 44 + .../Localization/it.lproj/Chats.strings | 44 + .../Localization/ko.lproj/Chats.strings | 44 + .../Localization/nl.lproj/Chats.strings | 44 + .../Localization/pl.lproj/Chats.strings | 44 + .../Localization/pt.lproj/Chats.strings | 44 + .../Localization/ru.lproj/Chats.strings | 44 + .../Localization/uk.lproj/Chats.strings | 44 + .../Localization/zh-Hans.lproj/Chats.strings | 44 + .../Chats/ChatConversationInputBar.swift | 109 +- .../Components/BubbleFragmentStack.swift | 4 + MC1/Views/Chats/Components/ChatInputBar.swift | 14 +- .../Chats/Components/ChatShareMenu.swift | 16 +- .../Chats/Components/FragmentLayout.swift | 24 +- .../Components/UnifiedMessageBubble.swift | 16 +- MC1/Views/Chats/MCOimg/MCOImageGeometry.swift | 53 + .../Chats/MCOimg/MCOImageRenderer+Text.swift | 53 + MC1/Views/Chats/MCOimg/MCOImageRenderer.swift | 112 + MC1/Views/Chats/MCOimg/MCOImageView.swift | 42 + MC1/Views/Chats/MCOimg/PixelPaintDraft.swift | 52 + MC1/Views/Chats/MCOimg/PixelPaintEditor.swift | 107 + .../Reactions/MessageActionAvailability.swift | 2 + .../Chats/Reactions/MessageActionsSheet.swift | 4 +- .../ChatMessageBakeState+ItemBuild.swift | 6 +- .../ViewModel/ChatTimelinePopulator.swift | 7 +- .../ViewModel/ChatViewModel+Channels.swift | 9 + .../ChatViewModel+MessageActions.swift | 21 +- .../RemoteNodes/Rooms/RoomMessageBubble.swift | 6 +- MC1Services/Package.swift | 3 +- .../Models/ChannelMessageEnvelope.swift | 17 +- .../Models/Rendering/MessageFragment.swift | 1 + .../MessagePollingServiceProtocol.swift | 3 + .../Persistence/MessagePersisting.swift | 31 + .../ChatSendQueueService+ChannelDrain.swift | 6 +- .../Services/ChatSendQueueService.swift | 6 +- .../Services/FirmwareDeviceErrorCode.swift | 3 + .../Services/MessageFragmentBuilder.swift | 12 +- .../Services/MessageLanguageDetector.swift | 1 + .../Services/MessagePollingService.swift | 43 +- .../MessageService+ChannelScope.swift | 20 + .../Services/MessageService+MCOImage.swift | 43 + .../Services/MessageService+SendChannel.swift | 16 +- .../Services/MessageService+SendDM.swift | 8 +- .../Services/PersistenceStore+Messages.swift | 54 + .../Services/ReactionService.swift | 26 +- .../Sync/SyncCoordinator+HandlerHelpers.swift | 9 +- .../SyncCoordinator+MessageHandlers.swift | 67 +- .../SyncCoordinator+ReactionHandlers.swift | 13 + .../MCOImageDatagramDuplicates.swift | 32 + .../Utilities/MCOImageTransport.swift | 50 + .../Utilities/MCOimg/MCOImageBase91.swift | 59 + .../Utilities/MCOimg/MCOImageBitReader.swift | 81 + .../Utilities/MCOimg/MCOImageBitWriter.swift | 44 + .../Utilities/MCOimg/MCOImageCodec.swift | 93 + .../Utilities/MCOimg/MCOImageCodecError.swift | 4 + .../Utilities/MCOimg/MCOImageContent.swift | 9 + .../Utilities/MCOimg/MCOImageFigure.swift | 50 + .../MCOimg/MCOImagePalette+Tables.swift | 193 + .../Utilities/MCOimg/MCOImagePalette.swift | 47 + .../Utilities/MCOimg/MCOImageRaster.swift | 17 + .../MCOimg/MCOImageV3Codec+Bitplanes.swift | 54 + .../MCOimg/MCOImageV3Codec+Blocks.swift | 148 + .../MCOimg/MCOImageV3Codec+CompactRows.swift | 81 + .../MCOimg/MCOImageV3Codec+Containers.swift | 109 + .../MCOimg/MCOImageV3Codec+Encode.swift | 160 + .../MCOimg/MCOImageV3Codec+LocalPalette.swift | 102 + .../MCOimg/MCOImageV3Codec+Rows.swift | 108 + .../Utilities/MCOimg/MCOImageV3Codec.swift | 135 + .../MCOimg/MCOImageV4BitReader.swift | 65 + .../MCOimg/MCOImageV4Codec+Raster.swift | 52 + .../Utilities/MCOimg/MCOImageV4Codec.swift | 9 + .../Utilities/MCOimg/MCOImageV4Document.swift | 9 + .../MCOimg/MCOImageV4Parser+Extended.swift | 135 + .../MCOimg/MCOImageV4Parser+Figures.swift | 82 + .../MCOimg/MCOImageV4Parser+Paths.swift | 79 + .../MCOimg/MCOImageV4Parser+Validation.swift | 40 + .../Utilities/MCOimg/MCOImageV4Parser.swift | 187 + .../Utilities/MCOimg/MCOImageV4Point.swift | 13 + .../Utilities/MCOimg/MCOImageV4Style.swift | 11 + .../Utilities/MCOimg/MCOImageWireBudget.swift | 3 + .../Utilities/MCOimg/MCOTextBitReader.swift | 35 + .../Utilities/MCOimg/MCOTextCodec.swift | 8 + .../Utilities/MCOimg/MCOTextDecoder.swift | 159 + .../Utilities/MCOimg/MCOTextModel.swift | 10 + .../Utilities/MCOimg/MCOTextModels+BE.swift | 37 + .../Utilities/MCOimg/MCOTextModels+DE.swift | 37 + .../Utilities/MCOimg/MCOTextModels+EN.swift | 35 + .../Utilities/MCOimg/MCOTextModels+FR.swift | 44 + .../Utilities/MCOimg/MCOTextModels+IT.swift | 39 + .../Utilities/MCOimg/MCOTextModels+RU.swift | 38 + .../Utilities/MCOimg/MCOTextModels+UK.swift | 38 + .../Utilities/MCOimg/MCOTextModels.swift | 10 + .../Fixtures/MCOTextFixtures.json | 108 + .../Fixtures/MCOimgV4Fixtures.json | 4083 +++++ .../MCOImageBinarySendTests.swift | 227 + .../MCOImageReceiveIntegrationTests.swift | 83 + .../MCOImageSendIntegrationTests.swift | 64 + .../MCOImageTransportTests.swift | 156 + .../MCOImageV3CodecTests.swift | 117 + .../Mocks/MockMeshCoreSession.swift | 62 + .../Mocks/MockMessagePollingService.swift | 7 + .../Mocks/MockPersistenceStore.swift | 6 + .../PersistenceStoreTests.swift | 98 + .../Services/ChatSendQueueReactionTests.swift | 25 + .../Services/ReactionServiceTests.swift | 57 + ...CoordinatorChannelImageReactionTests.swift | 190 + .../SyncCoordinatorTests.swift | 2 + .../Utilities/MCOImageV4CodecTests.swift | 168 + .../Utilities/MCOTextCodecTests.swift | 42 + .../ConnectionStatusLifecycleTests.swift | 1 + .../Views/Chats/ChatSendAdmissionTests.swift | 23 + .../Components/FragmentLayoutTests.swift | 8 +- .../RoomMessageBubbleA11yLabelTests.swift | 10 + .../Views/Chats/MCOImageGeometryTests.swift | 48 + .../Views/Chats/MCOImageMessageTests.swift | 39 + .../MessageActionAvailabilityTests.swift | 24 +- .../Models/MessageFragmentBuilderTests.swift | 23 +- .../Views/Chats/PixelPaintDraftTests.swift | 46 + .../Chats/PixelPaintPresentationTests.swift | 163 + .../Protocols/MessagingSessionOps.swift | 18 + .../MeshCoreSession+ChannelSending.swift | 22 +- .../ChannelSendSerializationTests.swift | 39 +- scripts/mcoimg/README.md | 208 + scripts/mcoimg/export_text_reference.dart | 75 + scripts/mcoimg/export_v4_reference.py | 63 + scripts/mcoimg/fixtures/v3-swift-encoded.json | 2073 +++ .../mcoimg/fixtures/v3-upstream-decoder.json | 847 + scripts/mcoimg/fixtures/v4-swift-raster.json | 13197 ++++++++++++++++ scripts/mcoimg/generate_text_tables.py | 61 + scripts/mcoimg/measure_wire_cost_test.dart | 50 + scripts/mcoimg/verify-v3.dart | 35 + scripts/mcoimg/verify-v3.swift | 68 + scripts/mcoimg/verify-v4-raster.dart | 48 + scripts/mcoimg/verify-v4-raster.swift | 38 + 139 files changed, 26961 insertions(+), 116 deletions(-) create mode 100644 MC1/Views/Chats/MCOimg/MCOImageGeometry.swift create mode 100644 MC1/Views/Chats/MCOimg/MCOImageRenderer+Text.swift create mode 100644 MC1/Views/Chats/MCOimg/MCOImageRenderer.swift create mode 100644 MC1/Views/Chats/MCOimg/MCOImageView.swift create mode 100644 MC1/Views/Chats/MCOimg/PixelPaintDraft.swift create mode 100644 MC1/Views/Chats/MCOimg/PixelPaintEditor.swift create mode 100644 MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOImageDatagramDuplicates.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodecError.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageContent.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageFigure.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette+Tables.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageRaster.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Blocks.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+CompactRows.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Containers.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Encode.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Rows.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Codec+Raster.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Codec.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Document.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Extended.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Figures.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Paths.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Validation.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Point.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Style.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageWireBudget.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextCodec.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModel.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModels+BE.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModels+DE.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModels+EN.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModels+FR.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModels+IT.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModels+RU.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModels+UK.swift create mode 100644 MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextModels.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Fixtures/MCOTextFixtures.json create mode 100644 MC1Services/Tests/MC1ServicesTests/Fixtures/MCOimgV4Fixtures.json create mode 100644 MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/MCOImageV3CodecTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelImageReactionTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Utilities/MCOImageV4CodecTests.swift create mode 100644 MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift create mode 100644 MC1Tests/Views/Chats/MCOImageGeometryTests.swift create mode 100644 MC1Tests/Views/Chats/MCOImageMessageTests.swift create mode 100644 MC1Tests/Views/Chats/PixelPaintDraftTests.swift create mode 100644 MC1Tests/Views/Chats/PixelPaintPresentationTests.swift create mode 100644 scripts/mcoimg/README.md create mode 100644 scripts/mcoimg/export_text_reference.dart create mode 100644 scripts/mcoimg/export_v4_reference.py create mode 100644 scripts/mcoimg/fixtures/v3-swift-encoded.json create mode 100644 scripts/mcoimg/fixtures/v3-upstream-decoder.json create mode 100644 scripts/mcoimg/fixtures/v4-swift-raster.json create mode 100644 scripts/mcoimg/generate_text_tables.py create mode 100644 scripts/mcoimg/measure_wire_cost_test.dart create mode 100644 scripts/mcoimg/verify-v3.dart create mode 100644 scripts/mcoimg/verify-v3.swift create mode 100644 scripts/mcoimg/verify-v4-raster.dart create mode 100644 scripts/mcoimg/verify-v4-raster.swift diff --git a/.gitignore b/.gitignore index 8ce74d4cb0..5857f8cae5 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ tmp/ scripts/ !/scripts/ /scripts/* +!/scripts/mcoimg/ !/scripts/test-app-ci.py !/scripts/tests/ /scripts/tests/* diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 4533b784c3..d41b921b99 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -558,6 +558,42 @@ public enum L10n { /// Location: MalwareWarningCard.swift - Warning title for flagged domains public static let title = L10n.tr("Chats", "chats.malwareWarning.title", fallback: "Link flagged as suspicious") } + public enum Mcoimg { + /// VoiceOver name for the pixel drawing canvas + public static let canvas = L10n.tr("Chats", "chats.mcoimg.canvas", fallback: "Pixel canvas") + /// Erases every pixel in the editor + public static let clear = L10n.tr("Chats", "chats.mcoimg.clear", fallback: "Clear Drawing") + /// VoiceOver name for a palette swatch; the argument is 1-based + public static func color(_ p1: Int) -> String { + return L10n.tr("Chats", "chats.mcoimg.color", p1, fallback: "Color %d") + } + /// Placeholder when an MCOimg payload cannot be decoded + public static let damaged = L10n.tr("Chats", "chats.mcoimg.damaged", fallback: "Damaged image") + /// Status shown when a pixel drawing is staged for Send + public static let draft = L10n.tr("Chats", "chats.mcoimg.draft", fallback: "Drawing ready to send") + /// Reopens the editor for a staged pixel drawing + public static let edit = L10n.tr("Chats", "chats.mcoimg.edit", fallback: "Edit Drawing") + /// Progress label while a pixel drawing is encoded + public static let encoding = L10n.tr("Chats", "chats.mcoimg.encoding", fallback: "Encoding Drawing") + /// Error when a pixel drawing cannot be encoded + public static let encodingFailed = L10n.tr("Chats", "chats.mcoimg.encodingFailed", fallback: "Unable to encode the drawing.") + /// VoiceOver name for a rendered MCOimg + public static let image = L10n.tr("Chats", "chats.mcoimg.image", fallback: "MCOimg image") + /// VoiceOver name for one cell; arguments are 1-based column and row + public static func pixel(_ p1: Int, _ p2: Int) -> String { + return L10n.tr("Chats", "chats.mcoimg.pixel", p1, p2, fallback: "Pixel %d, %d") + } + /// Removes a staged pixel drawing from the composer + public static let remove = L10n.tr("Chats", "chats.mcoimg.remove", fallback: "Remove Drawing") + /// Editor title and the compose-menu action for a pixel drawing + public static let title = L10n.tr("Chats", "chats.mcoimg.title", fallback: "Pixel Paint") + /// Error when a pixel drawing exceeds the conversation limit; arguments are size then limit + public static func tooLarge(_ p1: Int, _ p2: Int) -> String { + return L10n.tr("Chats", "chats.mcoimg.tooLarge", p1, p2, fallback: "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again.") + } + /// Placeholder when an MCOimg version cannot be shown + public static let unsupported = L10n.tr("Chats", "chats.mcoimg.unsupported", fallback: "Unsupported image format") + } public enum Mention { public enum Accessibility { /// Location: MentionSuggestionRow.swift - Accessibility hint for channel sender mention diff --git a/MC1/Resources/Localization/de.lproj/Chats.strings b/MC1/Resources/Localization/de.lproj/Chats.strings index cdedff3790..351e67ccdf 100644 --- a/MC1/Resources/Localization/de.lproj/Chats.strings +++ b/MC1/Resources/Localization/de.lproj/Chats.strings @@ -1056,6 +1056,50 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Verwalte deine Verbindung, sende Ankündigungen und prüfe den Akku. Das Funkgerät bleibt auch nach erzwungenem Beenden verbunden. Tippe auf „Trennen“, um die Verbindung zu beenden."; +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Bild"; diff --git a/MC1/Resources/Localization/en.lproj/Chats.strings b/MC1/Resources/Localization/en.lproj/Chats.strings index c0c37d9f47..da28c00261 100644 --- a/MC1/Resources/Localization/en.lproj/Chats.strings +++ b/MC1/Resources/Localization/en.lproj/Chats.strings @@ -1066,6 +1066,50 @@ /* Location: InlineImageFragmentView.swift - VoiceOver identity for a failed inline image */ "chats.inlineImage.failedLabel" = "Image failed to load"; +// MARK: - MCOimg + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + // MARK: - Image Viewer /* Location: FullScreenImageViewer.swift - Close button label */ diff --git a/MC1/Resources/Localization/es.lproj/Chats.strings b/MC1/Resources/Localization/es.lproj/Chats.strings index a5aaea9db5..732fa5eed1 100644 --- a/MC1/Resources/Localization/es.lproj/Chats.strings +++ b/MC1/Resources/Localization/es.lproj/Chats.strings @@ -1056,6 +1056,50 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Gestiona tu conexión, envía anuncios y revisa la batería. La radio permanece conectada incluso tras forzar el cierre. Toca Desconectar para cerrar el enlace."; +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Imagen"; diff --git a/MC1/Resources/Localization/fr.lproj/Chats.strings b/MC1/Resources/Localization/fr.lproj/Chats.strings index 90ef8ad719..a25cf028ad 100644 --- a/MC1/Resources/Localization/fr.lproj/Chats.strings +++ b/MC1/Resources/Localization/fr.lproj/Chats.strings @@ -1056,6 +1056,50 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Gérez votre connexion, envoyez des annonces et vérifiez la batterie. La radio reste connectée même après une fermeture forcée. Appuyez sur Déconnecter pour couper le lien."; +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Image"; diff --git a/MC1/Resources/Localization/it.lproj/Chats.strings b/MC1/Resources/Localization/it.lproj/Chats.strings index 0e2d265262..a3d1d11bc3 100644 --- a/MC1/Resources/Localization/it.lproj/Chats.strings +++ b/MC1/Resources/Localization/it.lproj/Chats.strings @@ -1049,6 +1049,50 @@ // MARK: - Inline Image +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Immagine"; diff --git a/MC1/Resources/Localization/ko.lproj/Chats.strings b/MC1/Resources/Localization/ko.lproj/Chats.strings index 0e6dab0dfa..ee67a6ab47 100644 --- a/MC1/Resources/Localization/ko.lproj/Chats.strings +++ b/MC1/Resources/Localization/ko.lproj/Chats.strings @@ -1049,6 +1049,50 @@ // MARK: - Inline Image +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "이미지"; diff --git a/MC1/Resources/Localization/nl.lproj/Chats.strings b/MC1/Resources/Localization/nl.lproj/Chats.strings index 0d024d1a99..4f8182715d 100644 --- a/MC1/Resources/Localization/nl.lproj/Chats.strings +++ b/MC1/Resources/Localization/nl.lproj/Chats.strings @@ -1056,6 +1056,50 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Beheer je verbinding, verstuur advertenties en controleer de batterij. De radio blijft verbonden, zelfs na een geforceerde afsluiting. Tik op Verbreken om de verbinding uit te schakelen."; +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Afbeelding"; diff --git a/MC1/Resources/Localization/pl.lproj/Chats.strings b/MC1/Resources/Localization/pl.lproj/Chats.strings index 06d6dc8ad9..364abac136 100644 --- a/MC1/Resources/Localization/pl.lproj/Chats.strings +++ b/MC1/Resources/Localization/pl.lproj/Chats.strings @@ -1048,6 +1048,50 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Zarządzaj połączeniem, wysyłaj ogłoszenia i sprawdzaj baterię. Radio pozostaje połączone nawet po wymuszonym zamknięciu aplikacji. Dotknij Rozłącz, aby wyłączyć łącze."; +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Obraz"; diff --git a/MC1/Resources/Localization/pt.lproj/Chats.strings b/MC1/Resources/Localization/pt.lproj/Chats.strings index 5fe68f006e..584101b785 100644 --- a/MC1/Resources/Localization/pt.lproj/Chats.strings +++ b/MC1/Resources/Localization/pt.lproj/Chats.strings @@ -1049,6 +1049,50 @@ // MARK: - Inline Image +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Imagem"; diff --git a/MC1/Resources/Localization/ru.lproj/Chats.strings b/MC1/Resources/Localization/ru.lproj/Chats.strings index 24189747df..4f9e66c7b2 100644 --- a/MC1/Resources/Localization/ru.lproj/Chats.strings +++ b/MC1/Resources/Localization/ru.lproj/Chats.strings @@ -1047,6 +1047,50 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Управляйте подключением, отправляйте объявления и проверяйте заряд батареи. Радио остаётся подключённым даже после принудительного закрытия приложения. Нажмите «Отключить», чтобы разорвать связь."; +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Изображение"; diff --git a/MC1/Resources/Localization/uk.lproj/Chats.strings b/MC1/Resources/Localization/uk.lproj/Chats.strings index 522fcdb25f..d137c22872 100644 --- a/MC1/Resources/Localization/uk.lproj/Chats.strings +++ b/MC1/Resources/Localization/uk.lproj/Chats.strings @@ -1047,6 +1047,50 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Керуйте з'єднанням, надсилайте оголошення та перевіряйте заряд. Радіо залишається підключеним навіть після примусового закриття застосунку. Натисніть «Відключити», щоб розірвати зв'язок."; +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Зображення"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings index ce4b3605fd..2a2fb460b6 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings @@ -1113,6 +1113,50 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "管理您的连接、发送广播并查看电池电量。即使在强制退出应用后,无线电仍保持连接。点击断开连接以关闭链路。"; +// MARK: - MCOimg + +/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel Paint"; + +/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Unsupported image format"; + +/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Damaged image"; + +/* TODO: translate - VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg image"; + +/* TODO: translate - Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Clear Drawing"; + +/* TODO: translate - Removes a staged pixel drawing from the composer */ +"chats.mcoimg.remove" = "Remove Drawing"; + +/* TODO: translate - Reopens the editor for a staged pixel drawing */ +"chats.mcoimg.edit" = "Edit Drawing"; + +/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Color %d"; + +/* TODO: translate - VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel canvas"; + +/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Pixel %d, %d"; + +/* TODO: translate - Status shown when a pixel drawing is staged for Send */ +"chats.mcoimg.draft" = "Drawing ready to send"; + +/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; + +/* TODO: translate - Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; + +/* TODO: translate - Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encoding Drawing"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "图片"; diff --git a/MC1/Views/Chats/ChatConversationInputBar.swift b/MC1/Views/Chats/ChatConversationInputBar.swift index 581861979e..c1cbf2a244 100644 --- a/MC1/Views/Chats/ChatConversationInputBar.swift +++ b/MC1/Views/Chats/ChatConversationInputBar.swift @@ -10,7 +10,31 @@ struct ChatConversationInputBar: View { let onSend: (String) async -> Bool let onWillSend: () -> Void + @Environment(\.appState) private var appState + @State private var drawing = PixelPaintDraft() + @State private var isShowingPainter = false + @State private var submissionTask: Task? + private static let previewSide: CGFloat = 56 + var body: some View { + VStack(spacing: 0) { + if drawing.isStaged { stagedDrawing } + inputBar + } + .fullScreenCover(isPresented: $isShowingPainter) { + PixelPaintEditor(draft: drawing) + } + .errorAlert($drawing.errorMessage) + .onChange(of: conversationType.coordinatorID) { + submissionTask?.cancel() + drawing.remove() + isShowingPainter = false + } + .onDisappear { submissionTask?.cancel() } + } + + @ViewBuilder + private var inputBar: some View { switch conversationType { case .dm: ChatInputBar( @@ -19,8 +43,11 @@ struct ChatConversationInputBar: View { placeholder: L10n.Chats.Chats.Input.Placeholder.directMessage, maxBytes: ProtocolLimits.maxDirectMessageLength, isEncrypted: true, - leading: { ChatShareMenu(onInsert: insertShared) }, - onSend: send + leading: { ChatShareMenu(onInsert: insertShared, onPaint: openPainter) }, + onSend: send, + hasAttachment: drawing.isStaged, + isSubmittingAttachment: drawing.isSubmitting, + onSendAttachment: sendDrawing ) case let .channel(channel): @@ -35,12 +62,77 @@ struct ChatConversationInputBar: View { : L10n.Chats.Chats.Channel.typePrivate, maxBytes: maxBytes, isEncrypted: channel.isEncryptedChannel, - leading: { ChatShareMenu(onInsert: insertShared) }, - onSend: send + leading: { ChatShareMenu(onInsert: insertShared, onPaint: openPainter) }, + onSend: send, + hasAttachment: drawing.isStaged, + isSubmittingAttachment: drawing.isSubmitting, + onSendAttachment: sendDrawing ) } } + private var stagedDrawing: some View { + HStack { + Button(action: openPainter) { + MCOImageRenderer(content: .raster(drawing.image)) + .frame(width: Self.previewSide, height: Self.previewSide) + } + .accessibilityLabel(L10n.Chats.Chats.Mcoimg.edit) + .accessibilityIdentifier("stagedPixelDrawing") + Text(L10n.Chats.Chats.Mcoimg.draft).font(.caption) + Spacer() + if drawing.isSubmitting { + ProgressView().accessibilityLabel(L10n.Chats.Chats.Mcoimg.encoding) + } + Button(L10n.Chats.Chats.Mcoimg.remove, systemImage: "xmark.circle") { drawing.remove() } + .labelStyle(.iconOnly) + } + .disabled(drawing.isSubmitting) + .padding(.horizontal) + } + + private func openPainter() { + guard !drawing.isSubmitting else { return } + ChatKeyboardLift.resignFirstResponder() + isShowingPainter = true + } + + private func sendDrawing() { + guard drawing.isStaged, !drawing.isSubmitting, appState.connectionState == .ready else { return } + let snapshot = drawing.image + let isChannel: Bool = if case .channel = conversationType { true } else { false } + drawing.isSubmitting = true + drawing.errorMessage = nil + submissionTask = Task { + defer { drawing.isSubmitting = false } + do { + let text = try await encodeDrawing(snapshot, channel: isChannel) + try Task.checkCancellation() + guard appState.connectionState == .ready, + appState.connectedDevice?.radioID == conversationType.radioID else { + drawing.errorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + return + } + let bytes = if isChannel { + try MCOImageTransport.encode(text: text, senderName: appState.connectedDevice?.nodeName ?? "").count + } else { + text.utf8.count + } + let limit = isChannel ? MCOImageWireBudget.maximumChannelDataBytes : ProtocolLimits.maxDirectMessageLength + guard bytes <= limit else { + drawing.errorMessage = L10n.Chats.Chats.Mcoimg.tooLarge(bytes, limit) + return + } + onWillSend() + if await onSend(text) { drawing.remove() } + } catch is CancellationError { + return + } catch { + drawing.errorMessage = L10n.Chats.Chats.Mcoimg.encodingFailed + } + } + } + private func send(_ text: String) { let draft = $composingText onWillSend() @@ -60,3 +152,12 @@ struct ChatConversationInputBar: View { focusRequest += 1 } } + +@concurrent +private func encodeDrawing(_ image: MCOImageRaster, channel: Bool) async throws -> String { + let body = try MCOImageV3Codec.encode(image, nonce: UInt8.random(in: .min ... .max)) + let payload = channel + ? try Data([MCOImageCodec.v4Subtype]) + MCOImageV4Codec.wrappingV3Body(body) + : Data([MCOImageCodec.v3Subtype]) + body + return try MCOImageCodec.text(fromAppPayload: payload) +} diff --git a/MC1/Views/Chats/Components/BubbleFragmentStack.swift b/MC1/Views/Chats/Components/BubbleFragmentStack.swift index 2f3d3d9206..8c5e33e4d7 100644 --- a/MC1/Views/Chats/Components/BubbleFragmentStack.swift +++ b/MC1/Views/Chats/Components/BubbleFragmentStack.swift @@ -86,6 +86,10 @@ struct BubbleFragmentStack: View, Equatable { .foregroundStyle(textPayload.baseColor.swiftUIColor) } + if let image = layout.mcoImage { + MCOImageView(content: image) + } + if let disabledImageURL { TapToLoadPreview( url: disabledImageURL, diff --git a/MC1/Views/Chats/Components/ChatInputBar.swift b/MC1/Views/Chats/Components/ChatInputBar.swift index 28fc7a25b4..9a84435d14 100644 --- a/MC1/Views/Chats/Components/ChatInputBar.swift +++ b/MC1/Views/Chats/Components/ChatInputBar.swift @@ -34,6 +34,9 @@ struct ChatInputBar: View { let isEncrypted: Bool @ViewBuilder let leading: () -> Leading let onSend: (String) -> Void + var hasAttachment = false + var isSubmittingAttachment = false + var onSendAttachment: (() -> Void)? @State private var isCoolingDown = false @State private var sendInvocationCounter: Int = 0 @@ -45,11 +48,11 @@ struct ChatInputBar: View { } private var isOverLimit: Bool { - byteCount > maxBytes + !hasAttachment && byteCount > maxBytes } private var shouldShowCharacterCount: Bool { - byteCount >= maxBytes - 20 + !hasAttachment && byteCount >= maxBytes - 20 } var body: some View { @@ -118,7 +121,8 @@ struct ChatInputBar: View { private var canSend: Bool { !isCoolingDown && appState.connectionState == .ready && - !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isOverLimit + !isSubmittingAttachment && + (hasAttachment || !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) && !isOverLimit } /// Hardware Return: `true` consumes it and sends under the same gates as the send @@ -131,6 +135,10 @@ struct ChatInputBar: View { private func send() { composerProxy.commitPendingInput() + if hasAttachment { + onSendAttachment?() + return + } let captured = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !captured.isEmpty else { return } isCoolingDown = true diff --git a/MC1/Views/Chats/Components/ChatShareMenu.swift b/MC1/Views/Chats/Components/ChatShareMenu.swift index 804354e084..e0eb9b6858 100644 --- a/MC1/Views/Chats/Components/ChatShareMenu.swift +++ b/MC1/Views/Chats/Components/ChatShareMenu.swift @@ -2,14 +2,11 @@ import CoreLocation import MC1Services import SwiftUI -/// Liquid Glass "+" menu for the chat input bar. -/// -/// Each action produces a bare formatted string and hands it to `onInsert`; the -/// caller is responsible for appending it to the compose field. This view never -/// reads the compose text. The contact list is fetched lazily inside -/// `ShareContactPickerSheet`, so no contact array is built here. +/// Text actions hand a bare string to `onInsert` and never read the compose field. +/// Pixel painting opens the conversation-owned editor; contacts load in `ShareContactPickerSheet`. struct ChatShareMenu: View { let onInsert: (String) -> Void + var onPaint: (() -> Void)? @Environment(\.appState) private var appState @@ -84,6 +81,13 @@ struct ChatShareMenu: View { } .disabled(!canShareLocation) + if let onPaint { + Button(action: onPaint) { + Label(L10n.Chats.Chats.Mcoimg.title, systemImage: "paintpalette") + } + .accessibilityIdentifier("pixelPaintAction") + } + Button { isShowingContactPicker = true } label: { diff --git a/MC1/Views/Chats/Components/FragmentLayout.swift b/MC1/Views/Chats/Components/FragmentLayout.swift index c685a8036d..fc461e8943 100644 --- a/MC1/Views/Chats/Components/FragmentLayout.swift +++ b/MC1/Views/Chats/Components/FragmentLayout.swift @@ -1,18 +1,8 @@ import Foundation import MC1Services -/// The single source of truth for which fragments render inside the colored -/// bubble box versus as siblings below it. -/// -/// Box-vs-sibling rule: `.text` and `.inlineImage` render inside the box -/// (`BubbleFragmentStack`); every other kind renders as a sibling beneath the -/// box (`UnifiedMessageBubble`), preserving document order. Adding a fragment -/// kind is one decision here, not a fan-out across the bubble view bodies. -/// -/// This is render partitioning, not model data: it is a pure function of -/// `item.content`, computed once in `MessageBubbleView.body` and passed down as -/// a plain value. It is never stored on `MessageItem` and never participates in -/// any bubble view's `==`, so the item-only Equatable seam stays intact. +/// `.text`, `.inlineImage`, and `.mcoImage` render in `BubbleFragmentStack`; every other kind is a sibling in `UnifiedMessageBubble`. +/// Computed from `item.content` and excluded from `MessageItem` equality. struct FragmentLayout { /// The single text fragment that fills the bubble box, if any. let textPayload: MessageTextPayload? @@ -20,13 +10,16 @@ struct FragmentLayout { /// The single inline image attached to the bubble box, if any. let inlineImage: InlineImage? - /// Fragments rendered below the box, in document order. Excludes the - /// box-resident text and inline image. + /// The single MCOimg attached to the bubble box, if any. + let mcoImage: MCOImageContent? + + /// Fragments below the box, in document order, excluding box-resident text, the inline image, and MCOimg. let siblings: [MessageFragment] init(content: [MessageFragment]) { var textPayload: MessageTextPayload? var inlineImage: InlineImage? + var mcoImage: MCOImageContent? var siblings: [MessageFragment] = [] for fragment in content { @@ -35,6 +28,8 @@ struct FragmentLayout { if textPayload == nil { textPayload = payload } case let .inlineImage(image): if inlineImage == nil { inlineImage = image } + case let .mcoImage(image): + if mcoImage == nil { mcoImage = image } case .linkPreview, .mapPreview, .malwareWarning, .reactionSummary: siblings.append(fragment) } @@ -42,6 +37,7 @@ struct FragmentLayout { self.textPayload = textPayload self.inlineImage = inlineImage + self.mcoImage = mcoImage self.siblings = siblings } } diff --git a/MC1/Views/Chats/Components/UnifiedMessageBubble.swift b/MC1/Views/Chats/Components/UnifiedMessageBubble.swift index 7c92569d5c..ba488d1264 100644 --- a/MC1/Views/Chats/Components/UnifiedMessageBubble.swift +++ b/MC1/Views/Chats/Components/UnifiedMessageBubble.swift @@ -246,7 +246,7 @@ struct UnifiedMessageBubble: View, Equatable { onRequestSnapshot: { callbacks.requestSnapshot?($0) }, onRetry: { callbacks.retrySnapshot?($0) } ) - case .text, .inlineImage: + case .text, .inlineImage, .mcoImage: EmptyView() } } @@ -257,7 +257,7 @@ struct UnifiedMessageBubble: View, Equatable { switch fragment { case .linkPreview, .mapPreview, .malwareWarning: true - case .reactionSummary, .text, .inlineImage: + case .reactionSummary, .text, .inlineImage, .mcoImage: false } } @@ -357,10 +357,14 @@ struct UnifiedMessageBubble: View, Equatable { } } } - label += MessageVisibleBody( - stored: message.text, - translation: layout.textPayload?.translation - ).spokenText + if let imageLabel = layout.mcoImage?.accessibilityLabel { + label += imageLabel + } else { + label += MessageVisibleBody( + stored: message.text, + translation: layout.textPayload?.translation + ).spokenText + } if item.envelope.isOutgoing { label += ", \(MessageStatusText.text(for: item.footer))" } diff --git a/MC1/Views/Chats/MCOimg/MCOImageGeometry.swift b/MC1/Views/Chats/MCOimg/MCOImageGeometry.swift new file mode 100644 index 0000000000..272d7483f3 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/MCOImageGeometry.swift @@ -0,0 +1,53 @@ +import MC1Services +import SwiftUI + +/// Anchors are cell centers in image space. `MCOImageRenderer` applies viewport scale later. +enum MCOImageGeometry { + static let cellCenter: CGFloat = 0.5 + + static func point(_ point: MCOImageV4Point) -> CGPoint { + CGPoint(x: CGFloat(point.x) + cellCenter, y: CGFloat(point.y) + cellCenter) + } + + static func rectangle(_ first: MCOImageV4Point, _ second: MCOImageV4Point, _ third: MCOImageV4Point) -> Path { + let first = point(first), second = point(second), third = point(third) + var path = Path() + path.move(to: first) + path.addLine(to: third) + path.addLine(to: second) + path.addLine(to: CGPoint(x: first.x + second.x - third.x, y: first.y + second.y - third.y)) + return path + } + + static func ellipse(_ first: MCOImageV4Point, _ second: MCOImageV4Point, + _ third: MCOImageV4Point) -> (path: Path, closed: Bool)? { + let first = point(first), second = point(second), third = point(third) + let dx = second.x - first.x, dy = second.y - first.y + let length = hypot(dx, dy) + guard length > 0 else { return nil } + let center = CGPoint(x: (first.x + second.x) / 2, y: (first.y + second.y) / 2) + let minor = abs((third.x - center.x) * -dy / length + (third.y - center.y) * dx / length) + if minor < cellCenter { + var path = Path() + path.move(to: first) + path.addLine(to: second) + return (path, false) + } + let rect = CGRect(x: -length / 2, y: -minor, width: length, height: minor * 2) + let transform = CGAffineTransform(translationX: center.x, y: center.y).rotated(by: atan2(dy, dx)) + return (Path(ellipseIn: rect).applying(transform), true) + } + + static func wave(_ start: MCOImageV4Point, _ end: MCOImageV4Point, depth: Int) -> Path? { + let start = point(start), end = point(end) + let dx = end.x - start.x, dy = end.y - start.y + let length = hypot(dx, dy) + guard length > 0 else { return nil } + let control = CGPoint(x: (start.x + end.x) / 2 - dy / length * CGFloat(depth) * 2, + y: (start.y + end.y) / 2 + dx / length * CGFloat(depth) * 2) + var path = Path() + path.move(to: start) + path.addQuadCurve(to: end, control: control) + return path + } +} diff --git a/MC1/Views/Chats/MCOimg/MCOImageRenderer+Text.swift b/MC1/Views/Chats/MCOimg/MCOImageRenderer+Text.swift new file mode 100644 index 0000000000..9885cdfcb1 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/MCOImageRenderer+Text.swift @@ -0,0 +1,53 @@ +import MC1Services +import SwiftUI + +extension MCOImageRenderer { + private static let lineHeightScale: CGFloat = 1.2 + private static let leftAlignment = 0 + private static let centerAlignment = 1 + + /// Fonts and line metrics are client choices; width, alignment, colors and origin come from the document. + static func drawText(_ text: String, origin: MCOImageV4Point, width: Int?, alignment: Int, fontSize: Int, + style: MCOImageV4Style, profile: Int, canvasWidth: Int, context: inout GraphicsContext) { + let resolvedWidth = width ?? max(1, min(canvasWidth, canvasWidth - origin.x)) + let origin = MCOImageGeometry.point(origin) + let width = CGFloat(resolvedWidth) + let lines = wrappedLines(text, width: width, fontSize: fontSize, context: context) + let lineHeight = CGFloat(fontSize) * lineHeightScale + if let fill = style.fillColor { + context.fill(Path(CGRect(x: origin.x, y: origin.y, width: width, height: lineHeight * CGFloat(lines.count))), + with: .color(color(fill, profile: profile))) + } + guard let stroke = style.strokeColor else { return } + for (index, line) in lines.enumerated() { + let resolved = context.resolve(Text(line).font(.system(size: CGFloat(fontSize))).foregroundColor(color(stroke, profile: profile))) + let measured = resolved.measure(in: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)) + let offset: CGFloat = switch alignment { + case leftAlignment: 0 + case centerAlignment: (width - measured.width) / 2 + default: width - measured.width + } + context.draw(resolved, at: CGPoint(x: origin.x + offset, y: origin.y + CGFloat(index) * lineHeight), anchor: .topLeading) + } + } + + private static func wrappedLines(_ text: String, width: CGFloat, fontSize: Int, context: GraphicsContext) -> [String] { + var lines: [String] = [] + for paragraph in text.components(separatedBy: "\n") { + var line = "" + for character in paragraph { + let candidate = line + String(character) + let measured = context.resolve(Text(candidate).font(.system(size: CGFloat(fontSize)))) + .measure(in: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) + if !line.isEmpty, measured.width > width { + lines.append(line) + line = String(character) + } else { + line = candidate + } + } + lines.append(line) + } + return lines + } +} diff --git a/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift b/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift new file mode 100644 index 0000000000..bd5441f788 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift @@ -0,0 +1,112 @@ +import MC1Services +import SwiftUI + +/// Uses logical cells for both versions; raster origins are edges, vector points are centers. +struct MCOImageRenderer: View { + let content: MCOImageContent + private static let strokeMiterLimit: CGFloat = 4 + + var body: some View { + Canvas { context, size in + switch content { + case let .raster(image): + prepare(&context, size: size, width: image.width, height: image.height) + Self.raster(image, origin: .zero, context: &context) + case let .document(document): + prepare(&context, size: size, width: document.width, height: document.height) + if let background = document.backgroundColor { + context.fill(Path(CGRect(x: 0, y: 0, width: document.width, height: document.height)), + with: .color(Self.color(background, profile: document.profile))) + } + for figure in document.figures { + Self.figure(figure, profile: document.profile, canvasWidth: document.width, context: &context) + } + case .unsupported, .damaged: break + } + } + } + + private func prepare(_ context: inout GraphicsContext, size: CGSize, width: Int, height: Int) { + let scale = min(size.width / CGFloat(width), size.height / CGFloat(height)) + context.translateBy(x: (size.width - CGFloat(width) * scale) / 2, + y: (size.height - CGFloat(height) * scale) / 2) + context.scaleBy(x: scale, y: scale) + context.clip(to: Path(CGRect(x: 0, y: 0, width: width, height: height))) + } + + static func color(_ reference: Int, profile: Int) -> Color { + let rgb = MCOImagePalette.color(reference, profile: profile) + let maximumComponent = 255.0 + return Color(.sRGB, red: Double((rgb >> 16) & 0xff) / maximumComponent, + green: Double((rgb >> 8) & 0xff) / maximumComponent, + blue: Double(rgb & 0xff) / maximumComponent, opacity: 1) + } + + static func raster(_ image: MCOImageRaster, origin: CGPoint, context: inout GraphicsContext) { + for row in 0.. 0 else { return } + draft.paint(x: Int(floor(value.location.x / side * Double(PixelPaintDraft.side))), + y: Int(floor(value.location.y / side * Double(PixelPaintDraft.side)))) + }.onEnded { _ in draft.endStroke() }) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { canvasWidth = $0 } + .accessibilityLabel(L10n.Chats.Chats.Mcoimg.canvas) + .accessibilityIdentifier("pixelPaintCanvas") + .accessibilityRepresentation { accessiblePixels } + } + + @State private var canvasWidth: CGFloat = 0 + + private var accessiblePixels: some View { + VStack { + ForEach(0.. 0) } } diff --git a/MC1/Views/Chats/Reactions/MessageActionsSheet.swift b/MC1/Views/Chats/Reactions/MessageActionsSheet.swift index 40a0e4033e..a2accad494 100644 --- a/MC1/Views/Chats/Reactions/MessageActionsSheet.swift +++ b/MC1/Views/Chats/Reactions/MessageActionsSheet.swift @@ -40,7 +40,7 @@ struct MessageActionsSheet: View { Divider() - if !dynamicTypeSize.isAccessibilitySize { + if availability.canReact, !dynamicTypeSize.isAccessibilitySize { ActionsEmojiSection( recentEmojis: recentEmojis, showEmojiPicker: $showEmojiPicker, @@ -52,7 +52,7 @@ struct MessageActionsSheet: View { ScrollViewReader { proxy in ScrollView { VStack(spacing: 0) { - if dynamicTypeSize.isAccessibilitySize { + if availability.canReact, dynamicTypeSize.isAccessibilitySize { ActionsEmojiSection( recentEmojis: recentEmojis, showEmojiPicker: $showEmojiPicker, diff --git a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift index 797f4f6f80..2ae3143422 100644 --- a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift +++ b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift @@ -112,8 +112,10 @@ extension ChatMessageBakeState { envInputs: EnvInputs, senderTables: ChatSenderTables ) -> MessageBuildInputs { - seedPreviewStateIfNeeded(for: message, envInputs: envInputs) - if envInputs.translationOffersEnabled { + if !MCOImageCodec.isImageText(message.text) { + seedPreviewStateIfNeeded(for: message, envInputs: envInputs) + } + if envInputs.translationOffersEnabled, !MCOImageCodec.isImageText(message.text) { seedDetectedLanguageIfNeeded(for: message) } let flags = Self.computeDisplayFlags(for: message, previous: previous, next: next) diff --git a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift index 73f9a16765..a53b71379f 100644 --- a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift +++ b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift @@ -156,12 +156,15 @@ enum ChatTimelinePopulator { } else { message.senderNodeName } - guard let senderName else { continue } + let reactionSender = senderName ?? ( + MCOImageCodec.isChannelImage(channelIndex: message.channelIndex, text: message.text) ? "Unknown" : nil + ) + guard let reactionSender else { continue } let pendingMatches = await reactionService.indexMessage( id: message.id, channelIndex: channel.index, - senderName: senderName, + senderName: reactionSender, text: message.text, timestamp: message.reactionTimestamp ) diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift index 3dd07fc6dd..29a3d57ca6 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift @@ -154,6 +154,15 @@ extension ChatViewModel { errorMessage = nil errorBannerMessage = nil + let originalMessage = message + let message: MessageDTO + do { + message = try await messageService?.prepareImageForResend(originalMessage) ?? originalMessage + } catch { + errorMessage = error.userFacingMessage + return + } + // Capture once so the three status-update writes below all target the // same container even if a reconnect fires between the awaits. let dataStore = dataStore diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift index 63be19ec1e..078bdc36fc 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift @@ -30,6 +30,13 @@ extension ChatViewModel { errorMessage = nil errorBannerMessage = nil + do { + _ = try await messageService?.prepareImageForResend(message) + } catch { + errorMessage = error.userFacingMessage + return + } + let envelope = DirectMessageEnvelope( messageID: message.id, contactID: contact.id, isSingleAttempt: message.reactionTargetMessageID != nil @@ -61,11 +68,17 @@ extension ChatViewModel { /// Resend a channel message in place, or copy text for direct messages. /// Used for "Send Again" context menu action. func sendAgain(_ message: MessageDTO) async { + let originalMessage = message + let message: MessageDTO + do { + message = try await messageService?.prepareImageForResend(originalMessage) ?? originalMessage + } catch { + errorMessage = error.userFacingMessage + return + } if let channelIndex = message.channelIndex { - // Channel messages: enqueue with isResend: true so the queue drain - // refreshes the mesh timestamp via resendChannelMessage. Reusing the - // original timestamp would hash identically to the failed packet and - // be dropped by the 128-slot cyclic dedup table at every neighbor. + // Text resends need a fresh wire timestamp; image nonces were prepared + // before enqueue so automatic queue retries can preserve their payload. let envelope = ChannelMessageEnvelope( messageID: message.id, channelIndex: channelIndex, diff --git a/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift b/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift index 14dc7f41a2..0e2bad4ea7 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift @@ -91,7 +91,7 @@ struct RoomMessageBubble: View { } var accessibilityMessageLabel: String { - let body = visibleBody.spokenText + let body = MCOImageCodec.content(from: message.text)?.accessibilityLabel ?? visibleBody.spokenText if isFromSelf { return "\(body), \(message.accessibilityStatusLabel)" } @@ -242,7 +242,9 @@ private struct BubbleContent: View { @ViewBuilder private var messageBody: some View { - if let plainText = visibleBody.plainText { + if let image = MCOImageCodec.content(from: message.text) { + MCOImageView(content: image) + } else if let plainText = visibleBody.plainText { Text(plainText) .font(.body) .foregroundStyle(textColor) diff --git a/MC1Services/Package.swift b/MC1Services/Package.swift index 1da5ecbbbe..c6da4d7252 100644 --- a/MC1Services/Package.swift +++ b/MC1Services/Package.swift @@ -26,7 +26,8 @@ let package = Package( .product(name: "MeshCoreTestSupport", package: "MeshCore") ], resources: [ - .process("MECP") + .process("MECP"), + .copy("Fixtures") ] ) ] diff --git a/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift b/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift index 11838a76d4..44341cb0ee 100644 --- a/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift +++ b/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift @@ -1,20 +1,7 @@ import Foundation -/// Channel-message envelope for `SendQueue`. -/// -/// `isResend` is load-bearing: a resend must call -/// `MessageService.resendChannelMessage` (which stamps a fresh timestamp -/// so the mesh dedup ring at 128 cyclic slots does not silently drop the -/// retry), while a fresh send must call `sendPendingChannelMessage` -/// which preserves the original timestamp. -/// -/// `messageText`, `messageTimestamp`, and `localNodeName` are captured at -/// enqueue time so the post-send `reactionService.indexMessage(...)` call -/// can read them without depending on view-model state at drain time. -/// During the mesh round-trip the user can navigate to a different channel -/// or rename the connected device — reading mutable state across that -/// window risks tagging the message with stale identity, or indexing -/// against the wrong message entirely. +/// `isResend` selects a fresh text timestamp; an MCOimg nonce is already in the captured text, so drain does not mint one. +/// Captured `messageText`, `messageTimestamp`, and `localNodeName` keep reaction indexing off a later channel or radio name. public struct ChannelMessageEnvelope: Sendable { public let messageID: UUID public let channelIndex: UInt8 diff --git a/MC1Services/Sources/MC1Services/Models/Rendering/MessageFragment.swift b/MC1Services/Sources/MC1Services/Models/Rendering/MessageFragment.swift index 41bd466553..011f2b239c 100644 --- a/MC1Services/Sources/MC1Services/Models/Rendering/MessageFragment.swift +++ b/MC1Services/Sources/MC1Services/Models/Rendering/MessageFragment.swift @@ -9,6 +9,7 @@ import Foundation public enum MessageFragment: Sendable, Hashable { case text(MessageTextPayload) case inlineImage(InlineImage) + case mcoImage(MCOImageContent) case linkPreview(LinkPreviewFragmentState) case mapPreview(MapPreviewFragmentState) case malwareWarning(URL) diff --git a/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift b/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift index bbe2c70750..a9da4cd556 100644 --- a/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift +++ b/MC1Services/Sources/MC1Services/Protocols/MessagePollingServiceProtocol.swift @@ -48,6 +48,9 @@ protocol MessagePollingServiceProtocol: Actor { /// Install the handler invoked for each incoming channel message. func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) + /// Install the handler invoked for each supported channel application datagram. + func setChannelDatagramHandler(_ handler: @escaping @Sendable (ChannelDatagram, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) + /// Install the handler invoked for each incoming signed room message. func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index 896bef9a4a..17d4b8b807 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -97,6 +97,17 @@ public protocol MessagePersisting: Actor { limit: Int ) async throws -> MessageDTO? + /// True when a stored channel image matches this reaction hash. + /// The text lookup returns nil for that row, which is also how a missing text message looks. + func channelImageMatchesReaction( + radioID: UUID, + channelIndex: UInt8, + parsedReaction: ParsedReaction, + localNodeName: String?, + timestampWindow: ClosedRange, + limit: Int + ) async throws -> Bool + /// Fetches channel message candidates for meshcore-open reaction matching func fetchChannelMessageCandidates( radioID: UUID, @@ -158,6 +169,9 @@ public protocol MessagePersisting: Actor { /// Update message retry status func updateMessageRetryStatus(id: UUID, status: MessageStatus, retryAttempt: Int, maxRetryAttempts: Int) async throws + /// Update the exact wire text before a user-initiated image resend. + func updateMessageText(id: UUID, text: String) async throws + /// Update message timestamp (for resending) func updateMessageTimestamp(id: UUID, timestamp: UInt32) async throws @@ -241,6 +255,12 @@ public protocol MessagePersisting: Actor { // MARK: - Default Parameter Values extension MessagePersisting { + public func updateMessageText(id: UUID, text: String) async throws { + guard var message = try await fetchMessage(id: id) else { return } + message.text = text + try await saveMessage(message) + } + /// Update message ACK info with no round-trip time func updateMessageAck(id: UUID, ackCode: UInt32, status: MessageStatus) async throws { try await updateMessageAck(id: id, ackCode: ackCode, status: status, roundTripTime: nil) @@ -275,6 +295,17 @@ extension MessagePersisting { } public extension MessagePersisting { + func channelImageMatchesReaction( + radioID _: UUID, + channelIndex _: UInt8, + parsedReaction _: ParsedReaction, + localNodeName _: String?, + timestampWindow _: ClosedRange, + limit _: Int + ) async throws -> Bool { + false + } + func admitOutgoingReaction(_ message: MessageDTO) async throws -> MessageDTO? { nil } diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift index addff30993..2926c7cfc3 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift @@ -60,7 +60,7 @@ extension ChatSendQueueService { timeout: dependencies.config.transportWaitTimeout ) case let .sent(indexTimestamp): - if let nodeName = envelope.localNodeName { + if let nodeName = envelope.localNodeName, !MCOImageCodec.isImageText(envelope.messageText) { _ = await dependencies.reactionService.indexMessage( id: envelope.messageID, channelIndex: envelope.channelIndex, @@ -134,7 +134,9 @@ extension ChatSendQueueService { envelope: ChannelMessageEnvelope, dependencies: ChannelDrainDependencies ) async throws { - guard isTransientChannelMessageError(error) else { + guard isTransientChannelMessageError( + error, isImage: MCOImageCodec.isImageText(envelope.messageText) + ) else { dependencies.logger.info( "channel drain terminal messageID=\(envelope.messageID) error=\(String(describing: error))" ) diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index d26df2cab0..366619d6c8 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -284,6 +284,9 @@ public final class ChatSendQueueService { guard target.radioID == radioID else { throw ChatSendQueueServiceError.notConnected } guard beginAdmission() else { throw CancellationError() } defer { finishAdmission() } + if MCOImageCodec.isChannelImage(channelIndex: target.channelIndex, text: target.text) { + return nil + } let text: String if target.channelIndex != nil { @@ -567,8 +570,9 @@ public final class ChatSendQueueService { isTransientError(error, deviceCode: FirmwareDeviceErrorCode.directMessageTableFull) } - nonisolated static func isTransientChannelMessageError(_ error: Error) -> Bool { + nonisolated static func isTransientChannelMessageError(_ error: Error, isImage: Bool = false) -> Bool { isTransientError(error, deviceCode: FirmwareDeviceErrorCode.channelMessageNotFound) + || (isImage && isTransientError(error, deviceCode: FirmwareDeviceErrorCode.channelDataTableFull)) } /// Returns true if `error` is `MeshCoreError.deviceError(channelMessageNotFound)` diff --git a/MC1Services/Sources/MC1Services/Services/FirmwareDeviceErrorCode.swift b/MC1Services/Sources/MC1Services/Services/FirmwareDeviceErrorCode.swift index 17e6e04c24..6d0cd06fbc 100644 --- a/MC1Services/Sources/MC1Services/Services/FirmwareDeviceErrorCode.swift +++ b/MC1Services/Sources/MC1Services/Services/FirmwareDeviceErrorCode.swift @@ -22,6 +22,9 @@ public enum FirmwareDeviceErrorCode { /// `.failed` so the user can resend into a different channel. public static let channelMessageNotFound: UInt8 = 2 + /// `TABLE_FULL` on binary GROUP_DATA. The outbound packet pool is temporarily full. + public static let channelDataTableFull: UInt8 = 3 + /// `RESP_CODE_NO_MORE_MESSAGES` surfaced on the remote-node section path. The /// companion radio's offline-message queue is empty, meaning the awaited /// repeater/room reply hasn't arrived yet; the section request backs off and diff --git a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift index a50238fecf..b4c8c2f403 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift @@ -35,6 +35,15 @@ public enum MessageFragmentBuilder { ) -> [MessageFragment] { var fragments: [MessageFragment] = [] + if let image = MCOImageCodec.content(from: message.text) { + fragments.append(.mcoImage(image)) + if !MCOImageCodec.isChannelImage(channelIndex: message.channelIndex, text: message.text), + let summary = message.reactionSummary, !summary.isEmpty { + fragments.append(.reactionSummary(summary)) + } + return fragments + } + fragments.append(.text(makeText(message: message, inputs: inputs, envInputs: envInputs))) if let summary = message.reactionSummary, !summary.isEmpty { @@ -274,7 +283,8 @@ public enum MessageFragmentBuilder { inputs: MessageBuildInputs, message: MessageDTO ) -> Bool { - inputs.previewState == .idle + !MCOImageCodec.isImageText(message.text) + && inputs.previewState == .idle && inputs.cachedURL != nil && message.linkPreviewURL == nil } diff --git a/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift b/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift index 4672107431..a7c6842b13 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift @@ -15,6 +15,7 @@ public enum MessageLanguageDetector: Sendable { /// Dominant language of the mention-stripped body, or `.undetermined`. public static func dominantLanguage(for text: String) -> DetectedLanguage { + guard !MCOImageCodec.isImageText(text) else { return .undetermined } let sample = detectionSample(from: text) guard !sample.isEmpty else { return .undetermined } diff --git a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift index 8b88fe21b7..80c4fc7f24 100644 --- a/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessagePollingService.swift @@ -41,6 +41,9 @@ actor MessagePollingService { /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. private var channelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void)? + private var channelDatagramHandler: (@Sendable (ChannelDatagram, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void)? + private var imageDatagramDuplicates = MCOImageDatagramDuplicates() + /// Handler for signed messages (from room servers). /// Installed by `SyncCoordinator.wireMessageHandlers`; cleared by `clearMessageHandlers`. private var signedMessageHandler: (@Sendable (ContactMessage, ReceiveScope) async -> Void)? @@ -100,6 +103,10 @@ actor MessagePollingService { channelMessageHandler = handler } + func setChannelDatagramHandler(_ handler: @escaping @Sendable (ChannelDatagram, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) { + channelDatagramHandler = handler + } + /// Set handler for signed messages (from room servers) func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) { signedMessageHandler = handler @@ -116,13 +123,14 @@ actor MessagePollingService { func clearMessageHandlers() { contactMessageHandler = nil channelMessageHandler = nil + channelDatagramHandler = nil signedMessageHandler = nil cliMessageHandler = nil } /// Whether any message handler is currently wired. var hasMessageHandlersWired: Bool { - contactMessageHandler != nil || channelMessageHandler != nil + contactMessageHandler != nil || channelMessageHandler != nil || channelDatagramHandler != nil || signedMessageHandler != nil || cliMessageHandler != nil } @@ -263,10 +271,10 @@ actor MessagePollingService { case let .channelMessage(msg): count += 1 await handleChannelMessage(msg, context: .initialSync(anchor: blockAnchor)) - case .channelDatagram: - // Datagrams are not user-visible messages; drain queue without counting. - // A follow-up plan will add a dedicated MC1Services listener for them. - break + case let .channelDatagram(datagram): + if await handleChannelDatagram(datagram, context: .initialSync(anchor: blockAnchor)) { + count += 1 + } case .noMoreMessages: return count } @@ -297,7 +305,11 @@ actor MessagePollingService { guard !isSuspendedForRadioErase else { return } eventMonitorTask?.cancel() let subscription = Task { [session] in - await session.eventsTracked(filter: EventFilter.anyContactMessage.or(.anyChannelMessage)) + let channelData = EventFilter.eventType { event in + if case .channelDataReceived = event { return true } + return false + } + return await session.eventsTracked(filter: EventFilter.anyContactMessage.or(.anyChannelMessage).or(channelData)) } eventSubscription = subscription eventMonitorTask = Task { [weak self, session] in @@ -334,11 +346,30 @@ actor MessagePollingService { defer { pendingHandlerCount -= 1 } await handleChannelMessage(message, context: .live) + case let .channelDataReceived(datagram): + guard !isPolling else { return } + pendingHandlerCount += 1 + defer { pendingHandlerCount -= 1 } + _ = await handleChannelDatagram(datagram, context: .live) + default: break } } + private func handleChannelDatagram(_ datagram: ChannelDatagram, context: DeliveryContext) async -> Bool { + guard MCOImageTransport.decode(datagram) != nil else { return false } + let arrivedAt = Date() + guard let radioID = currentRadioID, + let scope = try? await dataStore.captureReceiveScope(radioID: radioID, link: receiveLifetime), + imageDatagramDuplicates.admit(datagram, radioID: radioID, receivedAt: arrivedAt) else { return false } + let preference = await textRulesPreference() + let channel = try? await dataStore.fetchChannel(radioID: radioID, index: datagram.channelIndex) + guard scope.isCurrent else { return false } + await channelDatagramHandler?(datagram, channel, context, scope, preference, arrivedAt) + return true + } + // MARK: - Private Message Handlers /// Handle incoming contact message diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift index 3e42e680de..7438960900 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift @@ -24,6 +24,26 @@ extension MessageService { } else { scope } + if MCOImageCodec.isImageText(text) { + let payload = try await channelImagePayload(text, radioID: radioID) + if let appliedScope { + try await session.sendChannelData( + channelIndex: channelIndex, + dataType: MCOImageTransport.applicationDataType, + payload: payload, + floodScope: appliedScope + ) + } else { + try await session.sendChannelData( + channelIndex: channelIndex, + dataType: MCOImageTransport.applicationDataType, + payload: payload, + pathLength: PacketBuilder.floodPathSentinel, + pathBytes: Data() + ) + } + return + } if let appliedScope { try await session.sendChannelMessage( channel: channelIndex, diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift b/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift new file mode 100644 index 0000000000..43e4f4aeca --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift @@ -0,0 +1,43 @@ +import Foundation + +public extension MessageService { + /// Refreshes a user-initiated image resend before its queue envelope captures the wire text. + func prepareImageForResend(_ message: MessageDTO) async throws -> MessageDTO { + guard MCOImageCodec.isImageText(message.text) else { return message } + var refreshed = message + let text = message.channelIndex != nil + ? try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: message.text)) + : message.text + refreshed.text = try MCOImageCodec.refreshNonce(in: text) + if message.channelIndex != nil { + _ = try await channelImagePayload(refreshed.text, radioID: message.radioID) + } else { + guard refreshed.text.utf8.count <= ProtocolLimits.maxDirectMessageLength else { + throw MessageServiceError.messageTooLong + } + } + try await dataStore.updateMessageText(id: message.id, text: refreshed.text) + return refreshed + } + + internal func prepareChannelMessage(_ text: String, radioID: UUID) async throws -> String { + guard MCOImageCodec.isImageText(text) else { + try await rejectIfChannelTextTooLong(text, radioID: radioID) + return text + } + let canonicalText = try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: text)) + _ = try await channelImagePayload(canonicalText, radioID: radioID) + return canonicalText + } + + internal func channelImagePayload(_ text: String, radioID: UUID) async throws -> Data { + guard let device = try await dataStore.fetchDevice(radioID: radioID) else { + throw MessageServiceError.notConnected + } + let payload = try MCOImageTransport.encode(text: text, senderName: device.nodeName) + guard payload.count <= MCOImageWireBudget.maximumChannelDataBytes else { + throw MessageServiceError.messageTooLong + } + return payload + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index 16f67dfc52..0ca6aaf503 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -42,7 +42,7 @@ public extension MessageService { // Keep this send in the retirement barrier through the Sent write if scope cleanup triggers recovery. try beginInlineSend() defer { endInlineSend() } - try await rejectIfChannelTextTooLong(text, radioID: radioID) + let text = try await prepareChannelMessage(text, radioID: radioID) let messageID = UUID() let timestamp = UInt32(Date().timeIntervalSince1970) @@ -59,7 +59,7 @@ public extension MessageService { try await dataStore.saveMessage(messageDTO) do { - try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, config: config.poolBackoff, logger: logger) { + try await withPoolBackoff(transientCode: channelPoolErrorCode(text), config: config.poolBackoff, logger: logger) { try await sendChannelMessageWithScope( text: text, channelIndex: channelIndex, @@ -97,7 +97,7 @@ public extension MessageService { radioID: UUID, textType: TextType = .plain ) async throws -> MessageDTO { - try await rejectIfChannelTextTooLong(text, radioID: radioID) + let text = try await prepareChannelMessage(text, radioID: radioID) let messageID = UUID() let timestamp = UInt32(Date().timeIntervalSince1970) @@ -144,7 +144,7 @@ public extension MessageService { let isReaction = message.reactionTargetMessageID != nil let alreadyAccepted = isReaction && (acceptedChannelReactions.contains(messageID) || message.status == .sent) if !alreadyAccepted { - try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, config: config.poolBackoff, logger: logger) { + try await withPoolBackoff(transientCode: channelPoolErrorCode(message.text), config: config.poolBackoff, logger: logger) { try await sendChannelMessageWithScope( text: message.text, channelIndex: channelIndex, @@ -184,7 +184,7 @@ public extension MessageService { } } - /// Resends a channel message, preserving its wire timestamp only during recovery. + /// Recovery keeps the wire timestamp; a user resend stamps a new one. An MCOimg keeps the nonce prepared before admission. /// Returns that timestamp so reaction indexing matches the send. @discardableResult func resendChannelMessage( @@ -221,7 +221,7 @@ public extension MessageService { acceptedChannelReactions.contains(messageID) || (preserveTimestamp && message.status == .sent) ) if !alreadyAccepted { - try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, config: config.poolBackoff, logger: logger) { + try await withPoolBackoff(transientCode: channelPoolErrorCode(message.text), config: config.poolBackoff, logger: logger) { try await sendChannelMessageWithScope( text: message.text, channelIndex: channelIndex, @@ -261,6 +261,10 @@ public extension MessageService { return wireTimestamp } + private func channelPoolErrorCode(_ text: String) -> UInt8 { + MCOImageCodec.isImageText(text) ? FirmwareDeviceErrorCode.channelDataTableFull : FirmwareDeviceErrorCode.channelMessageNotFound + } + private func createOutgoingChannelMessage( id: UUID, radioID: UUID, diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift index 79734cf696..b91c2116d3 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendDM.swift @@ -233,7 +233,11 @@ public extension MessageService { replyToID: replyToID ) try await dataStore.saveMessage(messageDTO) - try await dataStore.updateContactLastMessage(contactID: contact.id, date: messageDTO.date) + do { + try await dataStore.updateContactLastMessage(contactID: contact.id, date: messageDTO.date) + } catch { + logger.warning("Pending DM saved but contact bookkeeping failed: \(error.localizedDescription)") + } return messageDTO } @@ -305,6 +309,8 @@ public extension MessageService { return existingMessage } + try validateDirectMessage(text: existingMessage.text, to: contact) + // The mesh seen table keys on ciphertext hash. A preserved timestamp continues // at the next unused attempt byte. A new timestamp is a new packet on this message. let wireTimestamp: UInt32 diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index 7ac735a935..bc111eab1b 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -241,6 +241,11 @@ public extension PersistenceStore { continue } + guard !MCOImageCodec.isChannelImage(channelIndex: candidate.channelIndex, text: candidate.text) else { + logger.debug("[REACTION-MATCH] Skip channel image") + continue + } + logger.debug("[REACTION-MATCH] Found match!") return candidate } @@ -249,6 +254,39 @@ public extension PersistenceStore { return nil } + /// True when a channel image in the window hashes to this reaction. + /// A text lookup miss looks the same as this, so the caller must not queue it. + func channelImageMatchesReaction( + radioID: UUID, + channelIndex: UInt8, + parsedReaction: ParsedReaction, + localNodeName: String?, + timestampWindow: ClosedRange, + limit: Int + ) async throws -> Bool { + let candidates = try fetchChannelMessageCandidates( + radioID: radioID, + channelIndex: channelIndex, + timestampWindow: timestampWindow, + limit: limit + ) + for candidate in candidates { + guard MCOImageCodec.isChannelImage(channelIndex: candidate.channelIndex, text: candidate.text) else { + continue + } + if candidate.direction == .outgoing { + guard let localNodeName, parsedReaction.targetSender == localNodeName else { continue } + } else { + guard candidate.senderNodeName == parsedReaction.targetSender else { continue } + } + let candidateHash = ReactionParser.generateMessageHash( + text: candidate.text, timestamp: candidate.reactionTimestamp + ) + if candidateHash == parsedReaction.messageHash { return true } + } + return false + } + /// Fetches channel message candidates within a timestamp window for meshcore-open reaction matching. /// /// Returns raw candidates without hash matching — the caller performs Dart hash comparison. @@ -529,6 +567,19 @@ public extension PersistenceStore { } } + func updateMessageText(id: UUID, text: String) async throws { + let targetID = id + let predicate = #Predicate { message in + message.id == targetID + } + var descriptor = FetchDescriptor(predicate: predicate) + descriptor.fetchLimit = 1 + if let message = try modelContext.fetch(descriptor).first { + message.text = text + try modelContext.save() + } + } + /// Update message timestamp (for resending) func updateMessageTimestamp(id: UUID, timestamp: UInt32) throws { let targetID = id @@ -1039,6 +1090,9 @@ public extension PersistenceStore { var messageDescriptor = FetchDescriptor(predicate: messagePredicate) messageDescriptor.fetchLimit = 1 guard let message = try modelContext.fetch(messageDescriptor).first else { return nil } + if MCOImageCodec.isChannelImage(channelIndex: message.channelIndex, text: message.text) { + return nil + } let senderName = dto.senderName let emoji = dto.emoji diff --git a/MC1Services/Sources/MC1Services/Services/ReactionService.swift b/MC1Services/Sources/MC1Services/Services/ReactionService.swift index 4b51ddb790..9de65eba93 100644 --- a/MC1Services/Sources/MC1Services/Services/ReactionService.swift +++ b/MC1Services/Sources/MC1Services/Services/ReactionService.swift @@ -75,6 +75,19 @@ public actor ReactionService { text: String, timestamp: UInt32 ) async -> [PendingReaction] { + let hash = ReactionParser.generateMessageHash(text: text, timestamp: timestamp) + let key = PendingReactionKey( + channelIndex: channelIndex, + targetSender: senderName, + messageHash: hash + ) + // A channel image is not a reaction target. Drop a reaction that arrived + // first, and do not leave the image in the cache for a later lookup. + if MCOImageCodec.isChannelImage(channelIndex: channelIndex, text: text) { + discardPendingReaction(for: key) + return [] + } + await messageCache.index( messageID: id, channelIndex: channelIndex, @@ -83,14 +96,6 @@ public actor ReactionService { timestamp: timestamp ) - // Check pending queue for matching reactions - let hash = ReactionParser.generateMessageHash(text: text, timestamp: timestamp) - let key = PendingReactionKey( - channelIndex: channelIndex, - targetSender: senderName, - messageHash: hash - ) - guard let matched = pendingReactions.removeValue(forKey: key) else { return [] } @@ -287,6 +292,11 @@ public actor ReactionService { logger.debug("Queued pending DM reaction \(parsed.emoji)") } + private func discardPendingReaction(for key: PendingReactionKey) { + guard pendingReactions.removeValue(forKey: key) != nil else { return } + pendingOrder.removeAll { $0 == key } + } + private func evictIfNeeded() { var totalCount = pendingReactions.values.reduce(0) { $0 + $1.count } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift index 4ec3a51d48..92934e4775 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+HandlerHelpers.swift @@ -20,11 +20,18 @@ extension SyncCoordinator { dependencies: SyncDependencies, radioID: UUID, channelIndex: UInt8?, - senderTimestamp: UInt32, + senderTimestamp: UInt32?, senderPublicKeyPrefix: Data?, defaultPathLength: UInt8, channelDeduplicationKey: String? ) async -> RxLogLookupResult { + // GROUP_DATA has no sender timestamp and cannot join timestamp-indexed text packets. + guard let senderTimestamp else { + return RxLogLookupResult( + pathNodes: nil, pathLength: defaultPathLength, packetHash: nil, + routeType: nil, regionScope: nil, regionScopeMatches: [] + ) + } if let channelIndex { logger.debug("Looking up RxLogEntry for channel \(channelIndex) with senderTimestamp: \(senderTimestamp)") } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 87d4d1d770..56c67a130f 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -19,6 +19,7 @@ extension SyncCoordinator { await wireContactMessageHandler(dependencies: dependencies, radioID: radioID, selfNodeName: selfNodeName) await wireChannelMessageHandler(dependencies: dependencies, radioID: radioID, selfNodeName: selfNodeName) + await wireChannelDatagramHandler(dependencies: dependencies, radioID: radioID, selfNodeName: selfNodeName) await wireSignedMessageHandler(dependencies: dependencies) await wireCLIMessageHandler(dependencies: dependencies) @@ -58,6 +59,30 @@ extension SyncCoordinator { } } + private func wireChannelDatagramHandler(dependencies: SyncDependencies, radioID: UUID, selfNodeName: String) async { + await dependencies.messagePollingService.setChannelDatagramHandler { [weak self] datagram, channel, context, scope, preference, arrivedAt in + guard let self, scope.radioID == radioID, scope.isCurrent, let image = MCOImageTransport.decode(datagram) else { return } + let message = ChannelMessage( + channelIndex: datagram.channelIndex, + pathLength: datagram.pathLength, + textType: MeshTextType.plain.rawValue, + senderTimestamp: Date(timeIntervalSince1970: 0), + text: image.text, + snr: datagram.snr + ) + await handleIncomingMessage( + kind: .channel(message, channel: channel), + receivedAt: arrivedAt, + context: context, + dependencies: dependencies, + selfNodeName: selfNodeName, + scope: scope, + preference: preference, + datagramSenderName: image.senderName + ) + } + } + // MARK: - Incoming Message Pipeline /// Discriminates the two text-message ingestion paths, carrying the wire @@ -175,7 +200,8 @@ extension SyncCoordinator { dependencies: SyncDependencies, selfNodeName: String, scope: ReceiveScope, - preference: TextRulesPreference? + preference: TextRulesPreference?, + datagramSenderName: String? = nil ) async { guard scope.isCurrent else { return } let radioID = scope.radioID @@ -213,7 +239,12 @@ extension SyncCoordinator { senderKeyPrefix = message.senderPublicKeyPrefix case let .channel(message, _): // Parse "NodeName: text" format for sender name - (senderNodeName, text) = Self.parseChannelMessage(message.text) + if let datagramSenderName { + senderNodeName = datagramSenderName + text = message.text + } else { + (senderNodeName, text) = Self.parseChannelMessage(message.text) + } senderTimestampDate = message.senderTimestamp textTypeRaw = message.textType snr = message.snr @@ -239,7 +270,9 @@ extension SyncCoordinator { // retries with different attempt counters, so it must not drive dedup. let deduplicationKey = Self.fallbackDeduplicationKey( contactID: contactID, channelIndex: channelIndex, - senderNodeName: senderNodeName, timestamp: timestamp, content: text + senderNodeName: senderNodeName, + timestamp: datagramSenderName == nil ? timestamp : finalTimestamp, + content: text ) // Channel lookup joins decrypted 0x88 rows by DeduplicationKey; DMs still @@ -248,7 +281,7 @@ extension SyncCoordinator { dependencies: dependencies, radioID: radioID, channelIndex: channelIndex, - senderTimestamp: timestamp, + senderTimestamp: datagramSenderName == nil ? timestamp : nil, senderPublicKeyPrefix: senderKeyPrefix, defaultPathLength: reportedPathLength, channelDeduplicationKey: channelIndex != nil ? deduplicationKey : nil @@ -363,15 +396,21 @@ extension SyncCoordinator { messageDTO, scope: scope, conversationID: channel?.textRulesID ), scope.isCurrent else { return } - let savedDTO = try await harvestAndRefreshChannelMessage( - messageDTO: messageDTO, - radioID: radioID, - dependencies: dependencies, - scope: scope - ) + let savedDTO: MessageDTO + if datagramSenderName == nil { + savedDTO = try await harvestAndRefreshChannelMessage( + messageDTO: messageDTO, + radioID: radioID, + dependencies: dependencies, + scope: scope + ) + } else { + savedDTO = messageDTO + } try await indexAndNotifyChannelMessage( messageDTO: savedDTO, channel: channel, + indexesReactions: datagramSenderName == nil, dependencies: dependencies, scope: scope ) @@ -487,12 +526,16 @@ extension SyncCoordinator { private func indexAndNotifyChannelMessage( messageDTO: MessageDTO, channel: ChannelDTO?, + indexesReactions: Bool = true, dependencies: SyncDependencies, scope: ReceiveScope ) async throws { guard scope.isCurrent, let channelIndex = messageDTO.channelIndex else { return } - // Use the sender timestamp so pending reactions match corrected-clock messages. - if let senderName = messageDTO.senderNodeName { + // A channel image is not a reaction target. Indexing it still runs so a + // reaction queued before the image arrived drops that pending key. + let isChannelImage = MCOImageCodec.isChannelImage(channelIndex: channelIndex, text: messageDTO.text) + let senderName = messageDTO.senderNodeName ?? (isChannelImage ? "Unknown" : nil) + if indexesReactions || isChannelImage, let senderName { let pendingMatches = await dependencies.reactionService.indexMessage( id: messageDTO.id, channelIndex: channelIndex, diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift index 5d4a292817..92c4ac94e1 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift @@ -252,6 +252,17 @@ extension SyncCoordinator { return true } + if (try? await dependencies.dataStore.channelImageMatchesReaction( + radioID: radioID, + channelIndex: channelIndex, + parsedReaction: parsed, + localNodeName: selfNodeName.isEmpty ? nil : selfNodeName, + timestampWindow: timestampWindow, + limit: 200 + )) == true { + return true + } + // Queue reaction for later matching when target message arrives await dependencies.reactionService.queuePendingReaction( parsed: parsed, @@ -360,6 +371,7 @@ extension SyncCoordinator { for candidate in candidates { // Skip messages that are themselves reactions if ReactionParser.isReactionText(candidate.text, isDM: false) { continue } + if MCOImageCodec.isChannelImage(channelIndex: candidate.channelIndex, text: candidate.text) { continue } // For channel messages, the Dart hash includes the sender name let candidateSenderName: String? = if candidate.direction == .outgoing { @@ -472,6 +484,7 @@ extension SyncCoordinator { for candidate in candidates { if ReactionParser.isReactionText(candidate.text, isDM: false) { continue } + if MCOImageCodec.isChannelImage(channelIndex: candidate.channelIndex, text: candidate.text) { continue } // Verify sender name hash let candidateSenderName: String? = if candidate.direction == .outgoing { diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOImageDatagramDuplicates.swift b/MC1Services/Sources/MC1Services/Utilities/MCOImageDatagramDuplicates.swift new file mode 100644 index 0000000000..f5207d9be7 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOImageDatagramDuplicates.swift @@ -0,0 +1,32 @@ +import Foundation +import MeshCore + +/// Limits duplicate suppression because image packet nonces have only one byte. +struct MCOImageDatagramDuplicates { + static let capacity = 128 + static let lifetime: TimeInterval = 60 + + private struct Entry { + let radioID: UUID + let channelIndex: UInt8 + let payload: Data + let receivedAt: Date + } + + private var entries: [Entry] = [] + + mutating func admit(_ datagram: ChannelDatagram, radioID: UUID, receivedAt: Date) -> Bool { + entries.removeAll { receivedAt.timeIntervalSince($0.receivedAt) >= Self.lifetime } + guard !entries.contains(where: { + $0.radioID == radioID && $0.channelIndex == datagram.channelIndex && $0.payload == datagram.data + }) else { return false } + if entries.count == Self.capacity { entries.removeFirst() } + entries.append(Entry( + radioID: radioID, + channelIndex: datagram.channelIndex, + payload: datagram.data, + receivedAt: receivedAt + )) + return true + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift new file mode 100644 index 0000000000..a6d15b5594 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift @@ -0,0 +1,50 @@ +import Foundation +import MeshCore + +/// Reads the sender name and stored MCOimg text without decoding the image. +public enum MCOImageTransport { + public static let applicationDataType: UInt16 = 0x0120 + public static let imageSubtype: UInt8 = 0x01 + private static let subtypeShift: UInt8 = 4 + private static let varintPayloadMask: UInt8 = 0x7f + private static let varintContinuation: UInt8 = 0x80 + private static let varintPayloadBits = 7 + private static let maxVarintBytes = 5 + + public static func encode(text: String, senderName: String) throws -> Data { + let payload = try MCOImageCodec.channelAppPayload(fromText: text) + let name = Data(senderName.utf8) + var writer = MCOImageBitWriter() + writer.varUint(name.count) + return writer.data + name + payload + } + + public static func decode(_ datagram: ChannelDatagram) -> (senderName: String, text: String)? { + guard datagram.dataType == applicationDataType, + datagram.data.count <= MCOImageWireBudget.maximumChannelDataBytes else { return nil } + let bytes = Array(datagram.data) + var nameLength = 0 + var cursor = 0 + for index in 0..> subtypeShift == imageSubtype, + let text = try? MCOImageCodec.text(fromAppPayload: Data(bytes[cursor...])) else { + return nil + } + return (senderName: name, text: text) + } + } + return nil + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift new file mode 100644 index 0000000000..fbb81e876c --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift @@ -0,0 +1,59 @@ +import Foundation + +public enum MCOImageBase91 { + private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~\"".utf8) + private static let decodeTable = Dictionary(uniqueKeysWithValues: alphabet.enumerated().map { ($1, $0) }) + private static let radix = 91 + private static let shortMask = 8191 + private static let longMask = 16383 + private static let shortThreshold = 88 + + public static func encode(_ data: Data) -> String { + var output: [UInt8] = [] + var queue = 0 + var bits = 0 + for byte in data { + queue |= Int(byte) << bits + bits += 8 + if bits > 13 { + var value = queue & shortMask + let consumed = value > shortThreshold ? 13 : 14 + if consumed == 14 { value = queue & longMask } + queue >>= consumed + bits -= consumed + output.append(alphabet[value % radix]) + output.append(alphabet[value / radix]) + } + } + if bits > 0 { + output.append(alphabet[queue % radix]) + if bits > 7 || queue > radix - 1 { output.append(alphabet[queue / radix]) } + } + return String(decoding: output, as: UTF8.self) + } + + public static func decode(_ text: String) throws -> Data { + var output = Data() + var value = -1 + var queue = 0 + var bits = 0 + for character in text.utf8 { + guard let decoded = decodeTable[character] else { throw MCOImageCodecError.damaged } + if value < 0 { + value = decoded + } else { + value += decoded * radix + queue |= value << bits + bits += (value & shortMask) > shortThreshold ? 13 : 14 + while bits > 7 { + output.append(UInt8(queue & 255)) + queue >>= 8 + bits -= 8 + } + value = -1 + } + } + if value >= 0 { output.append(UInt8((queue | (value << bits)) & 255)) } + return output + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift new file mode 100644 index 0000000000..a4ad02381e --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift @@ -0,0 +1,81 @@ +import Foundation + +/// MCOimg fields are least-significant-bit first, including unaligned integers. +struct MCOImageBitReader { + let bytes: [UInt8] + var position: Int + + init(_ data: Data, byteOffset: Int = 0) { + bytes = Array(data) + position = byteOffset * 8 + } + + static func width(_ value: Int) -> Int { value <= 0 ? 0 : Int.bitWidth - value.leadingZeroBitCount } + + mutating func read(_ bits: Int) throws -> Int { + guard (0...32).contains(bits), position >= 0, position + bits <= bytes.count * 8 else { throw MCOImageCodecError.damaged } + var value = 0 + for shift in 0..> (position % 8)) & 1) << shift + position += 1 + } + return value + } + + mutating func varUint() throws -> Int { + var result = 0 + for index in 0..<5 { + let byte = try read(8) + result |= (byte & 127) << (index * 7) + if byte & 128 == 0 { return result } + } + throw MCOImageCodecError.damaged + } + + mutating func prefix(limit: Int) throws -> Int { + for length in 0.. Int { + switch try prefix(limit: 3) { + case 0: return try read(2) + case 1: return try read(4) + 4 + case 2: return try read(8) + 20 + default: return try varUint() + } + } + + mutating func range(_ maximum: Int) throws -> Int { + guard maximum >= 0 else { throw MCOImageCodecError.damaged } + let value = try maximum <= 7 ? read(Self.width(maximum)) : compact() + guard value <= maximum else { throw MCOImageCodecError.damaged } + return value + } + + mutating func bounded(_ maximum: Int) throws -> Int { + guard maximum >= 0 else { throw MCOImageCodecError.damaged } + if maximum <= 7 { return try range(maximum) } + let value: Int + switch try prefix(limit: 3) { + case 0: value = try read(2) + case 1: value = try read(4) + 4 + case 2: value = try read(8) + 20 + default: + guard maximum >= 276 else { throw MCOImageCodecError.damaged } + value = try read(Self.width(maximum - 276)) + 276 + } + guard value <= maximum else { throw MCOImageCodecError.damaged } + return value + } + + mutating func signed() throws -> Int { + let encoded = try compact() + return encoded & 1 == 0 ? encoded / 2 : -(encoded + 1) / 2 + } + + mutating func finish() throws { + let padding = (8 - position % 8) % 8 + guard try read(padding) == 0, position == bytes.count * 8 else { throw MCOImageCodecError.damaged } + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift new file mode 100644 index 0000000000..32a6d5bc7e --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift @@ -0,0 +1,44 @@ +import Foundation + +struct MCOImageBitWriter { + var bytes: [UInt8] = [] + var position = 0 + + mutating func write(_ value: Int, _ bits: Int) { + for shift in 0..> shift) & 1) << (position % 8) + position += 1 + } + } + + mutating func varUint(_ value: Int) { + var remaining = value + repeat { + var byte = remaining & 127 + remaining >>= 7 + if remaining != 0 { byte |= 128 } + write(byte, 8) + } while remaining != 0 + } + + mutating func compact(_ value: Int) { + if value <= 3 { write(0, 1); write(value, 2) } else if value <= 19 { + write(1, 2); write(value - 4, 4) + } else if value <= 275 { + write(3, 3); write(value - 20, 8) + } else { + write(7, 3); varUint(value) + } + } + + mutating func bounded(_ value: Int, _ maximum: Int) { + if maximum <= 7 { write(value, MCOImageBitReader.width(maximum)) } else if value <= 275 { + compact(value) + } else { + write(7, 3); write(value - 276, MCOImageBitReader.width(maximum - 276)) + } + } + + var data: Data { Data(bytes) } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift new file mode 100644 index 0000000000..3c189def1b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift @@ -0,0 +1,93 @@ +import Foundation + +/// Dispatches the two text envelopes without conflating their Base91 input layers. +public enum MCOImageCodec { + public static let v3Subtype: UInt8 = 0x13 + public static let v4Subtype: UInt8 = 0x14 + private static let v3Version = 3 + private static let v4Version = 4 + private static let maximumVersionDigits = 2 + private static let textPrefixLength = 2 + private static let subtype: UInt8 = 1 + private static let versionMask: UInt8 = 0x0f + private static let subtypeShift = 4 + + public static func isImageText(_ text: String) -> Bool { + version(in: text.trimmingCharacters(in: .whitespacesAndNewlines)) != nil + } + + /// A channel row whose text is MCOimg. Group data and a channel text packet + /// with an `im3:` or `im4:` body are the same stored shape. + public static func isChannelImage(channelIndex: UInt8?, text: String) -> Bool { + channelIndex != nil && isImageText(text) + } + + public static func content(from text: String) -> MCOImageContent? { + let text = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard let version = version(in: text) else { return nil } + guard version == v3Version || version == v4Version else { return .unsupported } + do { + let payload = try appPayload(fromText: text) + let body = Data(payload.dropFirst()) + switch version { + case v3Version: return .raster(try MCOImageV3Codec.decodeBody(body)) + case v4Version: return .document(try MCOImageV4Codec.decodeBody(body)) + default: return .unsupported + } + } catch MCOImageCodecError.unsupported { + return .unsupported + } catch { + return .damaged + } + } + + public static func text(fromAppPayload payload: Data) throws -> String { + guard let header = payload.first, header >> subtypeShift == subtype else { + throw MCOImageCodecError.damaged + } + let version = header & versionMask + let bytes = header == v4Subtype ? Data(payload.dropFirst()) : payload + return "im\(version):" + MCOImageBase91.encode(bytes) + } + + public static func appPayload(fromText text: String) throws -> Data { + let text = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard let version = version(in: text), let colon = text.firstIndex(of: ":") else { + throw MCOImageCodecError.damaged + } + let decoded = try MCOImageBase91.decode(String(text[text.index(after: colon)...])) + guard !decoded.isEmpty else { throw MCOImageCodecError.damaged } + if version == v4Version { return Data([v4Subtype]) + decoded } + guard decoded.first == (subtype << subtypeShift | UInt8(version)) else { + throw MCOImageCodecError.damaged + } + return decoded + } + + public static func refreshNonce(in text: String) throws -> String { + var payload = try appPayload(fromText: text) + guard payload.count > 1 else { throw MCOImageCodecError.damaged } + payload[1] = UInt8.random(in: .min ... .max) + return try self.text(fromAppPayload: payload) + } + + public static func channelAppPayload(fromText text: String) throws -> Data { + let payload = try appPayload(fromText: text) + let body = Data(payload.dropFirst()) + switch payload.first { + case v3Subtype: return try Data([v4Subtype]) + MCOImageV4Codec.wrappingV3Body(body) + case v4Subtype: + _ = try MCOImageV4Codec.decodeBody(body) + return payload + default: throw MCOImageCodecError.unsupported + } + } + + private static func version(in text: String) -> Int? { + guard text.hasPrefix("im"), let colon = text.firstIndex(of: ":") else { return nil } + let digits = text[text.index(text.startIndex, offsetBy: textPrefixLength).. Self { + func moved(_ point: MCOImageV4Point) -> MCOImageV4Point { point.translated(x: x, y: y) } + switch self { + case let .dot(point, _): return .dot(moved(point), nextStyle) + case let .line(start, end, _): return .line(moved(start), moved(end), nextStyle) + case let .rectangle(first, second, third, _): return .rectangle(moved(first), moved(second), moved(third), nextStyle) + case let .ellipse(first, second, third, _): return .ellipse(moved(first), moved(second), moved(third), nextStyle) + case let .path(points, closed, _): return .path(points.map(moved), closed: closed, nextStyle) + case let .wave(start, end, depth, closed, _): + return .wave(moved(start), moved(end), depth: depth, closed: closed, nextStyle) + case let .text(origin, width, alignment, fontSize, text, _): + return .text(origin: moved(origin), width: width, alignment: alignment, fontSize: fontSize, text: text, nextStyle) + case let .group(figures, oldStyle): + return .group(figures.map { child in + child.translated(x: x, y: y, style: oldStyle == nextStyle ? child.style : nextStyle) + }, nextStyle) + case let .raster(origin, image): return .raster(origin: moved(origin), image: image) + } + } + + func expandedCount(upTo limit: Int) throws -> Int { + guard limit > 0 else { throw MCOImageCodecError.unsupported } + if case let .group(figures, _) = self { + var total = 0 + for figure in figures { total += try figure.expandedCount(upTo: limit - total) } + return total + } + return 1 + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette+Tables.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette+Tables.swift new file mode 100644 index 0000000000..ad6ccc1131 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette+Tables.swift @@ -0,0 +1,193 @@ +extension MCOImagePalette { + static let fixed: [[UInt32]] = [ + [ + 0xFFFFFF, 0x000000, + ], + [ + 0xFFFFFF, 0xC0C0C0, 0x565656, 0x000000, + ], + [ + 0xFFFFFF, 0x8D8D8D, 0x000000, 0xFE2400, 0xF1D100, 0x47C000, 0x3D69FF, 0x7900FF, + ], + [ + 0xFFFFFF, 0xA4A4A4, 0x000000, 0xD11E01, 0x620E01, 0xFF8400, 0x7B4000, 0xF1D100, 0x907C02, 0x41B000, 0x286E00, 0x7FDCFF, + 0x003AFF, 0x002296, 0x6A00E3, 0x2F0064, + ], + [ + 0xFFFFFF, 0xB3B3B3, 0x666666, 0x000000, 0xFFB0A3, 0xFF5541, 0xFE2400, 0x620E01, 0xFFB363, 0xFF8400, 0xC56601, 0x8E4900, + 0xF5DE5B, 0xF1D100, 0xB59D02, 0x786902, 0x95DA76, 0x47C000, 0x286E00, 0x1D4F00, 0xC4F1FF, 0x01C3FF, 0x038DB8, 0x016D8F, + 0x7596FF, 0x003AFF, 0x022ECA, 0x002296, 0xD7B2FF, 0xB287FF, 0x853DFF, 0x2F0064, + ], + [ + 0xFFFFFF, 0xD9D9D9, 0xB3B3B3, 0x8A8B8A, 0x6F6F6F, 0x4F4F4F, 0x242424, 0x000000, 0xFFB0A3, 0xFF9A89, 0xFF5541, 0xFE2400, + 0xD11E01, 0x911500, 0x620E01, 0x450A00, 0xFFB363, 0xFFA855, 0xFF9333, 0xFF8400, 0xE47601, 0xC56601, 0x8E4900, 0x7B4000, + 0xF7E572, 0xF5DE5B, 0xF1D100, 0xDFC102, 0xCBB101, 0xB59D02, 0x907C02, 0x786902, 0xB7E69B, 0x95DA76, 0x6DCD4B, 0x47C000, + 0x41B000, 0x369401, 0x286E00, 0x1D4F00, 0xC4F1FF, 0xABE9FF, 0x7FDCFF, 0x01C3FF, 0x00B6EE, 0x01AADF, 0x038DB8, 0x016D8F, + 0x91AAFF, 0x7596FF, 0x3B64FF, 0x003AFF, 0x0233E1, 0x022ECA, 0x0128B0, 0x002296, 0xD7B2FF, 0xB287FF, 0x9A65FF, 0x853DFF, + 0x7900FF, 0x6902DD, 0x5301AF, 0x2F0064, + ], + [ + 0xFFFFFF, 0xEEEEEE, 0xDDDDDD, 0xCCCCCC, 0xBBBBBB, 0xAAAAAA, 0x999999, 0x888888, 0x777777, 0x666666, 0x555555, 0x444444, + 0x333333, 0x222222, 0x111111, 0x000000, + ], + [ + 0xFFFFFF, 0xF7F7F7, 0xEFEFEF, 0xE6E6E6, 0xDEDEDE, 0xD6D6D6, 0xCECECE, 0xC5C5C5, 0xBDBDBD, 0xB5B5B5, 0xADADAD, 0xA5A5A5, + 0x9C9C9C, 0x949494, 0x8C8C8C, 0x848484, 0x7B7B7B, 0x737373, 0x6B6B6B, 0x636363, 0x5A5A5A, 0x525252, 0x4A4A4A, 0x424242, + 0x393939, 0x313131, 0x292929, 0x212121, 0x181818, 0x101010, 0x080808, 0x000000, + ], + [ + 0xFFFFFF, 0xDBDBDB, 0xB6B6B6, 0x919191, 0x6D6D6D, 0x484848, 0x242424, 0x000000, + ], + ] + + static let global512: [UInt32] = [ + 0xFFFFFF, 0xF1D3B3, 0xD7AE83, 0xBB875D, 0x9B633E, 0x7C492D, 0x5E331F, 0x412116, 0x25110B, 0xD9D9D9, 0xFFEDE5, 0xFFE5D3, + 0xFFD8C6, 0xF8CCBF, 0xF4BFA5, 0xEBB88F, 0xE0A984, 0xD2977B, 0xB3B3B3, 0xFFD6E0, 0xFFDCC8, 0xFFF2B8, 0xCDECCF, 0xC9EEF0, + 0xCEDDFA, 0xE0D2F4, 0xEACFE3, 0x8A8B8A, 0xE4E0AE, 0xCAC783, 0xAAA95F, 0x898B43, 0x6D7134, 0x535629, 0x3A3C1E, 0x232416, + 0x6F6F6F, 0xFFF1B8, 0xFFE08A, 0xF4C95D, 0xDDAF37, 0xC49324, 0x9D7118, 0x74500F, 0x493008, 0x4F4F4F, 0xB9F3E8, 0x82DDCF, + 0x4EC3B5, 0x27A497, 0x168479, 0x0E635C, 0x08443F, 0x032622, 0x242424, 0xF4C0A8, 0xE79B7C, 0xD47657, 0xB9563E, 0x963D2D, + 0x722B22, 0x4F1C18, 0x2B0E0D, 0x000000, 0xFFB0A3, 0xFAF3E8, 0xEFE3D2, 0xE2D1B9, 0xD3BFA2, 0xC2A987, 0xAA906F, 0x8D765C, + 0x6F5C49, 0xFF9A89, 0xFFE0C2, 0xF4C29F, 0xDFA57E, 0xC88962, 0xAA6B49, 0x82503A, 0x5B352A, 0x35201B, 0xFF5541, 0x8D8D8D, + 0xA4A4A4, 0x666666, 0xFF3F24, 0xFE3A1D, 0xFE3416, 0xFE2F0E, 0xFE2907, 0xFE2400, 0xF92300, 0xF42300, 0xEF2200, 0xEA2100, + 0xE52101, 0xE02001, 0xDB1F01, 0xD61F01, 0xD11E01, 0xCA1D01, 0xC31C01, 0xBC1B01, 0xB51A01, 0xAD1900, 0xA61800, 0x9F1700, + 0x981600, 0x911500, 0x8C1400, 0x871300, 0x811300, 0x7C1200, 0x771101, 0x721001, 0x6C1001, 0x670F01, 0x620E01, 0x5F0E01, + 0x5C0D01, 0x580D01, 0x550C01, 0x520C00, 0x4F0B00, 0x4B0B00, 0x480A00, 0x450A00, 0xFFB363, 0xFFB261, 0xFFB160, 0xFFAF5E, + 0xFFAE5D, 0xFFAD5B, 0xFFAC5A, 0xFFAA58, 0xFFA957, 0xFFA855, 0xFFA651, 0xFFA34D, 0xFFA14A, 0xFF9F46, 0xFF9C42, 0xFF9A3E, + 0xFF983B, 0xFF9537, 0xFF9333, 0xFF912D, 0xFF9028, 0xFF8E22, 0xFF8C1C, 0xFF8B17, 0xFF8911, 0xFF870B, 0xFF8606, 0xFF8400, + 0xFC8200, 0xF98100, 0xF67F00, 0xF37E00, 0xF07C01, 0xED7B01, 0xEA7901, 0xE77801, 0xE47601, 0xE17401, 0xDD7201, 0xDA7101, + 0xD66F01, 0xD36D01, 0xCF6B01, 0xCC6A01, 0xC86801, 0xC56601, 0xBF6301, 0xB96001, 0xB35C01, 0xAD5901, 0xA65600, 0xA05300, + 0x9A4F00, 0x944C00, 0x8E4900, 0x8C4800, 0x8A4700, 0x884600, 0x864500, 0x834400, 0x814300, 0x7F4200, 0x7D4100, 0x7B4000, + 0xF7E572, 0xF7E46F, 0xF7E36D, 0xF6E36A, 0xF6E268, 0xF6E165, 0xF6E063, 0xF5E060, 0xF5DF5E, 0xF5DE5B, 0xF5DD51, 0xF4DB47, + 0xF4DA3D, 0xF3D833, 0xF3D728, 0xF2D51E, 0xF2D414, 0xF1D20A, 0xF1D100, 0xEFCF00, 0xEDCD00, 0xEBCC01, 0xE9CA01, 0xE7C801, + 0xE5C601, 0xE3C502, 0xE1C302, 0xDFC102, 0xDDBF02, 0xDBBD02, 0xD8BC02, 0xD6BA02, 0xD4B801, 0xD2B601, 0xCFB501, 0xCDB301, + 0xCBB101, 0xC9AF01, 0xC6AD01, 0xC4AA01, 0xC1A801, 0xBFA602, 0xBCA402, 0xBAA102, 0xB79F02, 0xB59D02, 0xB19902, 0xAD9602, + 0xA99202, 0xA58E02, 0xA08B02, 0x9C8702, 0x988302, 0x948002, 0x907C02, 0x8D7A02, 0x8B7802, 0x887602, 0x857402, 0x837102, + 0x806F02, 0x7D6D02, 0x7B6B02, 0x786902, 0xB7E69B, 0xB3E597, 0xAFE393, 0xACE28F, 0xA8E18B, 0xA4DF86, 0xA0DE82, 0x9DDD7E, + 0x99DB7A, 0x95DA76, 0x91D971, 0x8CD76C, 0x88D668, 0x83D463, 0x7FD35E, 0x7AD159, 0x76D055, 0x71CE50, 0x6DCD4B, 0x69CC43, + 0x65CA3A, 0x60C932, 0x5CC72A, 0x58C621, 0x54C419, 0x4FC311, 0x4BC108, 0x47C000, 0x46BE00, 0x46BC00, 0x45BB00, 0x44B900, + 0x44B700, 0x43B500, 0x42B400, 0x42B200, 0x41B000, 0x40AD00, 0x3FAA00, 0x3DA700, 0x3CA400, 0x3BA001, 0x3A9D01, 0x389A01, + 0x379701, 0x369401, 0x349001, 0x338C01, 0x318701, 0x308301, 0x2E7F00, 0x2D7B00, 0x2B7600, 0x2A7200, 0x286E00, 0x276B00, + 0x266700, 0x246400, 0x236000, 0x225D00, 0x215900, 0x1F5600, 0x1E5200, 0x1D4F00, 0xC4F1FF, 0xC1F0FF, 0xBEEFFF, 0xBCEEFF, + 0xB9EDFF, 0xB6EDFF, 0xB3ECFF, 0xB1EBFF, 0xAEEAFF, 0xABE9FF, 0xA6E8FF, 0xA1E6FF, 0x9CE5FF, 0x97E3FF, 0x93E2FF, 0x8EE0FF, + 0x89DFFF, 0x84DDFF, 0x7FDCFF, 0x71D9FF, 0x63D6FF, 0x55D4FF, 0x47D1FF, 0x39CEFF, 0x2BCBFF, 0x1DC9FF, 0x0FC6FF, 0x01C3FF, + 0x01C2FD, 0x01C0FB, 0x01BFF9, 0x01BDF7, 0x00BCF6, 0x00BAF4, 0x00B9F2, 0x00B7F0, 0x00B6EE, 0x00B5EC, 0x00B3EB, 0x00B2E9, + 0x00B1E7, 0x01AFE6, 0x01AEE4, 0x01ADE2, 0x01ABE1, 0x01AADF, 0x01A7DB, 0x01A4D6, 0x02A0D2, 0x029DCE, 0x029AC9, 0x0297C5, + 0x0393C1, 0x0390BC, 0x038DB8, 0x0389B3, 0x0386AF, 0x0282AA, 0x027FA6, 0x027BA1, 0x02789D, 0x017498, 0x017194, 0x016D8F, + 0x91AAFF, 0x8EA8FF, 0x8BA6FF, 0x88A3FF, 0x85A1FF, 0x819FFF, 0x7E9DFF, 0x7B9AFF, 0x7898FF, 0x7596FF, 0x6F90FF, 0x688BFF, + 0x6285FF, 0x5B80FF, 0x557AFF, 0x4E75FF, 0x486FFF, 0x3D69FF, 0x3B64FF, 0x345FFF, 0x2E5BFF, 0x2756FF, 0x2151FF, 0x1A4DFF, + 0x1448FF, 0x0D43FF, 0x073FFF, 0x003AFF, 0x0039FC, 0x0038F8, 0x0138F5, 0x0137F2, 0x0136EE, 0x0135EB, 0x0235E8, 0x0234E4, + 0x0233E1, 0x0232DE, 0x0232DC, 0x0231D9, 0x0231D7, 0x0230D4, 0x0230D2, 0x022FCF, 0x022FCD, 0x022ECA, 0x022DC7, 0x022DC4, + 0x022CC1, 0x022BBE, 0x012BBC, 0x012AB9, 0x0129B6, 0x0129B3, 0x0128B0, 0x0127AD, 0x0127AA, 0x0126A7, 0x0125A4, 0x0025A2, + 0x00249F, 0x00239C, 0x002399, 0x002296, 0xD7B2FF, 0xD3ADFF, 0xCFA8FF, 0xCBA4FF, 0xC79FFF, 0xC29AFF, 0xBE95FF, 0xBA91FF, + 0xB68CFF, 0xB287FF, 0xAF83FF, 0xAD7FFF, 0xAA7CFF, 0xA778FF, 0xA574FF, 0xA270FF, 0x9F6DFF, 0x9D69FF, 0x9A65FF, 0x9861FF, + 0x955CFF, 0x9358FF, 0x9153FF, 0x8E4FFF, 0x8C4AFF, 0x8A46FF, 0x8741FF, 0x853DFF, 0x8436FF, 0x822FFF, 0x8129FF, 0x8022FF, + 0x7E1BFF, 0x7D14FF, 0x7C0EFF, 0x7A07FF, 0x7900FF, 0x7700FB, 0x7500F7, 0x7401F4, 0x7201F0, 0x7001EC, 0x6E01E8, 0x6D02E5, + 0x6A00E3, 0x6902DD, 0x6702D8, 0x6402D3, 0x6202CE, 0x5F02C9, 0x5D01C3, 0x5A01BE, 0x5801B9, 0x5501B4, 0x5301AF, 0x4F01A7, + 0x4B019E, 0x470196, 0x43018E, 0x3F0085, 0x3B007D, 0x370075, 0x33006C, 0x2F0064, + ] + + static let dynamicReferences: [[Int]] = [ + [ + 0, 83, 63, 91, 210, 283, 401, 484, + ], + [ + 0, 84, 63, 100, 118, 155, 191, 210, 246, 292, 310, 338, + 411, 447, 492, 511, + ], + [ + 0, 18, 85, 63, 64, 82, 91, 118, 128, 155, 173, 182, + 201, 210, 237, 255, 265, 283, 310, 319, 320, 347, 374, 383, + 393, 411, 429, 447, 448, 457, 475, 511, + ], + [ + 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, + 100, 109, 118, 127, 128, 137, 146, 155, 164, 173, 182, 191, + 192, 201, 210, 219, 228, 237, 246, 255, 256, 265, 274, 283, + 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383, + 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, + 484, 493, 502, 511, + ], + [ + 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, + 100, 109, 118, 127, 128, 137, 146, 155, 164, 173, 182, 191, + 192, 201, 210, 219, 228, 237, 246, 255, 256, 265, 274, 283, + 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383, + 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, + 484, 493, 502, 511, 1, 2, 3, 4, 5, 6, 7, 8, + 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, + 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35, + 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, + 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 61, 62, + 65, 66, 67, 68, 69, 70, 71, 72, + ], + [ + 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, + 100, 109, 118, 127, 128, 137, 146, 155, 164, 173, 182, 191, + 192, 201, 210, 219, 228, 237, 246, 255, 256, 265, 274, 283, + 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383, + 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, + 484, 493, 502, 511, 1, 2, 3, 4, 5, 6, 7, 8, + 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, + 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35, + 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, + 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 61, 62, + 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, + 78, 79, 80, 81, 83, 84, 85, 86, 87, 88, 89, 90, + 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, + 105, 106, 107, 108, 110, 111, 112, 113, 114, 115, 116, 117, + 119, 120, 121, 122, 123, 124, 125, 126, 129, 130, 131, 132, + 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 144, 145, + 147, 148, 149, 150, 151, 152, 153, 154, 156, 157, 158, 159, + 160, 161, 162, 163, 165, 166, 167, 168, 169, 170, 171, 172, + 174, 175, 176, 177, 178, 179, 180, 181, 183, 184, 185, 186, + 187, 188, 189, 190, 193, 194, 195, 196, 197, 198, 199, 200, + 202, 203, 204, 205, 206, 207, 208, 209, 211, 212, 213, 214, + 215, 216, 217, 218, + ], + [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, + 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, + 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, + 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, + 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, + 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, + 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, + 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, + 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, + 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, + 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, + 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, + 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, + 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, + 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, + 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, + 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, + 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, + 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, + 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, + 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, + 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, + 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, + 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, + 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, + 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, + 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, + 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, + 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, + 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, + 504, 505, 506, 507, 508, 509, 510, 511, + ], + ] +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift new file mode 100644 index 0000000000..3f2d796798 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift @@ -0,0 +1,47 @@ +public enum MCOImagePalette { + public static let profileCount = 16 + public static let firstDynamicProfile = 9 + public static let dynamic512Profile = 15 + + public static func count(profile: Int) -> Int { + guard (0.. [UInt32] { + profileReferences(profile).map { color($0, profile: profile) } + } + + public static func color(_ reference: Int, profile: Int) -> UInt32 { + if profile >= firstDynamicProfile { + return global512.indices.contains(reference) ? global512[reference] : 0 + } + guard fixed.indices.contains(profile), fixed[profile].indices.contains(reference) else { return 0 } + return fixed[profile][reference] + } + + public static func white(profile: Int) -> Int { 0 } + + public static func black(profile: Int) -> Int { + guard (0..= firstDynamicProfile ? 63 : [1, 3, 2, 2, 3, 7, 15, 31, 7][profile] + } + + public static func ref(fromStored value: Int, profile: Int) throws -> Int { + let refs = profileReferences(profile) + guard refs.indices.contains(value) else { throw MCOImageCodecError.damaged } + return refs[value] + } + + public static func stored(fromRef value: Int, profile: Int) throws -> Int { + guard let index = profileReferences(profile).firstIndex(of: value) else { throw MCOImageCodecError.damaged } + return index + } + + static func profileReferences(_ profile: Int) -> [Int] { + guard (0..= firstDynamicProfile ? dynamicReferences[profile - firstDynamicProfile] : Array(fixed[profile].indices) + } + + static func bits(_ profile: Int) -> Int { MCOImageBitReader.width(count(profile: profile) - 1) } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageRaster.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageRaster.swift new file mode 100644 index 0000000000..52df23789f --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageRaster.swift @@ -0,0 +1,17 @@ +/// A decoded MCOimg raster. Dynamic profiles use global512 color references; +/// fixed profiles use indexes within their profile palette. +public struct MCOImageRaster: Sendable, Hashable { + public let width: Int + public let height: Int + public let profile: Int + public let pixels: [Int] + public let transparentColor: Int? + + public init(width: Int, height: Int, profile: Int, pixels: [Int], transparentColor: Int? = nil) { + self.width = width + self.height = height + self.profile = profile + self.pixels = pixels + self.transparentColor = transparentColor + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift new file mode 100644 index 0000000000..bf86400dd3 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift @@ -0,0 +1,54 @@ +extension MCOImageV3Codec.Decoder { + mutating func bitplanes(count: Int, palette: [Int], adaptive: Bool) throws -> [Int] { + var pixels = Array(repeating: 0, count: count) + for bit in 0.. Int { + for length in 1...3 { + guard remaining >= length else { throw MCOImageCodecError.damaged } + if try reader.read(1) == 0 { return length } + } + guard remaining >= 4 else { throw MCOImageCodecError.damaged } + return try reader.range(remaining - 4) + 4 + } + + mutating func sparseBitplane(_ pixels: inout [Int], bit: Int, value: Bool) throws { + let count = try reader.range(pixels.count - 1) + 1 + var previous = -1 + for index in 0.. [Int] { + let count = width * height + let rowLength = scan == 1 || scan == 3 ? height : width + if sharedPalette != nil && (algorithm == .rawGlobal || algorithm == .directBitplanes || algorithm == .directRowDelta) { + throw MCOImageCodecError.damaged + } + if algorithm == .rawGlobal { return try (0..= MCOImagePalette.firstDynamicProfile else { throw MCOImageCodecError.damaged } + let palette = MCOImagePalette.profileReferences(profile) + if algorithm == .directBitplanes { return try bitplanes(count: count, palette: palette, adaptive: true) } + return try mapLocal(compactRows(count: count, rowLength: rowLength, valueBits: MCOImagePalette.bits(profile), + maximum: palette.count - 1, residuals: grayscale), palette: palette) + } + let background = try algorithm == .sparse || algorithm == .varSparse ? (inheritedBackground ?? self.background()) : nil + let palette = try sharedPalette ?? localPalette() + let bits = MCOImageBitReader.width(palette.count - 1) + switch algorithm { + case .rawLocal: + return try mapLocal((0.. [Int] { + try indexes.map { index in + guard palette.indices.contains(index) else { throw MCOImageCodecError.damaged } + return palette[index] + } + } + + mutating func rle(count: Int, palette: [Int], variable: Bool) throws -> [Int] { + let bits = MCOImageBitReader.width(palette.count - 1) + var result: [Int] = [] + while result.count < count { + let index = try reader.read(bits) + let length = try variable ? reader.varUint() : reader.bounded(count - result.count - 1) + 1 + guard palette.indices.contains(index), length > 0, length <= count - result.count else { throw MCOImageCodecError.damaged } + result.append(contentsOf: repeatElement(palette[index], count: length)) + } + return result + } + + mutating func sparse(count: Int, palette: [Int], background: Int, variable: Bool) throws -> [Int] { + let bits = MCOImageBitReader.width(palette.count - 1) + let segments = try variable ? reader.varUint() : reader.bounded(count - 1) + 1 + guard segments > 0, segments <= count else { throw MCOImageCodecError.damaged } + var result = Array(repeating: background, count: count) + var position = 0 + for _ in 0.. 0, length <= count - position else { + throw MCOImageCodecError.damaged + } + for offset in 0.. [Int] { + let minimumMatch = 3 + let bits = MCOImageBitReader.width(palette.count - 1) + var result: [Int] = [] + while result.count < count { + if try reader.read(1) != 0 { + let remaining = count - result.count + guard !result.isEmpty, remaining >= minimumMatch else { throw MCOImageCodecError.damaged } + let distance = try reader.range(result.count - 1) + 1 + let length = try reader.range(remaining - minimumMatch) + minimumMatch + for _ in 0.. 1 || bounds.height > 1 else { throw MCOImageCodecError.damaged } + let widths = bounds.width == 1 ? [1] : [bounds.width / 2, bounds.width - bounds.width / 2] + let heights = bounds.height == 1 ? [1] : [bounds.height / 2, bounds.height - bounds.height / 2] + var y = bounds.y + for height in heights { + var x = bounds.x + for width in widths { + try quadtree(&pixels, stride: stride, bounds: Bounds(x: x, y: y, width: width, height: height), palette: palette) + x += width + } + y += height + } + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+CompactRows.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+CompactRows.swift new file mode 100644 index 0000000000..ad48e953a4 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+CompactRows.swift @@ -0,0 +1,81 @@ +extension MCOImageV3Codec.Decoder { + mutating func compactRows(count: Int, rowLength: Int, valueBits: Int, maximum: Int, residuals: Bool) throws -> [Int] { + let virtual = try reader.read(1) != 0 + var pixels = Array(repeating: 0, count: count) + if !virtual { for x in 0.. [Int] { + var positions: [Int] = [] + if op == 2 || op == 3 { + let count = try reader.range(rowLength - 1) + 1 + var previous = -1 + for index in 0.. Int { + if !residual { return try rowValue(bits, maximum: maximum) } + let code = try reader.compact() + 1 + let delta = code & 1 == 1 ? (code + 1) / 2 : -(code / 2) + let value = base + delta + guard value >= 0, value <= maximum else { throw MCOImageCodecError.damaged } + return value + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Containers.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Containers.swift new file mode 100644 index 0000000000..5a1a53bdd7 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Containers.swift @@ -0,0 +1,109 @@ +import Foundation + +extension MCOImageV3Codec.Decoder { + mutating func color() throws -> Int { + try MCOImagePalette.ref(fromStored: reader.read(MCOImagePalette.bits(profile)), profile: profile) + } + + mutating func background() throws -> Int { try implicitWhite ? MCOImagePalette.white(profile: profile) : color() } + + mutating func pixels(container: MCOImageV3Codec.Container, algorithm: MCOImageV3Codec.Algorithm, scan: Int, context: Int) throws -> [Int] { + switch container { + case .block, .compactBlock: + return MCOImageV3Codec.fromScan(try block(width: width, height: height, algorithm: algorithm, scan: scan), width: width, height: height, scan: scan) + case .boundsBlock, .compactBoundsBlock: + let background = try background() + let bounds = try geometry(compact: container == .compactBoundsBlock) + let linear = try block(width: bounds.width, height: bounds.height, algorithm: algorithm, scan: scan, background: background) + var result = Array(repeating: background, count: width * height) + place(linear, in: bounds, scan: scan, result: &result) + return result + case .regions, .compactRegions: + return try regions(count: context + 1, compact: container == .compactRegions) + case .solid: + if implicitWhite { + guard context == 0 else { throw MCOImageCodecError.damaged } + return Array(repeating: MCOImagePalette.white(profile: profile), count: width * height) + } + let bits = MCOImagePalette.bits(profile) + let lowBits = min(bits, MCOImageV3Codec.containerShift) + guard context < 1 << lowBits else { throw MCOImageCodecError.damaged } + let ref = try context | reader.read(bits - lowBits) << lowBits + return Array(repeating: try MCOImagePalette.ref(fromStored: ref, profile: profile), count: width * height) + case .solidRects: + let background = try background() + let palette = try localPalette() + let bits = MCOImageBitReader.width(palette.count - 1) + let count = try context + (reader.read(1) << MCOImageV3Codec.containerShift) + 1 + var result = Array(repeating: background, count: width * height) + for _ in 0.. [Int] { + let background = try background() + let common = try compact && reader.read(1) != 0 + let delta = try compact && reader.read(1) != 0 + let shared = try compact && reader.read(1) != 0 + var commonAlgorithm: MCOImageV3Codec.Algorithm = .rawGlobal + var commonScan = 0 + var hybrid = false + if common { + let algorithmID = try reader.read(5) + hybrid = algorithmID == MCOImageV3Codec.contextMask + commonAlgorithm = try readAlgorithm(hybrid ? reader.read(5) : algorithmID) + commonScan = try commonAlgorithm.compact ? 0 : reader.read(2) + } + let palette = try shared ? localPalette() : nil + var result = Array(repeating: background, count: width * height) + var previous: Bounds? + for _ in 0.. MCOImageV3Codec.Algorithm { + guard let algorithm = MCOImageV3Codec.Algorithm(rawValue: value) else { throw MCOImageCodecError.unsupported } + return algorithm + } + + mutating func geometry(compact: Bool) throws -> Bounds { + let x = try reader.read(compact ? MCOImageBitReader.width(width - 1) : 8) + let y = try reader.read(compact ? MCOImageBitReader.width(height - 1) : 8) + guard x < width, y < height else { throw MCOImageCodecError.damaged } + let rectWidth = try reader.read(compact ? MCOImageBitReader.width(width - x - 1) : 8) + 1 + let rectHeight = try reader.read(compact ? MCOImageBitReader.width(height - y - 1) : 8) + 1 + guard x + rectWidth <= width, y + rectHeight <= height else { throw MCOImageCodecError.damaged } + return Bounds(x: x, y: y, width: rectWidth, height: rectHeight) + } + + mutating func deltaGeometry(_ previous: Bounds) throws -> Bounds { + let bounds = try Bounds(x: previous.x + reader.signed(), y: previous.y + reader.signed(), + width: previous.width + reader.signed(), height: previous.height + reader.signed()) + guard bounds.x >= 0, bounds.y >= 0, bounds.width > 0, bounds.height > 0, + bounds.x + bounds.width <= width, bounds.y + bounds.height <= height else { throw MCOImageCodecError.damaged } + return bounds + } + + func place(_ linear: [Int], in bounds: Bounds, scan: Int, result: inout [Int]) { + let pixels = MCOImageV3Codec.fromScan(linear, width: bounds.width, height: bounds.height, scan: scan) + for row in 0.. Data { + guard (1...maximumDimension).contains(image.width), (1...maximumDimension).contains(image.height), + (0..> containerShift, max(0, MCOImagePalette.bits(image.profile) - containerShift)) } + return writer.data + } + let fullBounds = Decoder.Bounds(x: 0, y: 0, width: image.width, height: image.height) + try addBlockCandidates(image, nonce: nonce, pixels: image.pixels, bounds: fullBounds, background: nil, candidates: &candidates) + let counts = Dictionary(image.pixels.map { ($0, 1) }, uniquingKeysWith: +) + let backgrounds = palette.sorted { counts[$0, default: 0] > counts[$1, default: 0] }.prefix(maximumBackgroundCandidates) + for background in backgrounds { + for scan in 0.. MCOImageBitWriter { + var writer = MCOImageBitWriter() + writer.write(Int(nonce), byteBits) + writer.write(image.profile | (scan << scanShift) | (implicit ? implicitWhiteFlag : 0) | (image.transparentColor == nil ? 0 : transparentFlag), byteBits) + writeDimensions(image.width, image.height, writer: &writer) + writer.write((container.rawValue << containerShift) | context, byteBits) + if let transparent = image.transparentColor { try writeColor(transparent, profile: image.profile, writer: &writer) } + return writer + } + + private static func writeDimensions(_ width: Int, _ height: Int, writer: inout MCOImageBitWriter) { + if width == height && width <= mediumDimensionLimit { writer.write(0, dimensionModeBits); writer.write(width - 1, squareDimensionBits) } else if width <= smallDimensionLimit && height <= smallDimensionLimit { + writer.write(1, dimensionModeBits); writer.write(width - 1, smallDimensionBits); writer.write(height - 1, smallDimensionBits) + } else if width <= mediumDimensionLimit && height <= mediumDimensionLimit { + writer.write(2, dimensionModeBits); writer.write(width - 1, squareDimensionBits); writer.write(height - 1, squareDimensionBits) + } else { + writer.write(3, dimensionModeBits); writer.write(width == height ? 0 : 1, 1); writer.write(width - 1, extendedDimensionBits) + if width != height { writer.write(height - 1, extendedDimensionBits) } + } + } + + private static func writeColor(_ color: Int, profile: Int, writer: inout MCOImageBitWriter) throws { + writer.write(try MCOImagePalette.stored(fromRef: color, profile: profile), MCOImagePalette.bits(profile)) + } + + private static func writePalette(_ palette: [Int], profile: Int, writer: inout MCOImageBitWriter) throws { + if MCOImagePalette.count(profile: profile) <= 64 { writer.write(0, 1); writer.write(palette.count - 1, MCOImagePalette.bits(profile)) } else if palette.count <= 64 { + writer.write(0, 1); writer.write(palette.count - 1, 6) + } else if palette.count <= 128 { + writer.write(1, 2); writer.write(palette.count - 65, 6) + } else if palette.count <= 384 { + writer.write(3, 3); writer.write(palette.count - 129, 8) + } else { writer.write(7, 4); writer.write(palette.count - 385, 7) } + for color in palette { try writeColor(color, profile: profile, writer: &writer) } + } + + private static func writeBlock(_ pixels: [Int], profile: Int, algorithm: Algorithm, rowLength: Int, writer: inout MCOImageBitWriter) throws { + if algorithm == .rawGlobal { + for color in pixels { try writeColor(color, profile: profile, writer: &writer) } + return + } + let palette = Array(Set(pixels)).sorted() + try writePalette(palette, profile: profile, writer: &writer) + let local = Dictionary(uniqueKeysWithValues: palette.enumerated().map { ($1, $0) }) + let indexes = pixels.map { local[$0]! } + let bits = MCOImageBitReader.width(palette.count - 1) + if algorithm == .rle { + var position = 0 + while position < indexes.count { + var end = position + 1 + while end < indexes.count && indexes[end] == indexes[position] { end += 1 } + writer.write(indexes[position], bits) + writer.bounded(end - position - 1, indexes.count - position - 1) + position = end + } + } else if algorithm == .rowRepeat { + for row in 0..<(indexes.count / rowLength) { + let start = row * rowLength + let same = row > 0 && indexes[start..<(start + rowLength)].elementsEqual(indexes[(start - rowLength).. 0 { writer.write(same ? 1 : 0, 1) } + if !same { for index in indexes[start..<(start + rowLength)] { writer.write(index, bits) } } + } + } else { for index in indexes { writer.write(index, bits) } } + } + + private static func writeSparse(_ pixels: [Int], background: Int, profile: Int, writer: inout MCOImageBitWriter) throws { + let palette = Array(Set(pixels).subtracting([background])).sorted() + try writePalette(palette, profile: profile, writer: &writer) + let local = Dictionary(uniqueKeysWithValues: palette.enumerated().map { ($1, $0) }) + var runs: [(start: Int, length: Int, color: Int)] = [] + var position = 0 + while position < pixels.count { + if pixels[position] == background { position += 1; continue } + var end = position + 1 + while end < pixels.count && pixels[end] == pixels[position] { end += 1 } + runs.append((position, end - position, pixels[position])) + position = end + } + writer.bounded(runs.count - 1, pixels.count - 1) + position = 0 + for run in runs { + writer.bounded(run.start - position, pixels.count - position - 1) + writer.write(local[run.color]!, MCOImageBitReader.width(palette.count - 1)) + writer.bounded(run.length - 1, pixels.count - run.start - 1) + position = run.start + run.length + } + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift new file mode 100644 index 0000000000..82307cc86a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift @@ -0,0 +1,102 @@ +extension MCOImageV3Codec.Decoder { + mutating func localPalette() throws -> [Int] { + let size = MCOImagePalette.count(profile: profile) + let count: Int + var descriptor: Int? + if size <= 64 { + if try reader.read(1) != 0 { descriptor = try reader.read(2); count = 0 } else { + count = try reader.read(MCOImagePalette.bits(profile)) + 1 + } + } else { + switch try reader.prefix(limit: 4) { + case 0: count = try reader.read(6) + 1 + case 1: count = try reader.read(6) + 65 + case 2: count = try reader.read(8) + 129 + case 3: count = try reader.read(7) + 385 + default: descriptor = try reader.read(2); count = 0 + } + } + let refs: [Int] + if let descriptor { + refs = try paletteDescriptor(descriptor, size: size) + } else { + guard count <= size else { throw MCOImageCodecError.damaged } + refs = try (0.. Int { + let size = MCOImagePalette.count(profile: profile) + if size <= 64 { return try reader.read(MCOImagePalette.bits(profile)) + 1 } + let prefix = try reader.prefix(limit: 2) + if prefix == 0 { return try reader.read(6) + 1 } + if prefix == 1 { return try reader.read(6) + 65 } + guard size > 128 else { throw MCOImageCodecError.damaged } + let count = try reader.read(MCOImageBitReader.width(size - 129)) + 129 + guard count <= size else { throw MCOImageCodecError.damaged } + return count + } + + mutating func paletteDescriptor(_ descriptor: Int, size: Int) throws -> [Int] { + var refs: [Int] = [] + switch descriptor { + case 0: + for ref in 0.. previousEnd, end < size, refs.count + length <= size else { throw MCOImageCodecError.damaged } + refs.append(contentsOf: start...end) + previousEnd = end + } + default: + guard profile == MCOImagePalette.dynamic512Profile else { throw MCOImageCodecError.damaged } + return try reader.read(1) == 0 ? bankBitmap() : orderedBanks() + } + return refs + } + + mutating func bankBitmap() throws -> [Int] { + let bankMask = try reader.read(8) + guard bankMask != 0 else { throw MCOImageCodecError.damaged } + var refs: [Int] = [] + for bank in 0..<8 where bankMask & (1 << bank) != 0 { + let before = refs.count + for offset in 0..<64 { if try reader.read(1) != 0 { refs.append((bank << 6) | offset) } } + guard refs.count > before else { throw MCOImageCodecError.damaged } + } + return refs + } + + mutating func orderedBanks() throws -> [Int] { + let count = try paletteLength() + if try reader.read(1) == 0 { + guard count <= 64 else { throw MCOImageCodecError.damaged } + let bank = try reader.read(3) + return try (0.. 1, count <= banks.count * 64 else { throw MCOImageCodecError.damaged } + var used: Set = [] + var refs: [Int] = [] + for _ in 0.. Int { + let value = try reader.read(bits) + guard value <= maximum else { throw MCOImageCodecError.damaged } + return value + } + + mutating func predictor(row: Int, virtual: Bool, enabled: Bool = true) throws -> Int { + let value = try !enabled || reader.read(1) == 0 ? 0 : reader.read(1) + 1 + guard row != 0 || !virtual || value == 0 else { throw MCOImageCodecError.damaged } + return value + } + + func predicted(_ pixels: [Int], row: Int, x: Int, rowLength: Int, predictor: Int, virtual: Bool) -> Int { + if row == 0 && virtual { return 0 } + let previousX = predictor == 1 ? (x + rowLength - 1) % rowLength : predictor == 2 ? (x + 1) % rowLength : x + return pixels[(row - 1) * rowLength + previousX] + } + + func copyRow(_ pixels: inout [Int], row: Int, rowLength: Int, predictor: Int = 0, virtual: Bool) { + for x in 0.. [Int] { + var pixels = Array(repeating: 0, count: count) + for x in 0.. [Int] { + let virtual = try reader.read(1) != 0 + let shifted = try reader.read(1) != 0 + var pixels = Array(repeating: 0, count: count) + if !virtual { for x in 0.. previous else { throw MCOImageCodecError.damaged } + pixels[start + x] = try rowValue(valueBits, maximum: maximum) + previous = x + } + } else { + let extended = try reader.read(2) + if extended == 3 { + let repeats = try reader.range(rowCount - row - 2) + 2 + for index in row..<(row + repeats) { copyRow(&pixels, row: index, rowLength: rowLength, virtual: virtual) } + row += repeats + continue + } + let prediction = try predictor(row: row, virtual: virtual, enabled: shifted) + copyRow(&pixels, row: row, rowLength: rowLength, predictor: prediction, virtual: virtual) + if extended == 1 { + try legacySegments(&pixels, start: start, rowLength: rowLength, bits: valueBits, maximum: maximum) + row += 1 + continue + } + let positions = try legacyPositions(rowLength: rowLength) + if extended == 2 { + let value = try rowValue(valueBits, maximum: maximum) + for x in positions { pixels[start + x] = value } + } else { + for x in positions { pixels[start + x] = try rowValue(valueBits, maximum: maximum) } + } + } + row += 1 + } + return pixels + } + + mutating func legacyPositions(rowLength: Int) throws -> [Int] { + var positions: [Int] = [] + for x in 0.. previousEnd, x + length <= rowLength else { throw MCOImageCodecError.damaged } + for offset in x..<(x + length) { pixels[start + offset] = try rowValue(bits, maximum: maximum) } + previousEnd = x + length - 1 + } + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift new file mode 100644 index 0000000000..bbcf05634b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift @@ -0,0 +1,135 @@ +import Foundation + +/// `decodeBody` keeps the leading packet nonce; `decodeBodyWithoutPacketNonce` starts at the header. +public enum MCOImageV3Codec { + static let maximumDimension = 256 + static let scanCount = 4 + static let maximumBackgroundCandidates = 4 + static let smallDimensionLimit = 32 + static let mediumDimensionLimit = 64 + static let dimensionModeBits = 2 + static let squareDimensionBits = 6 + static let smallDimensionBits = 5 + static let extendedDimensionBits = 8 + static let byteBits = 8 + static let transparentFlag = 0x80 + static let implicitWhiteFlag = 0x40 + static let profileMask = 0x0F + static let scanShift = 4 + static let containerShift = 5 + static let contextMask = 31 + + enum Container: Int { + case block = 0, compactBlock = 1, boundsBlock = 2, compactBoundsBlock = 3 + case regions = 4, compactRegions = 5, solid = 6, solidRects = 7 + } + + enum Algorithm: Int { + case rawGlobal = 0, rawLocal = 1, rle = 2, sparse = 3, biColor = 4, rowRepeat = 5, lz = 6, quadtree = 7 + case bitplanes = 8, adaptiveBitplanes = 9, directBitplanes = 10, compactRowDelta = 11, directRowDelta = 12, rowDelta = 13 + case varRle = 14, varSparse = 15 + + var compact: Bool { self == .rawGlobal || self == .rawLocal || self == .biColor } + var usesBackground: Bool { self == .sparse || self == .varSparse || self == .biColor } + } + + struct Decoder { + var reader: MCOImageBitReader + let width: Int + let height: Int + let profile: Int + let implicitWhite: Bool + + struct Bounds { + let x: Int + let y: Int + let width: Int + let height: Int + } + } + + public static func decodeBody(_ body: Data) throws -> MCOImageRaster { + try decode(body, hasNonce: true) + } + + public static func decodeBodyWithoutPacketNonce(_ body: Data) throws -> MCOImageRaster { + try decode(body, hasNonce: false) + } + + private static func decode(_ body: Data, hasNonce: Bool) throws -> MCOImageRaster { + let offset = hasNonce ? 1 : 0 + guard body.count >= offset + 3 else { throw MCOImageCodecError.damaged } + let header = Int(body[body.startIndex + offset]) + let profile = header & profileMask + let scan = (header >> scanShift) & 3 + let implicitWhite = header & implicitWhiteFlag != 0 + var reader = MCOImageBitReader(body, byteOffset: offset + 1) + let (width, height) = try readDimensions(&reader) + let containerByte = try reader.read(byteBits) + guard let container = Container(rawValue: containerByte >> containerShift) else { throw MCOImageCodecError.unsupported } + let context = containerByte & contextMask + let isBlock = container.rawValue <= Container.compactBoundsBlock.rawValue + guard let algorithm = Algorithm(rawValue: isBlock ? context : 0) else { throw MCOImageCodecError.unsupported } + if container == .block && algorithm.compact || container == .compactBlock && !algorithm.compact { + throw MCOImageCodecError.damaged + } + let requiresHorizontal = container == .compactBlock || container.rawValue >= Container.regions.rawValue + || container == .compactBoundsBlock && algorithm.compact || algorithm == .quadtree + guard !requiresHorizontal || scan == 0 else { throw MCOImageCodecError.damaged } + guard !implicitWhite || container.rawValue >= Container.boundsBlock.rawValue || algorithm.usesBackground else { + throw MCOImageCodecError.damaged + } + var decoder = Decoder(reader: reader, width: width, height: height, profile: profile, implicitWhite: implicitWhite) + let transparent = try header & transparentFlag != 0 ? decoder.color() : nil + let pixels = try decoder.pixels(container: container, algorithm: algorithm, scan: scan, context: context) + try decoder.reader.finish() + return MCOImageRaster(width: width, height: height, profile: profile, pixels: pixels, transparentColor: transparent) + } + + static func readDimensions(_ reader: inout MCOImageBitReader) throws -> (Int, Int) { + let mode = try reader.read(dimensionModeBits) + let width: Int + let height: Int + switch mode { + case 0: + width = try reader.read(squareDimensionBits) + 1 + height = width + case 1: + width = try reader.read(smallDimensionBits) + 1 + height = try reader.read(smallDimensionBits) + 1 + guard width != height else { throw MCOImageCodecError.damaged } + case 2: + width = try reader.read(squareDimensionBits) + 1 + height = try reader.read(squareDimensionBits) + 1 + guard width != height, width > smallDimensionLimit || height > smallDimensionLimit else { throw MCOImageCodecError.damaged } + default: + let rectangle = try reader.read(1) != 0 + width = try reader.read(extendedDimensionBits) + 1 + height = try rectangle ? reader.read(extendedDimensionBits) + 1 : width + guard rectangle ? width != height && (width > mediumDimensionLimit || height > mediumDimensionLimit) : width > mediumDimensionLimit else { throw MCOImageCodecError.damaged } + } + return (width, height) + } + + static func scanIndexes(width: Int, height: Int, scan: Int) -> [Int] { + if scan == 0 { return Array(0..<(width * height)) } + var indexes: [Int] = [] + let vertical = scan == 1 || scan == 3 + let outer = vertical ? width : height + let inner = vertical ? height : width + for major in 0..= 2 && major % 2 != 0 ? inner - minor - 1 : minor + indexes.append(vertical ? coordinate * width + major : major * width + coordinate) + } + } + return indexes + } + + static func fromScan(_ linear: [Int], width: Int, height: Int, scan: Int) -> [Int] { + if scan == 0 { return linear } + var result = Array(repeating: 0, count: linear.count) + for (position, index) in scanIndexes(width: width, height: height, scan: scan).enumerated() { result[index] = linear[position] } + return result + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift new file mode 100644 index 0000000000..906fb7aee9 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift @@ -0,0 +1,65 @@ +import Foundation + +struct MCOImageV4BitReader { + private let bytes: [UInt8] + private(set) var offset = 0 + private static let bitsPerByte = 8 + private static let varUIntBytes = 5 + private static let varUIntPayloadBits = 7 + private static let varUIntPayloadMask = 0x7f + private static let varUIntContinuation = 0x80 + + init(_ data: Data) { bytes = Array(data) } + + var remaining: Int { bytes.count * Self.bitsPerByte - offset } + + mutating func read(_ bits: Int) throws -> Int { + guard bits >= 0, bits <= Int.bitWidth - 1, bits <= remaining else { throw MCOImageCodecError.damaged } + var value = 0 + for shift in 0..> (offset % Self.bitsPerByte)) & 1) << shift + offset += 1 + } + return value + } + + mutating func bit() throws -> Bool { try read(1) != 0 } + + mutating func signed(_ bits: Int) throws -> Int { + let value = try read(bits) + return value & 1 == 0 ? value >> 1 : -(value >> 1) - 1 + } + + mutating func compact() throws -> Int { + if try !bit() { return try read(2) } + if try !bit() { return try read(4) + 4 } + if try !bit() { return try read(8) + 20 } + let value = try varUInt() + guard value > 275 else { throw MCOImageCodecError.damaged } + return value + } + + mutating func varUInt() throws -> Int { + var value = 0 + for index in 0.. Data { + guard count >= 0, count <= remaining / Self.bitsPerByte else { throw MCOImageCodecError.damaged } + return Data(try (0.. Data { + let image = try MCOImageV3Codec.decodeBody(body) + let field = MCOImageV4Parser.Field.self + let mixedMode = 1 + let rasterExtension = 14 + let headerBits = 4 + var writer = MCOImageBitWriter() + writer.write(mixedMode, field.modeBits) + writer.write(image.profile, field.profileBits) + writeRasterDimensions(image.width, image.height, writer: &writer) + writer.write(image.transparentColor == nil ? 0 : 1, 1) + if image.transparentColor != nil { writer.write(0, 1) } + writer.write(MCOImageV4Parser.Opcode.extended.rawValue, field.opcodeBits) + writer.write(rasterExtension, field.opcodeBits) + for size in [image.width, image.height] { + let margin = min(field.maximumOverscan, max(1, (size + field.overscanDivisor - 1) / field.overscanDivisor)) + writer.write(margin, MCOImageV4Parser.bits(size + 2 * margin - 1)) + } + let bytes = Array(body) + writer.write(Int(bytes[1]) >> headerBits, headerBits) + writer.compact(bytes.count - 2) + for byte in bytes.dropFirst(2) { writer.write(Int(byte), field.byteBits) } + writer.write(MCOImageV4Parser.Opcode.end.rawValue, field.opcodeBits) + return Data([bytes[0]]) + writer.data + } + + private static func writeRasterDimensions(_ width: Int, _ height: Int, writer: inout MCOImageBitWriter) { + let field = MCOImageV4Parser.Field.self + let squareMode = 0, smallMode = 1, mediumMode = 2, extendedMode = 3 + if width == height && width <= field.mediumDimensionMaximum { + writer.write(squareMode, field.modeBits) + writer.write(width - 1, field.mediumDimensionBits) + } else if max(width, height) <= field.smallDimensionMaximum { + writer.write(smallMode, field.modeBits) + writer.write(width - 1, field.smallDimensionBits) + writer.write(height - 1, field.smallDimensionBits) + } else if max(width, height) <= field.mediumDimensionMaximum { + writer.write(mediumMode, field.modeBits) + writer.write(width - 1, field.mediumDimensionBits) + writer.write(height - 1, field.mediumDimensionBits) + } else { + writer.write(extendedMode, field.modeBits) + writer.write(width == height ? 0 : 1, 1) + writer.write(width - 1, field.byteBits) + if width != height { writer.write(height - 1, field.byteBits) } + } + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Codec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Codec.swift new file mode 100644 index 0000000000..36f540f622 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Codec.swift @@ -0,0 +1,9 @@ +import Foundation + +public enum MCOImageV4Codec { + public static func decodeBody(_ body: Data) throws -> MCOImageV4Document { + guard !body.isEmpty else { throw MCOImageCodecError.damaged } + var parser = MCOImageV4Parser(Data(body.dropFirst())) + return try parser.decode() + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Document.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Document.swift new file mode 100644 index 0000000000..fa760d8116 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Document.swift @@ -0,0 +1,9 @@ +public struct MCOImageV4Document: Sendable, Hashable { + public let width: Int + public let height: Int + public let profile: Int + public let backgroundColor: Int? + public let figures: [MCOImageFigure] + public let targetName: String? + public let replyTimestamp: UInt32? +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Extended.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Extended.swift new file mode 100644 index 0000000000..003b4979ae --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Extended.swift @@ -0,0 +1,135 @@ +import Foundation + +extension MCOImageV4Parser { + private enum Extended: Int { + case lineDelta = 0, lineAxisDelta = 1, areaDelta = 2, waveDelta = 3, pathOrthogonal = 4 + case pathBounds = 5, pathBoundsDelta = 6, lineAxis = 7, ellipseDepth = 8, repeatBack = 9 + case dots = 10, style = 11, repeatColors = 12, group = 13, raster = 14, escape = 15 + } + + mutating func extended( + history: [MCOImageFigure], nested: Bool, + style: inout MCOImageV4Style, alignment: inout Int, fontSize: inout Int + ) throws -> [MCOImageFigure] { + let opcode = Extended(rawValue: try reader.read(Field.opcodeBits))! + switch opcode { + case .style, .repeatBack, .repeatColors, .dots, .group: break + default: try consume(1) + } + switch opcode { + case .style: + let fillMask = 1 + let strokeMask = 2 + let widthMask = 4 + let maskBits = 3 + let mask = try reader.read(maskBits) + guard mask != 0 else { throw MCOImageCodecError.damaged } + if mask & fillMask != 0 { style.fillColor = try optionalColor() } + if mask & strokeMask != 0 { style.strokeColor = try optionalColor() } + if mask & widthMask != 0 { style.strokeWidth = try reader.read(scalarBits) + 1 } + return [] + case .lineDelta: + let points = try pointSequence(count: 2) + return [.line(points[0], points[1], style)] + case .lineAxisDelta: + let vertical = try reader.bit() + let bits = try Field.shortWidths[reader.read(Field.shortSelectorBits)] + let start = try point() + let delta = try reader.signed(bits) + return [.line(start, start.translated(x: vertical ? 0 : delta, y: vertical ? delta : 0), style)] + case .lineAxis: + let vertical = try reader.bit() + let first = try coordinate(size: vertical ? width : height, bits: vertical ? xBits : yBits) + let start = try coordinate(size: vertical ? height : width, bits: vertical ? yBits : xBits) + let end = try coordinate(size: vertical ? height : width, bits: vertical ? yBits : xBits) + return [.line(MCOImageV4Point(x: vertical ? first : start, y: vertical ? start : first), + MCOImageV4Point(x: vertical ? first : end, y: vertical ? end : first), style)] + case .areaDelta: + let ellipse = try reader.bit() + let points = try pointSequence(count: 3) + return [ellipse ? .ellipse(points[0], points[1], points[2], style) : .rectangle(points[0], points[1], points[2], style)] + case .waveDelta: + let closed = try reader.bit() + let depth = try depth() + let points = try pointSequence(count: 2) + return [.wave(points[0], points[1], depth: depth, closed: closed, style)] + case .ellipseDepth: + let first = try point() + let second = try point() + let third = try ellipseThird(first: first, second: second, depth: depth()) + return [.ellipse(first, second, third, style)] + case .repeatBack: + let distanceBits = 3 + let minimumDistance = 2 + let distance = try reader.read(distanceBits) + 1 + guard distance >= minimumDistance, distance <= history.count else { throw MCOImageCodecError.damaged } + let delta = try translation(short: reader.bit()) + let previous = history[history.count - distance] + try consume(previous.expandedCount(upTo: remainingFigures)) + return [previous.translated(x: delta.x, y: delta.y, style: style)] + case .repeatColors: return try repeatedColors(history: history, style: &style) + case .dots: return try dots(style: style) + case .pathOrthogonal: return [try orthogonalPath(style: style)] + case .pathBounds: return [try boundsPath(delta: false, style: style)] + case .pathBoundsDelta: return [try boundsPath(delta: true, style: style)] + case .escape: + let textCommand = 0 + guard try reader.read(Field.opcodeBits) == textCommand else { throw MCOImageCodecError.unsupported } + return [try text(style: style, alignment: &alignment, fontSize: &fontSize)] + case .raster: + let mixedMode = 1 + guard mode == mixedMode, !nested else { throw MCOImageCodecError.damaged } + return [try raster()] + case .group: + let count = try reader.compact() + 1 + guard groupDepth < Field.maximumGroupDepth else { throw MCOImageCodecError.unsupported } + groupDepth += 1 + defer { groupDepth -= 1 } + var nestedStyle = style + var nestedAlignment = alignment + var nestedFont = fontSize + let figures = try stream(count: count, style: &nestedStyle, alignment: &nestedAlignment, fontSize: &nestedFont) + return [.group(figures, style)] + } + } + + private mutating func repeatedColors(history: [MCOImageFigure], style: inout MCOImageV4Style) throws -> [MCOImageFigure] { + guard var previous = history.last else { throw MCOImageCodecError.damaged } + let stroke = try reader.bit() + let delta = try translation(short: reader.bit()) + let count = try reader.compact() + 2 + let hasColors = try reader.bit() + if hasColors, count - 1 > reader.remaining { throw MCOImageCodecError.damaged } + let figureCost = try previous.expandedCount(upTo: remainingFigures) + guard count <= remainingFigures / figureCost else { throw MCOImageCodecError.unsupported } + try consume(count * figureCost) + let baseStyle = style + var currentStyle = style + var figures: [MCOImageFigure] = [] + for index in 0.. 0, hasColors { + currentStyle = baseStyle + if stroke { currentStyle.strokeColor = try optionalColor() } else { currentStyle.fillColor = try optionalColor() } + } + let figure = previous.translated(x: delta.x, y: delta.y, style: currentStyle) + try validate(figure) + figures.append(figure) + previous = figure + } + style = currentStyle + return figures + } + + private func ellipseThird(first: MCOImageV4Point, second: MCOImageV4Point, depth: Int) throws -> MCOImageV4Point { + let dx = second.x - first.x + let dy = second.y - first.y + let squared = dx * dx + dy * dy + let length = Int(Double(squared).squareRoot()) + guard length > 0, length * length == squared else { throw MCOImageCodecError.damaged } + let denominator = 2 * length + let numeratorX = (first.x + second.x) * length - 2 * dy * depth + let numeratorY = (first.y + second.y) * length + 2 * dx * depth + guard numeratorX % denominator == 0, numeratorY % denominator == 0 else { throw MCOImageCodecError.damaged } + return MCOImageV4Point(x: numeratorX / denominator, y: numeratorY / denominator) + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Figures.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Figures.swift new file mode 100644 index 0000000000..97944e437b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Figures.swift @@ -0,0 +1,82 @@ +import Foundation + +extension MCOImageV4Parser { + mutating func figure(_ opcode: Opcode, style: MCOImageV4Style) throws -> MCOImageFigure { + switch opcode { + case .dot: return try .dot(point(), style) + case .line: return try .line(point(), point(), style) + case .rectangle, .ellipse: + let first = try point() + let second = try point() + let third = try point() + return opcode == .rectangle ? .rectangle(first, second, third, style) : .ellipse(first, second, third, style) + case .rectangleAxis, .ellipseAxis: + let swapped = try reader.bit() + let first = try point() + let second = try point() + let third = swapped ? MCOImageV4Point(x: second.x, y: first.y) : MCOImageV4Point(x: first.x, y: second.y) + return opcode == .rectangleAxis ? .rectangle(first, second, third, style) : .ellipse(first, second, third, style) + case .path, .pathDelta: return try path(delta: opcode == .pathDelta, style: style) + case .wave: + let closed = try reader.bit() + let first = try point() + let second = try point() + return try .wave(first, second, depth: depth(), closed: closed, style) + default: throw MCOImageCodecError.damaged + } + } + + mutating func depth() throws -> Int { + let negative = try reader.bit() + let magnitude = try reader.read(scalarBits) + 1 + return negative ? -magnitude : magnitude + } + + mutating func pointSequence(count: Int) throws -> [MCOImageV4Point] { + let bits = try Field.shortWidths[reader.read(Field.shortSelectorBits)] + var points = [try point()] + for _ in 1.. MCOImageFigure { + let origin = try point() + let maskBits = 3 + let widthMask = 1 + let alignmentMask = 2 + let fontMask = 4 + let alignmentBits = 2 + let alignmentCount = 3 + let mask = try reader.read(maskBits) + let areaWidth = try mask & widthMask != 0 ? reader.read(xBits) + 1 : nil + if mask & alignmentMask != 0 { alignment = try reader.read(alignmentBits) } + guard alignment < alignmentCount else { throw MCOImageCodecError.damaged } + if mask & fontMask != 0 { fontSize = try reader.read(scalarBits) + 1 } + let bitLength = try reader.compact() + guard bitLength <= reader.remaining else { throw MCOImageCodecError.damaged } + var bytes = [UInt8](repeating: 0, count: (bitLength + Field.byteBits - 1) / Field.byteBits) + for index in 0.. MCOImageFigure { + let origin = try point() + let headerBits = 4 + let header = try reader.read(headerBits) << headerBits | profile + let count = try reader.compact() + let minimumPayloadCount = 2 + guard count >= minimumPayloadCount else { throw MCOImageCodecError.damaged } + let body = try Data([UInt8(header)]) + reader.data(count) + let image = try MCOImageV3Codec.decodeBodyWithoutPacketNonce(body) + guard image.profile == profile else { throw MCOImageCodecError.damaged } + return .raster(origin: origin, image: image) + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Paths.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Paths.swift new file mode 100644 index 0000000000..3f1684aef7 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Paths.swift @@ -0,0 +1,79 @@ +extension MCOImageV4Parser { + mutating func path(delta: Bool, style: MCOImageV4Style) throws -> MCOImageFigure { + let closed = try reader.bit() + let shortBits = try delta ? Field.shortWidths[reader.read(Field.shortSelectorBits)] : nil + let count = try reader.compact() + (closed ? 3 : 2) + var points = [try point()] + while points.count < count { + let next: MCOImageV4Point + if let shortBits { + let previous = points[points.count - 1] + let x = try reader.bit() ? coordinate(size: width, bits: xBits) : previous.x + reader.signed(shortBits) + let y = try reader.bit() ? coordinate(size: height, bits: yBits) : previous.y + reader.signed(shortBits) + next = MCOImageV4Point(x: x, y: y) + try validate(next) + } else { next = try point() } + points.append(next) + } + return .path(points, closed: closed, style) + } + + mutating func orthogonalPath(style: MCOImageV4Style) throws -> MCOImageFigure { + let closed = try reader.bit() + let bits = try Field.shortWidths[reader.read(Field.shortSelectorBits)] + let count = try reader.compact() + (closed ? 3 : 2) + var points = [try point()] + while points.count < count { + let previous = points[points.count - 1] + let vertical = try reader.bit() + let delta = try reader.signed(bits) + let next = previous.translated(x: vertical ? 0 : delta, y: vertical ? delta : 0) + try validate(next) + points.append(next) + } + return .path(points, closed: closed, style) + } + + mutating func boundsPath(delta: Bool, style: MCOImageV4Style) throws -> MCOImageFigure { + let closed = try reader.bit() + let shortBits = try delta ? Field.shortWidths[reader.read(Field.shortSelectorBits)] : nil + let count = try reader.compact() + (closed ? 3 : 2) + let origin = try point() + let boundsWidth = try reader.read(xBits) + 1 + let boundsHeight = try reader.read(yBits) + 1 + try validate(origin.translated(x: boundsWidth - 1, y: boundsHeight - 1)) + let localXBits = Self.bits(boundsWidth - 1) + let localYBits = Self.bits(boundsHeight - 1) + var points: [MCOImageV4Point] = [] + while points.count < count { + let next: MCOImageV4Point + if let shortBits, let previous = points.last { + next = try previous.translated(x: reader.signed(shortBits), y: reader.signed(shortBits)) + } else { next = try MCOImageV4Point(x: reader.read(localXBits), y: reader.read(localYBits)) } + guard next.x >= 0, next.x < boundsWidth, next.y >= 0, next.y < boundsHeight else { + throw MCOImageCodecError.damaged + } + points.append(next) + } + return .path(points.map { origin.translated(x: $0.x, y: $0.y) }, closed: closed, style) + } + + mutating func dots(style: MCOImageV4Style) throws -> [MCOImageFigure] { + let delta = try reader.bit() + let shortBits = try delta ? Field.shortWidths[reader.read(Field.shortSelectorBits)] : nil + let count = try reader.compact() + 2 + let minimumStepBits = shortBits.map { 2 * $0 } ?? (xBits + yBits) + guard count - 1 <= reader.remaining / minimumStepBits else { throw MCOImageCodecError.damaged } + try consume(count) + var points = [try point()] + while points.count < count { + let next: MCOImageV4Point + if let shortBits { + next = try points[points.count - 1].translated(x: reader.signed(shortBits), y: reader.signed(shortBits)) + try validate(next) + } else { next = try point() } + points.append(next) + } + return points.map { .dot($0, style) } + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Validation.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Validation.swift new file mode 100644 index 0000000000..dc33fbf355 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Validation.swift @@ -0,0 +1,40 @@ +extension MCOImageV4Parser { + func validate(_ point: MCOImageV4Point) throws { + guard point.x >= -margin(width), point.x < width + margin(width), + point.y >= -margin(height), point.y < height + margin(height) else { throw MCOImageCodecError.damaged } + } + + func validate(_ figure: MCOImageFigure) throws { + let style = figure.style + guard style.strokeWidth >= Field.defaultStrokeWidth, style.strokeWidth <= max(width, height) else { + throw MCOImageCodecError.damaged + } + switch figure { + case let .dot(point, style): + try validate(point) + guard style.strokeColor != nil else { throw MCOImageCodecError.damaged } + case let .line(start, end, _): + try validate(start) + try validate(end) + case let .rectangle(first, second, third, _), let .ellipse(first, second, third, _): + try validate(first) + try validate(second) + try validate(third) + guard first != second, first != third, second != third else { throw MCOImageCodecError.damaged } + case let .path(points, closed, _): + let minimumPoints = closed ? 3 : 2 + guard points.count >= minimumPoints else { throw MCOImageCodecError.damaged } + try points.forEach(validate) + case let .wave(start, end, depth, _, _): + try validate(start) + try validate(end) + guard depth != 0, abs(depth) <= max(width, height) else { throw MCOImageCodecError.damaged } + case let .text(origin, areaWidth, _, fontSize, _, _): + try validate(origin) + if let areaWidth, areaWidth < 1 || areaWidth > width { throw MCOImageCodecError.damaged } + guard fontSize >= 1, fontSize <= max(width, height) else { throw MCOImageCodecError.damaged } + case let .group(figures, _): try figures.forEach(validate) + case let .raster(origin, _): try validate(origin) + } + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift new file mode 100644 index 0000000000..bb682814df --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift @@ -0,0 +1,187 @@ +import Foundation + +struct MCOImageV4Parser { + enum Opcode: Int { + case end = 0, fill = 1, stroke = 2, strokeWidth = 3, dot = 4, line = 5 + case rectangle = 6, ellipse = 7, rectangleAxis = 8, path = 9, pathDelta = 10 + case wave = 11, repeatLast = 12, ellipseAxis = 13, repeatShort = 14, extended = 15 + } + + enum Field { + static let opcodeBits = 4 + static let modeBits = 2 + static let profileBits = 4 + static let byteBits = 8 + static let shortSelectorBits = 2 + static let shortWidths = [3, 4, 5, 6] + static let smallDimensionBits = 5 + static let mediumDimensionBits = 6 + static let smallDimensionMaximum = 32 + static let mediumDimensionMaximum = 64 + static let maximumOverscan = 16 + static let overscanDivisor = 8 + static let defaultStrokeWidth = 1 + static let initialTextAlignment = 0 + static let textSizePercent = 12 + static let percentDivisor = 100 + static let targetFlag = 1 + static let replyFlag = 2 + static let knownTailFlags = targetFlag | replyFlag + static let maximumExpandedFigures = 4096 + static let maximumGroupDepth = 64 + } + + var reader: MCOImageV4BitReader + var width = 0 + var height = 0 + var profile = 0 + var mode = 0 + var xBits = 0 + var yBits = 0 + var scalarBits = 0 + var colorBits = 0 + var remainingFigures = Field.maximumExpandedFigures + var groupDepth = 0 + + init(_ data: Data) { reader = MCOImageV4BitReader(data) } + + mutating func decode() throws -> MCOImageV4Document { + mode = try reader.read(Field.modeBits) + guard mode <= 1 else { throw MCOImageCodecError.unsupported } + profile = try reader.read(Field.profileBits) + (width, height) = try dimensions() + xBits = Self.bits(width + 2 * margin(width) - 1) + yBits = Self.bits(height + 2 * margin(height) - 1) + scalarBits = Self.bits(max(width, height) - 1) + colorBits = Self.bits(MCOImagePalette.count(profile: profile) - 1) + let background = try reader.bit() ? optionalColor() : MCOImagePalette.white(profile: profile) + var style = MCOImageV4Style( + fillColor: nil, strokeColor: MCOImagePalette.black(profile: profile), strokeWidth: Field.defaultStrokeWidth + ) + var alignment = Field.initialTextAlignment + var fontSize = max(1, width * Field.textSizePercent / Field.percentDivisor) + let figures = try stream(count: nil, style: &style, alignment: &alignment, fontSize: &fontSize) + if mode == 1, !figures.contains(where: { if case .raster = $0 { true } else { false } }) { + throw MCOImageCodecError.damaged + } + try reader.finishByte() + var targetName: String? + var replyTimestamp: UInt32? + if reader.remaining > 0 { + let flags = try reader.read(Field.byteBits) + guard flags & ~Field.knownTailFlags == 0 else { throw MCOImageCodecError.damaged } + if flags & Field.targetFlag != 0 { + let count = try reader.varUInt() + guard count > 0, let name = String(data: try reader.data(count), encoding: .utf8) else { + throw MCOImageCodecError.damaged + } + targetName = name + } + if flags & Field.replyFlag != 0 { + replyTimestamp = UInt32(try reader.read(Field.byteBits)) + | UInt32(try reader.read(Field.byteBits)) << Field.byteBits + | UInt32(try reader.read(Field.byteBits)) << (2 * Field.byteBits) + | UInt32(try reader.read(Field.byteBits)) << (3 * Field.byteBits) + } + guard reader.remaining == 0 else { throw MCOImageCodecError.damaged } + } + return MCOImageV4Document(width: width, height: height, profile: profile, backgroundColor: background, + figures: figures, targetName: targetName, replyTimestamp: replyTimestamp) + } + + mutating func stream( + count: Int?, style: inout MCOImageV4Style, alignment: inout Int, fontSize: inout Int + ) throws -> [MCOImageFigure] { + var figures: [MCOImageFigure] = [] + var history: [MCOImageFigure] = [] + while count == nil || figures.count < count! { + let opcode = Opcode(rawValue: try reader.read(Field.opcodeBits))! + var next: [MCOImageFigure] = [] + switch opcode { + case .end: + guard count == nil else { throw MCOImageCodecError.damaged } + return figures + case .fill: style.fillColor = try optionalColor() + case .stroke: style.strokeColor = try optionalColor() + case .strokeWidth: style.strokeWidth = try reader.read(scalarBits) + 1 + case .repeatLast, .repeatShort: + guard let previous = history.last else { throw MCOImageCodecError.damaged } + let short = opcode == .repeatShort + let delta = try translation(short: short) + try consume(previous.expandedCount(upTo: remainingFigures)) + next = [previous.translated(x: delta.x, y: delta.y, style: style)] + case .extended: + next = try extended(history: history, nested: count != nil, style: &style, alignment: &alignment, fontSize: &fontSize) + default: + try consume(1) + next = [try figure(opcode, style: style)] + } + if let count, next.count > count - figures.count { throw MCOImageCodecError.damaged } + for figure in next { + try validate(figure) + figures.append(figure) + if case .raster = figure { continue } + history.append(figure) + } + } + return figures + } + + mutating func dimensions() throws -> (Int, Int) { + switch try reader.read(Field.modeBits) { + case 0: + let side = try reader.read(Field.mediumDimensionBits) + 1 + return (side, side) + case 1: + let width = try reader.read(Field.smallDimensionBits) + 1 + let height = try reader.read(Field.smallDimensionBits) + 1 + guard width != height else { throw MCOImageCodecError.damaged } + return (width, height) + case 2: + let width = try reader.read(Field.mediumDimensionBits) + 1 + let height = try reader.read(Field.mediumDimensionBits) + 1 + guard width != height, width > Field.smallDimensionMaximum || height > Field.smallDimensionMaximum else { + throw MCOImageCodecError.damaged + } + return (width, height) + default: + let rectangle = try reader.bit() + let width = try reader.read(Field.byteBits) + 1 + let height = try rectangle ? reader.read(Field.byteBits) + 1 : width + guard max(width, height) > Field.mediumDimensionMaximum, !rectangle || width != height else { + throw MCOImageCodecError.damaged + } + return (width, height) + } + } + + mutating func optionalColor() throws -> Int? { try reader.bit() ? color() : nil } + + mutating func color() throws -> Int { + try MCOImagePalette.ref(fromStored: reader.read(colorBits), profile: profile) + } + + mutating func point() throws -> MCOImageV4Point { + try MCOImageV4Point(x: coordinate(size: width, bits: xBits), y: coordinate(size: height, bits: yBits)) + } + + mutating func coordinate(size: Int, bits: Int) throws -> Int { + let code = try reader.read(bits) + guard code < size + 2 * margin(size) else { throw MCOImageCodecError.damaged } + return code - margin(size) + } + + mutating func translation(short: Bool) throws -> MCOImageV4Point { + let shortBits = try short ? Field.shortWidths[reader.read(Field.shortSelectorBits)] : nil + return try MCOImageV4Point(x: reader.signed(shortBits ?? (xBits + 1)), y: reader.signed(shortBits ?? (yBits + 1))) + } + + func margin(_ size: Int) -> Int { min(Field.maximumOverscan, max(1, (size + Field.overscanDivisor - 1) / Field.overscanDivisor)) } + + static func bits(_ maximum: Int) -> Int { max(1, Int.bitWidth - maximum.leadingZeroBitCount) } + + mutating func consume(_ count: Int) throws { + guard count <= remainingFigures else { throw MCOImageCodecError.unsupported } + remainingFigures -= count + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Point.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Point.swift new file mode 100644 index 0000000000..b5aa035e04 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Point.swift @@ -0,0 +1,13 @@ +public struct MCOImageV4Point: Sendable, Hashable { + public let x: Int + public let y: Int + + public init(x: Int, y: Int) { + self.x = x + self.y = y + } + + func translated(x: Int, y: Int) -> Self { + Self(x: self.x + x, y: self.y + y) + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Style.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Style.swift new file mode 100644 index 0000000000..936d275561 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Style.swift @@ -0,0 +1,11 @@ +public struct MCOImageV4Style: Sendable, Hashable { + public var fillColor: Int? + public var strokeColor: Int? + public var strokeWidth: Int + + public init(fillColor: Int?, strokeColor: Int?, strokeWidth: Int) { + self.fillColor = fillColor + self.strokeColor = strokeColor + self.strokeWidth = strokeWidth + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageWireBudget.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageWireBudget.swift new file mode 100644 index 0000000000..dad0b082fc --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageWireBudget.swift @@ -0,0 +1,3 @@ +public enum MCOImageWireBudget { + public static let maximumChannelDataBytes = 165 +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift new file mode 100644 index 0000000000..48574a09d8 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift @@ -0,0 +1,35 @@ +import Foundation + +struct MCOTextBitReader { + let bytes: [UInt8] + let limit: Int + private(set) var offset = 0 + private static let bitsPerByte = 8 + + init(_ data: Data, bitLength: Int) throws { + guard bitLength >= 0, bitLength <= data.count * Self.bitsPerByte else { throw MCOImageCodecError.damaged } + bytes = Array(data) + limit = bitLength + } + + var remaining: Int { limit - offset } + + mutating func read(_ count: Int) throws -> Int { + guard count >= 0, count < Int.bitWidth, count <= remaining else { throw MCOImageCodecError.damaged } + var value = 0 + for _ in 0..> (Self.bitsPerByte - 1 - offset % Self.bitsPerByte)) & 1) + offset += 1 + } + return value + } + + mutating func bit() throws -> Bool { try read(1) != 0 } + + mutating func headerField() throws -> Int { + let shortBits = 3 + let escape = 7 + let value = try read(shortBits) + return try value == escape ? escape + read(Self.bitsPerByte) : value + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextCodec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextCodec.swift new file mode 100644 index 0000000000..b0c00363f4 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextCodec.swift @@ -0,0 +1,8 @@ +import Foundation + +enum MCOTextCodec { + static func decode(_ data: Data, bitLength: Int) throws -> String { + var decoder = try MCOTextDecoder(data, bitLength: bitLength) + return try decoder.decode() + } +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift new file mode 100644 index 0000000000..e38b16bd71 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift @@ -0,0 +1,159 @@ +import Foundation + +struct MCOTextDecoder { + private enum Field { + static let version = 1 + static let languageBits = 3 + static let languageEscape = 7 + static let globalLanguageNone = 255 + static let symbolBits = 5 + static let extendedBits = 3 + static let byteBits = 8 + static let rawPaddingBits = 4 + static let predictionCount = 4 + static let space: UInt32 = 0x20 + static let lineFeed: UInt32 = 0x0a + } + + private enum Context { case start, punctuation, symbol } + private var reader: MCOTextBitReader + private var languageA = 0 + private var languageB: Int? + private var language = 0 + private var context = Context.start + private var previous: UInt32? + private var shift = false + private var capitals = false + private var output = String.UnicodeScalarView() + + init(_ data: Data, bitLength: Int) throws { reader = try MCOTextBitReader(data, bitLength: bitLength) } + + mutating func decode() throws -> String { + guard try reader.headerField() == Field.version else { throw MCOImageCodecError.unsupported } + let generation = try reader.headerField() + let first = try reader.read(Field.languageBits) + let second = try reader.read(Field.languageBits) + if first == Field.languageEscape { + if second == 1 { + guard try reader.read(Field.rawPaddingBits) == 0, reader.remaining % Field.byteBits == 0 else { + throw MCOImageCodecError.damaged + } + return try utf8(count: reader.remaining / Field.byteBits) + } + guard second == 0 else { throw MCOImageCodecError.damaged } + languageA = try reader.read(Field.byteBits) + let partner = try reader.read(Field.byteBits) + languageB = partner == Field.globalLanguageNone ? nil : partner + } else { + languageA = first + languageB = second == Field.languageEscape ? nil : second + } + guard MCOTextModels.all.indices.contains(languageA), + languageB == nil || MCOTextModels.all.indices.contains(languageB!) else { throw MCOImageCodecError.damaged } + guard generation == MCOTextModels.generation else { throw MCOImageCodecError.unsupported } + language = languageA + while reader.remaining > 0 { try token() } + guard !shift else { throw MCOImageCodecError.damaged } + return String(output) + } + + private mutating func token() throws { + let model = MCOTextModels.all[language] + switch try tokenPrefix() { + case 0: + let rank = try top4Rank() + let predictions: [Int] + switch context { + case .start: predictions = model.start + case .punctuation: predictions = model.punctuationStart + case .symbol: + guard let previous, let index = model.symbols.firstIndex(of: previous) else { throw MCOImageCodecError.damaged } + let start = index * Field.predictionCount + predictions = Array(model.top4[start.. Int { + let maximumPrefixLength = 6 + for count in 0.. Int { + if try !reader.bit() { return 0 } + if try !reader.bit() { return 1 } + return try reader.bit() ? 3 : 2 + } + + private mutating func extended() throws { + try requireNoShift() + switch try reader.read(Field.extendedBits) { + case 0: + let next = try reader.read(Field.byteBits) + guard MCOTextModels.all.indices.contains(next) else { throw MCOImageCodecError.damaged } + language = next + reset() + case 1: reset() + case 2: + let count = try reader.read(Field.symbolBits) + 1 + output.append(contentsOf: try utf8(count: count).unicodeScalars) + reset() + case 3: capitals.toggle() + default: throw MCOImageCodecError.damaged + } + } + + private mutating func emit(_ rune: UInt32, model: MCOTextModel) throws { + let uppercase = model.uppercase[rune] + guard !shift || uppercase != nil else { throw MCOImageCodecError.damaged } + try append(uppercase != nil && capitals != shift ? uppercase! : rune) + context = .symbol + previous = rune + shift = false + } + + private mutating func append(_ rune: UInt32) throws { + guard let scalar = UnicodeScalar(rune) else { throw MCOImageCodecError.damaged } + output.append(scalar) + } + + private mutating func utf8(count: Int) throws -> String { + guard count <= reader.remaining / Field.byteBits else { throw MCOImageCodecError.damaged } + let bytes = try (0.. ProtocolLimits.maxChannelMessageLength(nodeNameByteCount: name.utf8.count)) + let message = try await service.createPendingChannelMessage(text: exact, channelIndex: 0, radioID: radioID) + try await service.sendPendingChannelMessage(messageID: message.id) + #expect(await session.sendChannelDataInvocations.first?.payload.count == 165) + let oversized = try textWithPayloadSize(166, senderName: name) + await #expect(throws: MessageServiceError.self) { + try await service.createPendingChannelMessage(text: oversized, channelIndex: 0, radioID: radioID) + } + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: 0, limit: 10, offset: 0).count == 1) + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: name + "A")) + await #expect(throws: MessageServiceError.self) { + try await service.sendPendingChannelMessage(messageID: message.id) + } + #expect(await session.sendChannelDataInvocations.count == 1) + #expect(await session.sendChannelMessageInvocations.isEmpty) + #expect(try await store.fetchMessage(id: message.id)?.status == .failed) + } + + @Test(arguments: ["im3:!", "im4:!", "im5:AA"]) + func `damaged and unsupported image text never falls through to channel text`(text: String) async throws { + let radioID = UUID() + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: store, contactService: nil) + try await store.saveDevice(.testDevice(radioID: radioID)) + await #expect(throws: (any Error).self) { + try await service.sendChannelMessage(text: text, channelIndex: 0, radioID: radioID) + } + #expect(await session.sendChannelDataInvocations.isEmpty) + #expect(await session.sendChannelMessageInvocations.isEmpty) + } + + @Test + func `firmware rejection marks failed without a text fallback`() async throws { + let radioID = UUID() + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: store, contactService: nil) + try await store.saveDevice(.testDevice(radioID: radioID)) + let message = try await service.createPendingChannelMessage(text: fixture, channelIndex: 0, radioID: radioID) + await session.setSendChannelDataError(MeshCoreError.deviceError(code: 1)) + await #expect(throws: MessageServiceError.self) { + try await service.sendPendingChannelMessage(messageID: message.id) + } + #expect(await session.sendChannelDataInvocations.count == 1) + #expect(await session.sendChannelMessageInvocations.isEmpty) + #expect(try await store.fetchMessage(id: message.id)?.status == .failed) + } + + @Test + func `ordinary channel text remains a text command`() async throws { + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: MockPersistenceStore(), contactService: nil) + _ = try await service.sendChannelMessage(text: "hello", channelIndex: 0, radioID: UUID()) + #expect(await session.sendChannelMessageInvocations.first?.text == "hello") + #expect(await session.sendChannelDataInvocations.isEmpty) + } + + @Test(arguments: [MeshCoreError.notConnected, .deviceError(code: 3)]) + @MainActor + func `persisted legacy image replays as identical binary after disconnect`(failure: MeshCoreError) async throws { + let store = PersistenceStore(modelContainer: try PersistenceStore.createContainer(inMemory: true)) + let radioID = UUID() + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio")) + try await store.saveChannel(ChannelDTO.testChannel(radioID: radioID, index: 0)) + let message = MessageDTO.testChannelMessage(radioID: radioID, text: fixture, status: .pending) + try await store.saveMessage(message) + let envelope = ChannelMessageEnvelope(messageID: message.id, channelIndex: 0, isResend: false, + messageText: message.text, messageTimestamp: message.timestamp, localNodeName: "Radio") + _ = try await store.insertPendingSendAssigningSequence(PendingSendDTO(envelope: envelope, radioID: radioID)) + let firstSession = MockMeshCoreSession() + await firstSession.setSendChannelDataError(failure) + let firstService = MessageService(session: firstSession, dataStore: store, contactService: nil, + config: .init(poolBackoff: .init(attemptCap: 0))) + let firstQueue = ChatSendQueueService( + radioID: radioID, dataStore: store, messageService: firstService, + channelService: ChannelService(session: firstSession, dataStore: store, rxLogService: nil), reactionService: ReactionService() + ) + await firstQueue.hydrate() + try await waitUntil("Binary image should reach the disconnected transport") { + await !firstSession.sendChannelDataInvocations.isEmpty + } + await firstQueue.shutdown() + await firstQueue.awaitDrainCompletion() + #expect(try await store.hasPendingSend(messageID: message.id)) + let replaySession = MockMeshCoreSession() + let replayService = MessageService(session: replaySession, dataStore: store, contactService: nil) + let replayQueue = ChatSendQueueService( + radioID: radioID, dataStore: store, messageService: replayService, + channelService: ChannelService(session: replaySession, dataStore: store, rxLogService: nil), reactionService: ReactionService() + ) + await replayQueue.hydrate() + await replayQueue.awaitDrainCompletion() + await replayQueue.shutdown() + #expect(await replaySession.sendChannelDataInvocations.first?.payload == firstSession.sendChannelDataInvocations.first?.payload) + #expect(await firstSession.sendChannelMessageInvocations.isEmpty) + #expect(await replaySession.sendChannelMessageInvocations.isEmpty) + #expect(try await store.fetchMessage(id: message.id)?.status == .sent) + #expect(try await store.hasPendingSend(messageID: message.id) == false) + } + + @Test(arguments: SendPath.allCases) + func `binary TABLE_FULL retries the same payload before success`(path: SendPath) async throws { + let radioID = UUID() + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio")) + let service = MessageService(session: session, dataStore: store, contactService: nil, + config: .init(poolBackoff: .init(baseDelay: 0, jitterRange: 1...1))) + await session.setSendChannelDataErrors([.deviceError(code: 3), nil]) + let message = try await service.createPendingChannelMessage(text: fixture, channelIndex: 0, radioID: radioID) + switch path { + case .inline: _ = try await service.sendChannelMessage(text: fixture, channelIndex: 0, radioID: radioID) + case .pending: try await service.sendPendingChannelMessage(messageID: message.id) + case .resend: try await service.resendChannelMessage(messageID: message.id) + } + let calls = await session.sendChannelDataInvocations + #expect(calls.count == 2) + #expect(calls[0].payload == calls[1].payload) + #expect(await session.sendChannelMessageInvocations.isEmpty) + #expect(ChatSendQueueService.isTransientChannelMessageError(MeshCoreError.deviceError(code: 3), isImage: true)) + #expect(!ChatSendQueueService.isTransientChannelMessageError(MeshCoreError.deviceError(code: 3), isImage: false)) + } + + @Test + func `transparent v3 pixels remain clear when wrapped in a v4 document`() throws { + let image = MCOImageRaster(width: 2, height: 2, profile: 0, pixels: [0, 1, 1, 0], transparentColor: 1) + let body = try MCOImageV3Codec.encode(image, nonce: 42) + let document = try MCOImageV4Codec.decodeBody(MCOImageV4Codec.wrappingV3Body(body)) + #expect(document.backgroundColor == nil) + #expect(document.figures == [.raster(origin: .init(x: 0, y: 0), image: image)]) + } + + private func textWithPayloadSize(_ size: Int, senderName: String) throws -> String { + let payload = try MCOImageCodec.channelAppPayload(fromText: fixture) + for count in 1...200 { + var length = MCOImageBitWriter() + length.varUint(count) + let tail = Data([1]) + length.data + Data(repeating: 0x74, count: count) + let text = try MCOImageCodec.text(fromAppPayload: payload + tail) + if try MCOImageTransport.encode(text: text, senderName: senderName).count == size { return text } + } + throw MCOImageCodecError.damaged + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift new file mode 100644 index 0000000000..1fb1b929f0 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift @@ -0,0 +1,83 @@ +import Foundation +@testable import MC1Services +import MeshCoreTestSupport +import Testing + +@Suite("MCOimg receive persistence") +@MainActor +struct MCOImageReceiveIntegrationTests { + @Test(arguments: [ + (initialSync: true, v4: false), + (initialSync: false, v4: true) + ]) + func `channel datagram is persisted with unknown sender time and conversation callbacks`( + initialSync: Bool, v4: Bool + ) async throws { + let radioID = UUID() + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + try await store.saveDevice(.testDevice(id: radioID)) + let channel = ChannelDTO.testChannel(radioID: radioID, index: 2) + try await store.saveChannel(channel) + let services = ServiceContainer( + session: MeshCoreSession(transport: SimulatorMockTransport()), + dataStore: store, + radioID: radioID + ) + services.notificationService.isSuppressingNotifications = true + defer { Task { await services.tearDown() } } + let poller = MockMessagePollingService() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: poller), + radioID: radioID + ) + let sender = "Peer:名" + let v3Payload = try #require(Data(base64Encoded: "E3oBjQBCvgE=")) + let appPayload = v4 ? Data([0x14, 0, 0, 0, 0]) : v3Payload + let expectedText = try MCOImageCodec.text(fromAppPayload: appPayload) + let packet = ChannelDatagram( + channelIndex: channel.index, + pathLength: 2, + dataType: MCOImageTransport.applicationDataType, + data: Data([UInt8(sender.utf8.count)]) + Data(sender.utf8) + appPayload, + snr: 6.25 + ) + let anchor = Date().addingTimeInterval(-60) + let before = Date() + let stream = coordinator.dataEvents() + let handler = try #require(await poller.capturedChannelDatagramHandler) + let scope = try #require(try await store.captureReceiveScope(radioID: radioID, link: ReceiveScope.Lifetime())) + await handler(packet, channel, initialSync ? .initialSync(anchor: anchor) : .live, scope, nil, before) + coordinator.finishDataEvents() + let messages = try await store.fetchMessages(radioID: radioID, channelIndex: channel.index) + let message = try #require(messages.first) + #expect(messages.count == 1) + #expect(message.text == expectedText) + #expect(message.senderNodeName == sender) + #expect(message.timestampCorrected) + #expect(message.senderTimestamp == 0) + #expect(message.createdAt >= before) + #expect(message.snr == packet.snr) + #expect(message.pathLength == packet.pathLength) + #expect(message.sortDate == (initialSync ? anchor : message.createdAt)) + #expect(try await store.fetchChannel(id: channel.id)?.unreadCount == 1) + var sawAdmission = false + for await event in stream { + if case let .channelMessageReceived(received, _, _) = event { + sawAdmission = received.id == message.id && received.text == message.text + } + } + #expect(sawAdmission) + if v4 { + guard case .document = MCOImageCodec.content(from: message.text) else { + Issue.record("Persisted v4 text must still decode as a document") + return + } + } else { + guard case .raster = MCOImageCodec.content(from: message.text) else { + Issue.record("Persisted v3 text must still decode as a raster") + return + } + } + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift new file mode 100644 index 0000000000..d33be4f8ba --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift @@ -0,0 +1,64 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("MCOimg send integration") +struct MCOImageSendIntegrationTests { + private let fixture = "im3:g/5WjAL`NA" + + @Test + func `pending DM admission survives contact bookkeeping failure`() async throws { + let store = MockPersistenceStore() + await store.setStubbedUpdateContactLastMessageError(MessageServiceError.contactNotFound) + let service = MessageService(session: MockMeshCoreSession(), dataStore: store, contactService: nil) + let contact = ContactDTO.testContact(radioID: UUID()) + let message = try await service.createPendingMessage(text: fixture, to: contact) + #expect(try await store.fetchMessage(id: message.id)?.text == fixture) + #expect(message.status == .pending) + } + + @Test + func `channel drain revalidates sender name budget before issuing a radio command`() async throws { + let radioID = UUID() + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: store, contactService: nil) + try await store.saveDevice(.testDevice(id: radioID, nodeName: "A")) + let text = String(repeating: "a", count: ProtocolLimits.maxChannelMessageLength(nodeNameByteCount: 1)) + let message = try await service.createPendingChannelMessage(text: text, channelIndex: 0, radioID: radioID) + try await store.saveDevice(.testDevice(id: radioID, nodeName: "Longer")) + await #expect { + try await service.sendPendingChannelMessage(messageID: message.id) + } throws: { error in + guard let serviceError = error as? MessageServiceError, case .messageTooLong = serviceError else { return false } + return true + } + #expect(await session.sendChannelMessageInvocations.isEmpty) + #expect(try await store.fetchMessage(id: message.id)?.status == .failed) + } + + @Test + func `image resend persists exactly the text that queue envelopes and ACK prediction use`() async throws { + let store = MockPersistenceStore() + let service = MessageService(session: MockMeshCoreSession(), dataStore: store, contactService: nil) + let contact = ContactDTO.testContact(radioID: UUID()) + let original = try await service.createPendingMessage(text: fixture, to: contact) + let refreshed = try await service.prepareImageForResend(original) + let originalPayload = try MCOImageCodec.appPayload(fromText: original.text) + let refreshedPayload = try MCOImageCodec.appPayload(fromText: refreshed.text) + #expect(originalPayload.dropFirst(2) == refreshedPayload.dropFirst(2)) + #expect(refreshedPayload.count == originalPayload.count) + #expect(try await store.fetchMessage(id: original.id)?.text == refreshed.text) + #expect(refreshed.id == original.id) + } + + @Test + func `nonimage resend preparation preserves the original wire text`() async throws { + let store = MockPersistenceStore() + let service = MessageService(session: MockMeshCoreSession(), dataStore: store, contactService: nil) + let contact = ContactDTO.testContact(radioID: UUID()) + let original = try await service.createPendingMessage(text: "hello", to: contact) + #expect(try await service.prepareImageForResend(original) == original) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift new file mode 100644 index 0000000000..dff5a01e7f --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift @@ -0,0 +1,156 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("MCOimg channel transport") +struct MCOImageTransportTests { + private let appPayload = Data(base64Encoded: "E3oBjQBCvgE=")! + + private func datagram( + payload: Data? = nil, + name: String = "Peer:名", + channelIndex: UInt8 = 2, + dataType: UInt16 = MCOImageTransport.applicationDataType + ) -> ChannelDatagram { + let nameBytes = Data(name.utf8) + return ChannelDatagram( + channelIndex: channelIndex, + pathLength: 0, + dataType: dataType, + data: payload ?? Data([UInt8(nameBytes.count)]) + nameBytes + appPayload, + snr: 4.5 + ) + } + + @Test + func `registered envelope preserves sender and v3 text representation`() throws { + let image = try #require(MCOImageTransport.decode(datagram())) + #expect(image.senderName == "Peer:名") + #expect(image.text == "im3:g/5WjAL`NA") + #expect(try MCOImageCodec.appPayload(fromText: image.text) == appPayload) + } + + @Test + func `v4 text omits subtype byte and unknown image versions survive for placeholders`() throws { + for version: UInt8 in [0x14, 0x15] { + let payload = Data([0, version, 0, 0]) + let image = try #require(MCOImageTransport.decode(datagram(payload: payload))) + #expect(image.text.hasPrefix(version == 0x14 ? "im4:" : "im5:")) + #expect(try MCOImageCodec.appPayload(fromText: image.text) == Data([version, 0, 0])) + } + } + + @Test + func `complete binary envelope accepts the exact packet boundary and rejects one byte over`() throws { + let name = String(repeating: "a", count: 155) + let exact = Data([0x9b, 0x01]) + Data(name.utf8) + appPayload + #expect(exact.count == MCOImageWireBudget.maximumChannelDataBytes) + let decoded = try #require(MCOImageTransport.decode(datagram(payload: exact))) + #expect(decoded.senderName == name) + #expect(MCOImageTransport.decode(datagram(payload: exact + Data([0]))) == nil) + } + + @Test + func `other namespaces and subtypes are ignored`() { + #expect(MCOImageTransport.decode(datagram(dataType: 0x0121)) == nil) + #expect(MCOImageTransport.decode(datagram(payload: Data([0, 0x31, 0]))) == nil) + } + + @Test(arguments: [ + Data(), Data([0x80]), Data([0x80, 0x00, 0x13]), + Data([0x81, 0x80, 0x80, 0x80, 0x80, 0, 0x13]), + Data([3, 0x61, 0x62]), Data([1, 0xff, 0x13]), Data([0]) + ]) + func `damaged sender envelopes do not become text messages`(payload: Data) { + #expect(MCOImageTransport.decode(datagram(payload: payload)) == nil) + } + + @Test + func `duplicate window is scoped to radio channel and exact nonce and expires`() { + let radioID = UUID() + let time = Date(timeIntervalSince1970: 100) + var duplicates = MCOImageDatagramDuplicates() + let packet = datagram() + #expect({ duplicates.admit(packet, radioID: radioID, receivedAt: time) }()) + #expect({ !duplicates.admit(packet, radioID: radioID, receivedAt: time.addingTimeInterval(1)) }()) + #expect({ duplicates.admit(packet, radioID: UUID(), receivedAt: time.addingTimeInterval(2)) }()) + #expect({ duplicates.admit(datagram(channelIndex: 3), radioID: radioID, receivedAt: time.addingTimeInterval(3)) }()) + var newNonce = packet.data + newNonce[newNonce.startIndex + 1 + "Peer:名".utf8.count + 1] ^= 1 + #expect({ duplicates.admit(datagram(payload: newNonce), radioID: radioID, receivedAt: time.addingTimeInterval(4)) }()) + #expect({ duplicates.admit(packet, radioID: radioID, receivedAt: time.addingTimeInterval(MCOImageDatagramDuplicates.lifetime)) }()) + } + + @Test + func `duplicate window evicts old entries at capacity`() { + let radioID = UUID() + let time = Date() + var duplicates = MCOImageDatagramDuplicates() + for nonce in 0...MCOImageDatagramDuplicates.capacity { + let packet = datagram(payload: Data([0, 0x13, UInt8(nonce)])) + #expect({ duplicates.admit(packet, radioID: radioID, receivedAt: time) }()) + } + #expect({ duplicates.admit(datagram(payload: Data([0, 0x13, 0])), radioID: radioID, receivedAt: time) }()) + } + + private actor Receipt { + var received: [(ChannelDatagram, DeliveryContext)] = [] + + func record(_ packet: ChannelDatagram, context: DeliveryContext) { + received.append((packet, context)) + } + } + + @Test + func `initial sync admits image datagrams while continuing to drain unknown application data`() async throws { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let session = MockMeshCoreSession() + let polling = MessagePollingService(session: session, dataStore: store) + let receipt = Receipt() + await polling.setChannelDatagramHandler { packet, _, context, _, _, _ in + await receipt.record(packet, context: context) + } + await polling.startMessageEventMonitoring(radioID: radioID) + let packet = datagram() + await session.setQueuedMessageResults([ + .channelDatagram(datagram(dataType: 0xffff)), .channelDatagram(packet), + .channelDatagram(packet), .noMoreMessages + ]) + #expect(try await polling.pollAllMessages() == 1) + let received = await receipt.received + #expect(received.count == 1) + #expect(received.first?.0 == packet) + guard case .initialSync = received.first?.1 else { + Issue.record("Datagram must retain initial-sync delivery context") + return + } + await polling.stopMessageEventMonitoring() + await session.finishEventStreams() + } + + @Test + func `live receipt subscribes to channel datagrams and retains delivery context`() async throws { + let radioID = UUID() + let store = try await PersistenceStore.createTestDataStore(radioID: radioID) + let session = MockMeshCoreSession() + let polling = MessagePollingService(session: session, dataStore: store) + let receipt = Receipt() + await polling.setChannelDatagramHandler { packet, _, context, _, _, _ in + await receipt.record(packet, context: context) + } + await polling.startMessageEventMonitoring(radioID: radioID) + try await waitUntil("poller should subscribe") { await session.eventSubscriptionCount == 1 } + await session.yieldEvent(.channelDataReceived(datagram())) + try await waitUntil("datagram should reach handler") { await receipt.received.count == 1 } + guard case .live = await receipt.received.first?.1 else { + Issue.record("Datagram must retain live delivery context") + return + } + await polling.clearMessageHandlers() + #expect(await !polling.hasMessageHandlersWired) + await polling.stopMessageEventMonitoring() + await session.finishEventStreams() + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageV3CodecTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageV3CodecTests.swift new file mode 100644 index 0000000000..ed67b5d473 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageV3CodecTests.swift @@ -0,0 +1,117 @@ +import Foundation +@testable import MC1Services +import Testing + +struct MCOImageV3CodecTests { + private static let profileNames = [ + "mono", "master4", "master8", "master16", "master32", "master64", "grayscale16", "grayscale32", "grayscale8", + "dynamicGlobal8", "dynamicGlobal16", "dynamicGlobal32", "dynamicGlobal64", "dynamicGlobal128", "dynamicGlobal256", "dynamicGlobal512" + ] + + private struct Fixtures: Decodable { + let fixtures: [Fixture] + } + + private struct Fixture: Decodable { + let name: String + let bodyBase64: String + let text: String + let width: Int + let height: Int + let paletteProfile: String + let pixels: [Int] + let transparentColor: Int? + + var image: MCOImageRaster { + MCOImageRaster(width: width, height: height, profile: MCOImageV3CodecTests.profileNames.firstIndex(of: paletteProfile)!, + pixels: pixels, transparentColor: transparentColor) + } + } + + private func fixtures() throws -> [Fixture] { + let file = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .appendingPathComponent("../../../scripts/mcoimg/fixtures/v3-upstream-decoder.json").standardizedFileURL + return try JSONDecoder().decode(Fixtures.self, from: Data(contentsOf: file)).fixtures + } + + @Test func decodesAllUpstreamContainersAndAlgorithms() throws { + let fixtures = try fixtures() + #expect(fixtures.count == 39) + for fixture in fixtures { + let body = try #require(Data(base64Encoded: fixture.bodyBase64)) + #expect(try MCOImageV3Codec.decodeBody(body) == fixture.image, "\(fixture.name)") + #expect(try MCOImageV3Codec.decodeBodyWithoutPacketNonce(Data(body.dropFirst())) == fixture.image, "\(fixture.name)") + #expect(try MCOImageBase91.decode(String(fixture.text.dropFirst(4))) == Data([0x13]) + body, "\(fixture.name)") + } + } + + @Test func encodingPreservesPixelsAcrossProfilesAndNonces() throws { + for profile in 0.. = .success(.noMoreMessages) + private var queuedMessageResults: [MessageResult] = [] + + func setQueuedMessageResults(_ results: [MessageResult]) { + queuedMessageResults = results + } /// Results to return from successive `sendLogin` calls, consumed FIFO. public var stubbedSendLoginResults: [Result] = [] @@ -275,6 +282,14 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps public let timestamp: Date } + public struct SendChannelDataInvocation: Sendable, Equatable { + public let channelIndex: UInt8 + public let dataType: UInt16 + public let payload: Data + /// Nil when the send omitted the flood-scope preface. + public let floodScope: ResolvedFloodScope? + } + public struct AddContactInvocation: Sendable, Equatable { public let contact: MeshContact } @@ -303,6 +318,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps public private(set) var sendMessageInvocations: [SendMessageInvocation] = [] public private(set) var sendChannelMessageInvocations: [SendChannelMessageInvocation] = [] + public private(set) var sendChannelDataInvocations: [SendChannelDataInvocation] = [] public private(set) var getContactsInvocations: [Date?] = [] public private(set) var getContactPublicKeys: [Data] = [] public private(set) var addContactInvocations: [AddContactInvocation] = [] @@ -375,6 +391,14 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps stubbedSendChannelMessageError = error } + public func setSendChannelDataError(_ error: Error?) { + stubbedSendChannelDataError = error + } + + public func setSendChannelDataErrors(_ errors: [MeshCoreError?]) { + sendChannelDataErrors = errors + } + public func setGetChannelError(_ error: Error?) { stubbedGetChannelError = error } @@ -555,6 +579,42 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps try await sendChannelMessage(channel: channel, text: text, timestamp: timestamp) } + public func sendChannelData( + channelIndex: UInt8, dataType: UInt16, payload: Data, floodScope: ResolvedFloodScope + ) async throws { + try await recordChannelData( + channelIndex: channelIndex, dataType: dataType, payload: payload, floodScope: floodScope + ) + } + + public func sendChannelData( + channelIndex: UInt8, + dataType: UInt16, + payload: Data, + pathLength _: UInt8, + pathBytes _: Data + ) async throws { + try await recordChannelData( + channelIndex: channelIndex, dataType: dataType, payload: payload, floodScope: nil + ) + } + + private func recordChannelData( + channelIndex: UInt8, + dataType: UInt16, + payload: Data, + floodScope: ResolvedFloodScope? + ) async throws { + sendChannelDataInvocations.append(SendChannelDataInvocation( + channelIndex: channelIndex, dataType: dataType, payload: payload, floodScope: floodScope + )) + if !sendChannelDataErrors.isEmpty { + if let error = sendChannelDataErrors.removeFirst() { throw error } + return + } + if let error = stubbedSendChannelDataError { throw error } + } + public func getContacts(since lastModified: Date?) async throws -> [MeshContact] { try await getContactsReportingTotal(since: lastModified).contacts } @@ -785,6 +845,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps public func getMessage(timeout: TimeInterval?) async throws -> MessageResult { getMessageTimeouts.append(timeout) + if !queuedMessageResults.isEmpty { return queuedMessageResults.removeFirst() } switch stubbedGetMessageResult { case let .success(result): return result @@ -814,6 +875,7 @@ public actor MockMeshCoreSession: MeshCoreSessionProtocol, AdvertisingSessionOps public func reset() { sendMessageInvocations = [] sendChannelMessageInvocations = [] + sendChannelDataInvocations = [] getContactsInvocations = [] getContactPublicKeys = [] addContactInvocations = [] diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift index 4534afbf67..504e278a75 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockMessagePollingService.swift @@ -61,6 +61,8 @@ public actor MockMessagePollingService: MessagePollingServiceProtocol { /// Captured channel message handler (set via setChannelMessageHandler) public private(set) var capturedChannelMessageHandler: (@Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void)? + private(set) var capturedChannelDatagramHandler: (@Sendable (ChannelDatagram, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void)? + /// Captured signed message handler (set via setSignedMessageHandler) public private(set) var capturedSignedMessageHandler: (@Sendable (ContactMessage, ReceiveScope) async -> Void)? @@ -77,6 +79,10 @@ public actor MockMessagePollingService: MessagePollingServiceProtocol { capturedChannelMessageHandler = handler } + public func setChannelDatagramHandler(_ handler: @escaping @Sendable (ChannelDatagram, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) { + capturedChannelDatagramHandler = handler + } + public func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) { capturedSignedMessageHandler = handler } @@ -96,6 +102,7 @@ public actor MockMessagePollingService: MessagePollingServiceProtocol { resumeAutoFetchCallCount = 0 capturedContactMessageHandler = nil capturedChannelMessageHandler = nil + capturedChannelDatagramHandler = nil capturedSignedMessageHandler = nil capturedCLIMessageHandler = nil } diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index c74506cf44..f96d39090d 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift @@ -21,6 +21,7 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { public var stubbedUpdateMessageStatusError: Error? public var stubbedResolvePendingAcknowledgementError: Error? public var stubbedSaveContactError: Error? + var stubbedUpdateContactLastMessageError: Error? public var stubbedFetchContactError: Error? public var stubbedFetchContactPublicKeysError: Error? public var stubbedDeleteContactError: Error? @@ -73,6 +74,10 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { updateMessageAckObserver = observer } + public func setStubbedUpdateContactLastMessageError(_ error: Error?) { + stubbedUpdateContactLastMessageError = error + } + public func setStubbedFetchContactError(_ error: Error?) { stubbedFetchContactError = error } @@ -1150,6 +1155,7 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { } public func updateContactLastMessage(contactID: UUID, date: Date?) async throws { + if let error = stubbedUpdateContactLastMessageError { throw error } if let contact = contacts[contactID] { contacts[contactID] = ContactDTO( id: contact.id, diff --git a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift index e88c748e15..d952efdd34 100644 --- a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift @@ -1090,6 +1090,104 @@ struct PersistenceStoreTests { #expect(found?.id == outgoingMessage.id) } + @Test + func `Channel image is not a reaction match`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + + let timestamp: UInt32 = 1_700_000_200 + let channelIndex: UInt8 = 0 + let createdAt = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let image = MessageDTO.testChannelMessage( + radioID: device.id, + channelIndex: channelIndex, + text: "im4:pixel", + timestamp: timestamp, + createdAt: createdAt, + direction: .incoming, + status: .delivered, + senderNodeName: "RemoteNode" + ) + let text = MessageDTO.testChannelMessage( + radioID: device.id, + channelIndex: channelIndex, + text: "Plain channel text", + timestamp: timestamp, + createdAt: createdAt, + direction: .incoming, + status: .delivered, + senderNodeName: "RemoteNode" + ) + try await store.saveMessage(image) + try await store.saveMessage(text) + + let reactionService = ReactionService() + let imageReaction = reactionService.buildReactionText( + emoji: "👍", + targetSender: "RemoteNode", + targetText: image.text, + targetTimestamp: image.reactionTimestamp + ) + let textReaction = reactionService.buildReactionText( + emoji: "👍", + targetSender: "RemoteNode", + targetText: text.text, + targetTimestamp: text.reactionTimestamp + ) + let imageParsed = try #require(ReactionParser.parse(imageReaction)) + let textParsed = try #require(ReactionParser.parse(textReaction)) + let window = (timestamp - 300)...(timestamp + 300) + + let foundImage = try await store.findChannelMessageForReaction( + radioID: device.id, + channelIndex: channelIndex, + parsedReaction: imageParsed, + localNodeName: "LocalNode", + timestampWindow: window, + limit: 200 + ) + let foundText = try await store.findChannelMessageForReaction( + radioID: device.id, + channelIndex: channelIndex, + parsedReaction: textParsed, + localNodeName: "LocalNode", + timestampWindow: window, + limit: 200 + ) + #expect(foundImage == nil) + #expect(foundText?.id == text.id) + #expect(try await store.channelImageMatchesReaction( + radioID: device.id, + channelIndex: channelIndex, + parsedReaction: imageParsed, + localNodeName: "LocalNode", + timestampWindow: window, + limit: 200 + )) + #expect(try await store.channelImageMatchesReaction( + radioID: device.id, + channelIndex: channelIndex, + parsedReaction: textParsed, + localNodeName: "LocalNode", + timestampWindow: window, + limit: 200 + ) == false) + + let admission = try await store.admitReaction(ReactionDTO( + messageID: image.id, + emoji: "👍", + senderName: "RemoteNode", + messageHash: imageParsed.messageHash, + rawText: imageReaction, + channelIndex: image.channelIndex, + radioID: device.id + )) + #expect(admission == nil) + #expect(try await store.fetchReactions(for: image.id).isEmpty) + #expect(try await store.fetchMessage(id: image.id)?.reactionSummary == nil) + } + @Test func `Update message status`() async throws { let store = try await createTestStore() diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift index 8e898b07a6..1313676f0a 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift @@ -209,6 +209,31 @@ struct ChatSendQueueReactionTests { await env.close() } + @Test + func `a channel image does not enqueue a reaction`() async throws { + let (env, _) = try await makeChannelEnvironment() + do { + let connection = try #require(env.manager.currentConnection) + let image = MessageDTO.testChannelMessage( + radioID: connection.device.radioID, + text: "im4:pixel", + direction: .incoming, + status: .delivered, + senderNodeName: "Ada" + ) + try await env.manager.persistenceStore.saveMessage(image) + let queue = try #require(connection.services.chatSendQueueService) + let outgoing = try await queue.enqueueReaction(to: image, emoji: "👍", senderName: Self.senderName) + #expect(outgoing == nil) + #expect(try await env.manager.persistenceStore.fetchPendingSends(radioID: image.radioID).isEmpty) + #expect(try await env.manager.persistenceStore.fetchReactions(for: image.id).isEmpty) + } catch { + await env.close() + throw error + } + await env.close() + } + private func makeChannelEnvironment() async throws -> (ConnectionManagerRadioTestHarness, MessageDTO) { let env = try ConnectionManagerRadioTestHarness() configureNotifications(env) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift index 6426f1b5fd..6650b2579a 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift @@ -578,4 +578,61 @@ struct ReactionServiceTests { #expect(matches.isEmpty) } + + @Test + func `Indexing a channel image drops only that pending hash`() async throws { + let service = ReactionService() + let radioID = UUID() + let timestamp: UInt32 = 1_704_067_200 + let imageText = "im4:pixel" + let imageReactionText = service.buildReactionText( + emoji: "👍", + targetSender: "Ada", + targetText: imageText, + targetTimestamp: timestamp + ) + let imageParsed = try #require(ReactionParser.parse(imageReactionText)) + await service.queuePendingReaction( + parsed: imageParsed, + channelIndex: 0, + senderNodeName: "Bea", + rawText: imageReactionText, + radioID: radioID + ) + + let textReactionText = service.buildReactionText( + emoji: "🔥", + targetSender: "Ada", + targetText: "Hello world", + targetTimestamp: timestamp + ) + let textParsed = try #require(ReactionParser.parse(textReactionText)) + await service.queuePendingReaction( + parsed: textParsed, + channelIndex: 0, + senderNodeName: "Bea", + rawText: textReactionText, + radioID: radioID + ) + + let imageMatches = await service.indexMessage( + id: UUID(), + channelIndex: 0, + senderName: "Ada", + text: imageText, + timestamp: timestamp + ) + #expect(imageMatches.isEmpty) + #expect(await service.findTargetMessage(parsed: imageParsed, channelIndex: 0) == nil) + + let textMatches = await service.indexMessage( + id: UUID(), + channelIndex: 0, + senderName: "Ada", + text: "Hello world", + timestamp: timestamp + ) + #expect(textMatches.count == 1) + #expect(textMatches.first?.parsed.emoji == "🔥") + } } diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelImageReactionTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelImageReactionTests.swift new file mode 100644 index 0000000000..41ead9a044 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelImageReactionTests.swift @@ -0,0 +1,190 @@ +import Foundation +@testable import MC1Services +import MeshCoreTestSupport +import Testing + +@Suite("Channel image reactions") +@MainActor +struct SyncCoordinatorChannelImageReactionTests { + /// Matches `ReactionService`'s pending cap. One more entry evicts the oldest. + private static let pendingReactionCap = 100 + + @Test + func `Reactions that match a stored channel image do not evict a pending text reaction`() async throws { + let radioID = UUID() + let session = MeshCoreSession(transport: SimulatorMockTransport()) + let services = try await ServiceContainer.forTesting(session: session, radioID: radioID) + defer { Task { await services.tearDown() } } + + let timestamp: UInt32 = 1_700_000_000 + let channelIndex: UInt8 = 0 + let image = MessageDTO.testChannelMessage( + radioID: radioID, + channelIndex: channelIndex, + text: "im4:pixel", + timestamp: timestamp, + createdAt: Date(timeIntervalSince1970: TimeInterval(timestamp)), + direction: .incoming, + status: .delivered, + senderNodeName: "Ada" + ) + try await services.dataStore.saveMessage(image) + + let textTimestamp: UInt32 = 1_700_000_100 + try await queueReaction( + on: services.reactionService, + emoji: "🔥", + targetSender: "Ada", + targetText: "Plain channel text", + targetTimestamp: textTimestamp, + channelIndex: channelIndex, + radioID: radioID + ) + + let imageReaction = services.reactionService.buildReactionText( + emoji: "👍", + targetSender: "Ada", + targetText: image.text, + targetTimestamp: image.reactionTimestamp + ) + let coordinator = SyncCoordinator() + let receiveTime = Date(timeIntervalSince1970: TimeInterval(timestamp)) + for _ in 0.. Void) {} + func setChannelDatagramHandler(_ handler: @escaping @Sendable (ChannelDatagram, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) {} + func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) {} func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} diff --git a/MC1Services/Tests/MC1ServicesTests/Utilities/MCOImageV4CodecTests.swift b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOImageV4CodecTests.swift new file mode 100644 index 0000000000..31a46f6787 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOImageV4CodecTests.swift @@ -0,0 +1,168 @@ +import Foundation +import Testing +@testable import MC1Services + +struct MCOImageV4CodecTests { + @Test func decodesEmptyVectorDocument() throws { + // Nonce, vector/mono header, canonical 1×1 dimensions, default background, END. + let document = try MCOImageV4Codec.decodeBody(Data([0, 0, 0, 0])) + #expect(document.width == 1) + #expect(document.height == 1) + #expect(document.profile == 0) + #expect(document.figures.isEmpty) + } + + @Test func rejectsReservedModeAsUnsupported() { + #expect(throws: MCOImageCodecError.unsupported) { + try MCOImageV4Codec.decodeBody(Data([0, 2, 0])) + } + } + + @Test func rejectsTruncatedDocumentAsDamaged() { + #expect(throws: MCOImageCodecError.damaged) { + try MCOImageV4Codec.decodeBody(Data([0])) + } + } + + @Test func boundsZeroDeltaRepeatExpansionBeforeAllocating() throws { + let supported = try MCOImageV4Codec.decodeBody(repeatedDots(count: 4095)) + #expect(supported.figures.count == 4096) + let amplified = repeatedDots(count: 1 << 30) + #expect(amplified.count < 20) + #expect(throws: MCOImageCodecError.unsupported) { + try MCOImageV4Codec.decodeBody(amplified) + } + } + + @Test func boundsNestedGroupDepth() throws { + #expect(try MCOImageV4Codec.decodeBody(nestedGroups(depth: 64)).figures.count == 1) + #expect(throws: MCOImageCodecError.unsupported) { + try MCOImageV4Codec.decodeBody(nestedGroups(depth: 65)) + } + } + + @Test func taggedDartCommandFixtures() throws { + let url = try #require(Bundle.module.url(forResource: "MCOimgV4Fixtures", withExtension: "json", subdirectory: "Fixtures")) + let root = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + let fixtures = try #require(root["fixtures"] as? [[String: Any]]) + #expect(fixtures.count > 50) + for fixture in fixtures { + let encoded = try #require(fixture["bodyBase64"] as? String) + let body = try #require(Data(base64Encoded: encoded)) + if let failure = fixture["error"] as? String { + #expect(throws: failure == "unsupported" ? MCOImageCodecError.unsupported : .damaged) { + try MCOImageV4Codec.decodeBody(body) + } + } else { + let actual = dump(try MCOImageV4Codec.decodeBody(body)) + let expected = try #require(fixture["document"] as? [String: Any]) + #expect(try canonicalJSON(actual) == canonicalJSON(expected), "Body: \(encoded)") + } + } + } + + private func canonicalJSON(_ value: [String: Any]) throws -> Data { + try JSONSerialization.data(withJSONObject: value, options: .sortedKeys) + } + + private func repeatedDots(count: Int) -> Data { + var bits = FixtureBits() + bits.dot() + bits.put(15, 4) + bits.put(12, 4) + bits.put(1, 1) + bits.put(1, 1) + bits.put(0, 2) + bits.put(0, 3) + bits.put(0, 3) + bits.compact(count - 2) + bits.put(0, 1) + return bits.body() + } + + private func nestedGroups(depth: Int) -> Data { + var bits = FixtureBits() + for _ in 0..> shift) & 1) } + } + + mutating func compact(_ value: Int) { + if value <= 3 { put(0, 1); put(value, 2) } else if value <= 19 { + put(1, 2); put(value - 4, 4) + } else if value <= 275 { put(3, 3); put(value - 20, 8) } else { + put(7, 3) + var remaining = value + repeat { + let low = remaining & 0x7f + remaining >>= 7 + put(low | (remaining == 0 ? 0 : 0x80), 8) + } while remaining != 0 + } + } + + mutating func dot() { put(4, 4); put(1, 2); put(1, 2) } + + mutating func body() -> Data { + put(0, 4) + var bytes = [UInt8](repeating: 0, count: (bits.count + 7) / 8) + for (index, bit) in bits.enumerated() where bit != 0 { bytes[index / 8] |= 1 << (index % 8) } + return Data([0] + bytes) + } + } + + private func dump(_ document: MCOImageV4Document) -> [String: Any] { + ["width": document.width, "height": document.height, "profile": document.profile, + "backgroundColor": document.backgroundColor as Any? ?? NSNull(), + "figures": document.figures.map { dump($0, canvasWidth: document.width) }, + "targetName": document.targetName as Any? ?? NSNull(), + "replyTimestamp": document.replyTimestamp as Any? ?? NSNull()] + } + + private func dump(_ style: MCOImageV4Style) -> [String: Any] { + ["fillColor": style.fillColor as Any? ?? NSNull(), "strokeColor": style.strokeColor as Any? ?? NSNull(), + "strokeWidth": style.strokeWidth] + } + + private func point(_ point: MCOImageV4Point) -> [Int] { [point.x, point.y] } + + private func dump(_ figure: MCOImageFigure, canvasWidth: Int) -> [String: Any] { + var result: [String: Any] = ["style": dump(figure.style)] + switch figure { + case let .dot(value, _): result.merge(["kind": "dot", "point": point(value)]) { _, new in new } + case let .line(start, end, _): + result.merge(["kind": "line", "start": point(start), "end": point(end)]) { _, new in new } + case let .rectangle(first, second, third, _): + result.merge(["kind": "rectangle", "first": point(first), "second": point(second), "third": point(third)]) { _, new in new } + case let .ellipse(first, second, third, _): + result.merge(["kind": "ellipse", "first": point(first), "second": point(second), "third": point(third)]) { _, new in new } + case let .path(points, closed, _): + result.merge(["kind": "path", "points": points.map(point), "closed": closed]) { _, new in new } + case let .wave(start, end, depth, closed, _): + result.merge(["kind": "wave", "start": point(start), "end": point(end), "depth": depth, "closed": closed]) { _, new in new } + case let .text(origin, width, alignment, fontSize, text, _): + let resolvedWidth = width ?? max(1, min(canvasWidth, canvasWidth - origin.x)) + result.merge(["kind": "text", "origin": point(origin), "width": resolvedWidth, "alignment": alignment, + "fontSize": fontSize, "text": text]) { _, new in new } + case let .group(figures, _): + result.merge(["kind": "group", "figures": figures.map { dump($0, canvasWidth: canvasWidth) }]) { _, new in new } + case let .raster(origin, image): + result.merge(["kind": "raster", "origin": point(origin), "width": image.width, "height": image.height, + "profile": image.profile, "pixels": image.pixels, + "transparentColor": image.transparentColor as Any? ?? NSNull()]) { _, new in new } + } + return result + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift new file mode 100644 index 0000000000..5203745ef2 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift @@ -0,0 +1,42 @@ +import Foundation +import Testing +@testable import MC1Services + +struct MCOTextCodecTests { + @Test func frozenGenerationZeroReferenceVectors() throws { + let url = try #require(Bundle.module.url(forResource: "MCOTextFixtures", withExtension: "json", subdirectory: "Fixtures")) + let root = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + let fixtures = try #require(root["fixtures"] as? [[String: Any]]) + #expect(fixtures.count == 17) + for fixture in fixtures { + let encoded = try #require(fixture["dataBase64"] as? String) + let data = try #require(Data(base64Encoded: encoded)) + let bitLength = try #require(fixture["bitLength"] as? Int) + let expected = try #require(fixture["text"] as? String) + #expect(try MCOTextCodec.decode(data, bitLength: bitLength) == expected) + } + } + + @Test func rawUTF8DoesNotRequireKnownModelGeneration() throws { + let bits = [0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0] + let header = bytes(bits) + #expect(try MCOTextCodec.decode(header + Data("Help".utf8), bitLength: 48) == "Help") + } + + @Test func rejectsPendingShiftAndInvalidUTF8() { + // Version 1, generation 0, English/no partner, then an unfinished SHIFT. + let shift = [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0] + #expect(throws: MCOImageCodecError.damaged) { + try MCOTextCodec.decode(bytes(shift), bitLength: shift.count) + } + #expect(throws: MCOImageCodecError.damaged) { + try MCOTextCodec.decode(Data([0x23, 0x90, 0xff]), bitLength: 24) + } + } + + private func bytes(_ bits: [Int]) -> Data { + var bytes = [UInt8](repeating: 0, count: (bits.count + 7) / 8) + for (index, bit) in bits.enumerated() where bit != 0 { bytes[index / 8] |= 1 << (7 - index % 8) } + return Data(bytes) + } +} diff --git a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift index 08a24f9ba9..782f141524 100644 --- a/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift +++ b/MC1Tests/AppState/ConnectionStatusLifecycleTests.swift @@ -272,6 +272,7 @@ struct ConnectionStatusLifecycleTests { func resumeAutoFetch() async {} func setContactMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?) async -> Void) {} func setChannelMessageHandler(_ handler: @escaping @Sendable (ChannelMessage, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) {} + func setChannelDatagramHandler(_ handler: @escaping @Sendable (ChannelDatagram, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date) async -> Void) {} func setSignedMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ReceiveScope) async -> Void) {} func setCLIMessageHandler(_ handler: @escaping @Sendable (ContactMessage, ContactDTO?) async -> Void) {} } diff --git a/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift b/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift index c222fef68b..85d19c1795 100644 --- a/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift +++ b/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift @@ -65,6 +65,29 @@ struct ChatSendAdmissionTests { #expect(viewModel.sendErrorMessage == L10n.Chats.Chats.Alert.UnableToSend.message) } + @Test(arguments: [false, true]) + func `message creation rejection returns false without admitting or queuing a Message`(isChannel: Bool) async throws { + let radioID = UUID() + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + let service = MessageService(session: MeshCoreSession(transport: MockTransport()), dataStore: store, contactService: nil) + let viewModel = ChatViewModel() + viewModel.configureForTesting(dependencies: .testDefaults(dataStore: { store }, messageService: { service })) + viewModel.bindCoordinatorForTesting(ChatCoordinator.makeForTesting()) + selectConversation(viewModel, radioID: radioID, isChannel: isChannel) + let text = String(repeating: "a", count: ProtocolLimits.maxDirectMessageLength + 1) + + #expect(await !submit(text, to: viewModel, isChannel: isChannel)) + #expect(viewModel.messages.isEmpty) + #expect(viewModel.errorMessage != nil) + #expect(try await store.fetchPendingSends(radioID: radioID).isEmpty) + if let contact = viewModel.currentContact { + #expect(try await store.fetchMessages(contactID: contact.id).isEmpty) + } + if let channel = viewModel.currentChannel { + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: channel.index).isEmpty) + } + } + @Test(arguments: [false, true]) func `production tabs retain the draft when service loss wins the send handoff`(isChannel: Bool) async throws { let suiteName = "test.send-admission.\(UUID().uuidString)" diff --git a/MC1Tests/Views/Chats/Components/FragmentLayoutTests.swift b/MC1Tests/Views/Chats/Components/FragmentLayoutTests.swift index 401bac6b4d..5f32104bbe 100644 --- a/MC1Tests/Views/Chats/Components/FragmentLayoutTests.swift +++ b/MC1Tests/Views/Chats/Components/FragmentLayoutTests.swift @@ -138,12 +138,13 @@ struct FragmentLayoutTests { let expectedBoxImage = content.contains { if case .inlineImage = $0 { true } else { false } } #expect((layout.textPayload != nil) == expectedBoxText) #expect((layout.inlineImage != nil) == expectedBoxImage) + #expect((layout.mcoImage != nil) == content.contains { if case .mcoImage = $0 { true } else { false } }) // Siblings: content minus text/inlineImage, in order, exactly as the old // UnifiedMessageBubble ForEach + EmptyView arm produced them. let expectedSiblings = content.filter { switch $0 { - case .text, .inlineImage: false + case .text, .inlineImage, .mcoImage: false case .linkPreview, .mapPreview, .malwareWarning, .reactionSummary: true } } @@ -154,6 +155,7 @@ struct FragmentLayoutTests { KindScenario(name: "text only", kinds: [.text]), KindScenario(name: "text + reaction", kinds: [.text, .reactionSummary]), KindScenario(name: "text + malware + map", kinds: [.text, .malwareWarning, .mapPreview]), + KindScenario(name: "MCOimg + reaction", kinds: [.mcoImage, .reactionSummary]), KindScenario(name: "text + inline image", kinds: [.text, .inlineImage]), KindScenario(name: "text + link preview", kinds: [.text, .linkPreview]), KindScenario(name: "text + map preview", kinds: [.text, .mapPreview]), @@ -171,13 +173,14 @@ struct FragmentLayoutTests { // MARK: - Helpers enum FragmentKind: Equatable { - case text, inlineImage, linkPreview, mapPreview, malwareWarning, reactionSummary + case text, inlineImage, mcoImage, linkPreview, mapPreview, malwareWarning, reactionSummary } private static func fragment(for kind: FragmentKind) -> MessageFragment { switch kind { case .text: textFragment() case .inlineImage: inlineImageFragment() + case .mcoImage: .mcoImage(.unsupported) case .linkPreview: linkPreviewFragment case .mapPreview: mapPreviewFragment case .malwareWarning: malwareFragment @@ -189,6 +192,7 @@ struct FragmentLayoutTests { switch fragment { case .text: .text case .inlineImage: .inlineImage + case .mcoImage: .mcoImage case .linkPreview: .linkPreview case .mapPreview: .mapPreview case .malwareWarning: .malwareWarning diff --git a/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift b/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift index ebf4fd2fd9..e540442ae8 100644 --- a/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift +++ b/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift @@ -6,6 +6,16 @@ import Testing @MainActor @Suite("RoomMessageBubble accessibility label") struct RoomMessageBubbleA11yLabelTests { + @Test(arguments: ["im3:g/5WjAL`NA", "im4:AAAAA", "im5:unknown", "im3:"]) + func imageMessagesAnnounceTheirLocalizedContent(_ text: String) throws { + let message = RoomMessageDTO(sessionID: UUID(), authorKeyPrefix: Data([0xAA]), + authorName: "Alice", text: text, timestamp: 100) + let content = try #require(MCOImageCodec.content(from: text)) + let bubble = RoomMessageBubble(message: message, showTimestamp: false, showSenderName: false, showAvatar: true) + #expect(bubble.accessibilityMessageLabel == "Alice: " + content.accessibilityLabel) + #expect(!bubble.accessibilityMessageLabel.contains(text)) + } + @Test func `incoming follow-up label still includes the author`() { let message = RoomMessageDTO( diff --git a/MC1Tests/Views/Chats/MCOImageGeometryTests.swift b/MC1Tests/Views/Chats/MCOImageGeometryTests.swift new file mode 100644 index 0000000000..011ef1a480 --- /dev/null +++ b/MC1Tests/Views/Chats/MCOImageGeometryTests.swift @@ -0,0 +1,48 @@ +import MC1Services +import SwiftUI +import Testing +@testable import MC1 + +@Suite("MCOimg rendering geometry") +@MainActor +struct MCOImageGeometryTests { + private func point(_ x: Int, _ y: Int) -> MCOImageV4Point { .init(x: x, y: y) } + + @Test func vectorAnchorsUseCellCentersWithoutClampingOverscan() { + #expect(MCOImageGeometry.point(point(-1, 4)) == CGPoint(x: -0.5, y: 4.5)) + let rect = MCOImageGeometry.rectangle(point(0, 0), point(4, 4), point(4, 0)) + #expect(rect.boundingRect == CGRect(x: 0.5, y: 0.5, width: 4, height: 4)) + } + + @Test func ellipseUsesDiameterAndPerpendicularThirdPoint() throws { + let ellipse = try #require(MCOImageGeometry.ellipse(point(0, 2), point(8, 2), point(4, 4))) + #expect(ellipse.closed) + #expect(ellipse.path.boundingRect == CGRect(x: 0.5, y: 0.5, width: 8, height: 4)) + let degenerate = try #require(MCOImageGeometry.ellipse(point(0, 0), point(4, 0), point(1, 0))) + #expect(!degenerate.closed) + #expect(MCOImageGeometry.ellipse(point(0, 0), point(0, 0), point(1, 1))?.path == nil) + } + + @Test func waveDepthIsTheVisibleMidpointDisplacement() throws { + let path = try #require(MCOImageGeometry.wave(point(0, 0), point(8, 0), depth: 2)) + var control: CGPoint? + path.forEach { if case let .quadCurve(_, value) = $0 { control = value } } + #expect(control == CGPoint(x: 4.5, y: 4.5)) + #expect(path.boundingRect.maxY == 2.5) + } + + @Test func rasterPaintsExactProfileColorsAndTransparency() throws { + let image = MCOImageRaster(width: 2, height: 1, profile: 0, pixels: [0, 1], transparentColor: 0) + let renderer = ImageRenderer(content: MCOImageRenderer(content: .raster(image)).frame(width: 2, height: 1)) + renderer.scale = 1 + let rendered = try #require(renderer.cgImage) + var bytes = [UInt8](repeating: 0, count: 8) + let colorSpace = CGColorSpaceCreateDeviceRGB() + let bitmap = try #require(CGContext(data: &bytes, width: 2, height: 1, bitsPerComponent: 8, + bytesPerRow: 8, space: colorSpace, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) + bitmap.draw(rendered, in: CGRect(x: 0, y: 0, width: 2, height: 1)) + #expect(Array(bytes[0..<4]) == [0, 0, 0, 0]) + #expect(Array(bytes[4..<8]) == [0, 0, 0, 255]) + } +} diff --git a/MC1Tests/Views/Chats/MCOImageMessageTests.swift b/MC1Tests/Views/Chats/MCOImageMessageTests.swift new file mode 100644 index 0000000000..bcf56299b2 --- /dev/null +++ b/MC1Tests/Views/Chats/MCOImageMessageTests.swift @@ -0,0 +1,39 @@ +import Foundation +import MC1Services +import Testing +@testable import MC1 + +@Suite("MCOimg message content") +struct MCOImageMessageTests { + @Test func encodedPixelsBakeWithoutTextPreviewsOrTranslation() throws { + let image = MCOImageRaster(width: 2, height: 2, profile: 0, pixels: [0, 1, 1, 0]) + let body = try MCOImageV3Codec.encode(image, nonce: 42) + let text = try MCOImageCodec.text(fromAppPayload: Data([MCOImageCodec.v3Subtype]) + body) + let message = MessageFragmentBuilderFixtures.makeMessage(text: text) + let inputs = MessageFragmentBuilderFixtures.makeMinimalInputs(messageID: message.id) + let item = MessageFragmentBuilder.makeItem(for: message, inputs: inputs, + envInputs: MessageFragmentBuilderFixtures.makeEnvInputs()) + #expect(item.content == [.mcoImage(.raster(image))]) + #expect(!item.shouldRequestPreviewFetch) + #expect(item.translation == nil) + #expect(MessageLanguageDetector.dominantLanguage(for: text) == .undetermined) + let layout = FragmentLayout(content: item.content) + #expect(layout.mcoImage == .raster(image)) + #expect(layout.textPayload == nil) + #expect(layout.siblings.isEmpty) + } + + @Test func terminalPlaceholdersDifferAndParticipateInItemIdentity() { + let id = UUID() + let unsupported = MessageFragmentBuilderFixtures.makeMessage(id: id, text: "im5:anything") + let damaged = MessageFragmentBuilderFixtures.makeMessage(id: id, text: "im3:") + let inputs = MessageFragmentBuilderFixtures.makeMinimalInputs(messageID: id) + let environment = MessageFragmentBuilderFixtures.makeEnvInputs() + let first = MessageFragmentBuilder.makeItem(for: unsupported, inputs: inputs, envInputs: environment) + let second = MessageFragmentBuilder.makeItem(for: damaged, inputs: inputs, envInputs: environment) + #expect(first.content == [.mcoImage(.unsupported)]) + #expect(second.content == [.mcoImage(.damaged)]) + #expect(first != second) + #expect(Set([first, second]).count == 2) + } +} diff --git a/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift b/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift index aa836da993..0cf30530c5 100644 --- a/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift +++ b/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift @@ -197,11 +197,33 @@ struct MessageActionAvailabilityTests { #expect(availability.canBlockSender == false) } + @Test + func `channel image cannot react`() { + let message = makeMessage(channelIndex: 0, text: "im4:pixel") + let availability = MessageActionAvailability(message: message) + #expect(availability.canReact == false) + } + + @Test + func `direct image can react`() { + let message = makeMessage(contactID: UUID(), text: "im4:pixel") + let availability = MessageActionAvailability(message: message) + #expect(availability.canReact == true) + } + + @Test + func `channel text can react`() { + let message = makeMessage(channelIndex: 0, text: "Hello") + let availability = MessageActionAvailability(message: message) + #expect(availability.canReact == true) + } + // MARK: - Helper private func makeMessage( contactID: UUID? = nil, channelIndex: UInt8? = nil, + text: String = "Test", pathLength: UInt8 = 0x02, pathNodes: Data? = Data([0xA3, 0x7F]), direction: MessageDirection = .incoming, @@ -214,7 +236,7 @@ struct MessageActionAvailabilityTests { radioID: UUID(), contactID: contactID, channelIndex: channelIndex, - text: "Test", + text: text, timestamp: 0, createdAt: Date(), direction: direction, diff --git a/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift b/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift index 1ea34aef9c..071b99b25e 100644 --- a/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift +++ b/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift @@ -85,6 +85,20 @@ struct MessageFragmentBuilderTests { #expect(summary == "👍:1") } + @Test + func `channel image omits a stored reaction summary`() { + let message = makeMessage(text: "im4:pixel", reactionSummary: "👍:1", channelIndex: 0, contactID: nil) + let item = MessageFragmentBuilder.makeItem(for: message, inputs: makeInputs(messageID: message.id), envInputs: makeEnvInputs()) + #expect(item.content.map(Self.kind(of:)) == [.mcoImage]) + } + + @Test + func `direct image keeps a stored reaction summary`() { + let message = makeMessage(text: "im4:pixel", reactionSummary: "👍:1") + let item = MessageFragmentBuilder.makeItem(for: message, inputs: makeInputs(messageID: message.id), envInputs: makeEnvInputs()) + #expect(item.content.map(Self.kind(of:)) == [.mcoImage, .reactionSummary]) + } + /// Adding a reaction must flip `MessageItem.hashValue` so the diffable /// data source reloads the cell. Without this, an in-progress reaction /// add would not visibly update until another property (status, etc.) @@ -621,6 +635,8 @@ struct MessageFragmentBuilderTests { text: String = "hello", status: MessageStatus = .sent, reactionSummary: String? = nil, + channelIndex: UInt8? = nil, + contactID: UUID? = Self.contactID, linkPreviewURL: String? = nil, linkPreviewTitle: String? = nil, heardRepeats: Int = 0, @@ -632,8 +648,8 @@ struct MessageFragmentBuilderTests { MessageDTO( id: id, radioID: Self.radioID, - contactID: Self.contactID, - channelIndex: nil, + contactID: contactID, + channelIndex: channelIndex, text: text, timestamp: UInt32(Self.referenceDate.timeIntervalSince1970), createdAt: Self.referenceDate, @@ -815,13 +831,14 @@ struct MessageFragmentBuilderTests { } private enum FragmentKind: Equatable { - case text, inlineImage, linkPreview, mapPreview, malwareWarning, reactionSummary + case text, inlineImage, mcoImage, linkPreview, mapPreview, malwareWarning, reactionSummary } private static func kind(of fragment: MessageFragment) -> FragmentKind { switch fragment { case .text: .text case .inlineImage: .inlineImage + case .mcoImage: .mcoImage case .linkPreview: .linkPreview case .mapPreview: .mapPreview case .malwareWarning: .malwareWarning diff --git a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift new file mode 100644 index 0000000000..99f93b2569 --- /dev/null +++ b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift @@ -0,0 +1,46 @@ +import MC1Services +import Testing +@testable import MC1 + +@Suite("Pixel paint drafts") +@MainActor +struct PixelPaintDraftTests { + @Test func paintingInterpolatesAndRetainsPixelsAcrossEditorSessions() { + let draft = PixelPaintDraft() + draft.paint(x: 0, y: 0) + draft.paint(x: PixelPaintDraft.side - 1, y: PixelPaintDraft.side - 1) + draft.endStroke() + draft.isStaged = true + let staged = draft.image + for index in 0.. String? in + if let label = object.accessibilityLabel { return "\(type(of: object)): \(label) [\((object as? UIView)?.accessibilityIdentifier ?? "")]" } + return nil + } + Issue.record("Window accessibility labels: \(labels)") + throw error + } + draft.paint(x: 1, y: 2) + draft.endStroke() + let pixels = draft.image + appState.connectionManager.setTestState(connectionState: .disconnected, connectedDevice: .some(nil)) + #expect(controller.presentedViewController != nil) + #expect(draft.image == pixels) + try #require(await activate(L10n.Localizable.Common.done, in: try #require(controller.presentedViewController).view)) + try await waitUntil("Done should dismiss the editor") { controller.presentedViewController == nil } + #expect(draft.isStaged) + #expect(draft.image == pixels) + presentation.isPresented = true + try await waitUntil("Editor should reopen") { controller.presentedViewController != nil } + #expect(draft.image == pixels) + try #require(await activate(L10n.Localizable.Common.done, in: try #require(controller.presentedViewController).view)) + try await waitUntil("Done should dismiss the editor") { controller.presentedViewController == nil } + #expect(draft.image == pixels) + } + + @Test func normalHardwareSendStagesImageWithoutClearingExistingText() async throws { + let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + appState.connectionManager.setTestState(connectionState: .ready) + let model = InputModel() + let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + window.rootViewController = UIHostingController(rootView: InputHarness(model: model).environment(\.appState, appState)) + window.makeKeyAndVisible() + defer { + window.isHidden = true + window.rootViewController = nil + window.windowScene = nil + appState.shutdown() + } + try await waitUntil { descendants(window).contains { $0 is ChatComposerUITextView } } + let composer = try #require(descendants(window).compactMap { $0 as? ChatComposerUITextView }.first) + #expect(composer.onSend?() == true) + #expect(model.imageSubmissions == 1) + #expect(model.textSubmissions == 0) + #expect(model.text == InputModel.originalText) + try await Task.sleep(for: .milliseconds(50)) + #expect(composer.onSend?() == false) + #expect(model.imageSubmissions == 1) + } + + private struct Harness: View { + let draft: PixelPaintDraft + @Bindable var presentation: Presentation + var body: some View { + Color.clear + .fullScreenCover(isPresented: $presentation.isPresented) { PixelPaintEditor(draft: draft) } + .onAppear { presentation.isReady = true } + } + } + + @Observable + @MainActor + final class Presentation { + var isPresented = false + var isReady = false + } + + @Observable + @MainActor + final class InputModel { + static let originalText = String(repeating: "Existing text ", count: 20) + var text = originalText + var imageSubmissions = 0 + var textSubmissions = 0 + var submitting = false + } + + private struct InputHarness: View { + @Bindable var model: InputModel + var body: some View { + ChatInputBar(text: $model.text, focusRequest: 0, placeholder: "Text", maxBytes: 150, + isEncrypted: true, leading: { EmptyView() }, + onSend: { _ in model.textSubmissions += 1 }, hasAttachment: true, + isSubmittingAttachment: model.submitting, onSendAttachment: { + model.submitting = true + model.imageSubmissions += 1 + }) + } + } + + private func activate(_ identifier: String, in window: UIView) async -> Bool { + for _ in 0..<100 { + window.layoutIfNeeded() + if let object = descendants(window).first(where: { $0.accessibilityLabel == identifier }) { + if let button = object as? UIButton { + if button.allControlEvents.contains(.primaryActionTriggered) { button.performPrimaryAction() } else { button.sendActions(for: .touchUpInside) } + return true + } + if object.accessibilityActivate() { return true } + } + try? await Task.sleep(for: .milliseconds(20)) + } + return false + } + + private func descendants(_ root: NSObject) -> [NSObject] { + var seen: Set = [] + var result: [NSObject] = [] + func visit(_ object: NSObject) { + guard seen.insert(ObjectIdentifier(object)).inserted else { return } + result.append(object) + if let view = object as? UIView { view.subviews.forEach(visit) } + let count = object.accessibilityElementCount() + if count != NSNotFound, count > 0 { + for index in 0.. Bool = { cancelled.withLock { $0 } } - let message = PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp) try await withTaskCancellationHandler { if let floodScope { try await requestResponseSerializer.withSerialization(resumeCallerOnCancel: false) { [self] in diff --git a/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift b/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift index 83edd461af..1460659203 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift @@ -11,11 +11,11 @@ struct ChannelSendSerializationTests { private static let secondScope = FloodScope.region("Beta") private static let selectedScope = FloodScope.region("Gamma") - @Test - func `concurrent channel sends and scope writes keep each send together`() async throws { + @Test(arguments: [false, true]) + func `concurrent channel sends and scope writes keep each send together`(binary: Bool) async throws { let (session, transport) = try await startSession() let first = Task { - try await session.sendChannelMessage( + try await send(session: session, binary: binary, channel: Self.firstChannel, text: "first", timestamp: Self.timestamp, floodScope: .scope(Self.firstScope) ) @@ -24,7 +24,7 @@ struct ChannelSendSerializationTests { #expect(await transport.sentData[1] == PacketBuilder.setFloodScope(Self.firstScope.scopeKey())) let second = Task { - try await session.sendChannelMessage( + try await send(session: session, binary: binary, channel: Self.secondChannel, text: "second", timestamp: Self.timestamp, floodScope: .scope(Self.secondScope) ) @@ -35,9 +35,9 @@ struct ChannelSendSerializationTests { await transport.simulateOK() try await waitForFrameCount(3, transport: transport) - #expect(await transport.sentData[2] == PacketBuilder.sendChannelMessage( + #expect(await transport.sentData[2] == (try command(binary: binary, channel: Self.firstChannel, text: "first", timestamp: Self.timestamp - )) + ))) await transport.simulateOK() try await waitForFrameCount(4, transport: transport) #expect(await transport.sentData[3] == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) @@ -56,11 +56,12 @@ struct ChannelSendSerializationTests { let frames = await Array(transport.sentData.dropFirst()) let secondScopeFrame = PacketBuilder.setFloodScope(Self.secondScope.scopeKey()) let secondScopeIndex = try #require(frames.firstIndex(of: secondScopeFrame)) - #expect(frames[secondScopeIndex + 1] == PacketBuilder.sendChannelMessage( + #expect(frames[secondScopeIndex + 1] == (try command(binary: binary, channel: Self.secondChannel, text: "second", timestamp: Self.timestamp - )) + ))) #expect(frames[secondScopeIndex + 2] == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) - #expect(frames.filter { $0.first == CommandCode.sendChannelMessage.rawValue }.count == 2) + let commandCode = binary ? CommandCode.sendChannelData : CommandCode.sendChannelMessage + #expect(frames.filter { $0.first == commandCode.rawValue }.count == 2) await session.stop() } @@ -174,6 +175,26 @@ struct ChannelSendSerializationTests { await session.stop() } + private func command(binary: Bool, channel: UInt8, text: String, timestamp: Date) throws -> Data { + if binary { + return try PacketBuilder.sendChannelData(channelIndex: channel, dataType: 0x0120, payload: Data(text.utf8)) + } + return PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp) + } + + private func send( + session: MeshCoreSession, binary: Bool, channel: UInt8, text: String, + timestamp: Date, floodScope: ResolvedFloodScope + ) async throws { + if binary { + try await session.sendChannelData( + channelIndex: channel, dataType: 0x0120, payload: Data(text.utf8), floodScope: floodScope + ) + } else { + try await session.sendChannelMessage(channel: channel, text: text, timestamp: timestamp, floodScope: floodScope) + } + } + private func waitForFrameCount(_ count: Int, transport: MockTransport) async throws { try await waitUntil("Expected at least \(count) frames") { await transport.sentData.count >= count diff --git a/scripts/mcoimg/README.md b/scripts/mcoimg/README.md new file mode 100644 index 0000000000..347834b569 --- /dev/null +++ b/scripts/mcoimg/README.md @@ -0,0 +1,208 @@ +# MCOimg compatibility checks + +The codec target is HDDen/meshcore-open tag `9.5.1-mod-1.9.0`, commit +`fe375741226588440e268002b4975349b2e95ffe`. The Dart codec, palette tables, +model, MCOtxt generation-0 tables, and Flutter painter at that commit are the +normative sources. The upstream code is GPL-3.0, as is MeshCore One. + +The Swift v3 decoder fixtures are copied from the upstream JavaScript fixture +exchange. `verify-v3.swift` runs every fixture and writes Swift encoder output. +The Swift encoder deliberately searches a smaller candidate set than Dart; +decoded pixels, rather than identical compressed bytes, establish compatibility. + +V4 has no published cross-runtime fixture exchange. Its fixture JSON records +streams independently assembled by the later upstream command tests, decoded +by the tagged Dart codec. `export_v4_reference.py` instruments those tests to +export document dumps and rejection classes. The assembly source revision and +export command must accompany regenerated fixture evidence. Text and raster +layers are compared as decoded values; platform fonts and antialiasing are +client choices. + +`measure_wire_cost_test.dart` measures v3 raster and v4 mixed encodings of the +same pixels. Copy it into the reference package's `test/helpers/` and run +`flutter test test/helpers/measure_wire_cost_test.dart` with +`MCOIMG_COST_OUTPUT` set to the desired JSON path. It includes the UTF-8 sender +envelope for GROUP_DATA and the complete Base91 wrappers and sender prefix for +text transport. A mixed raster still uses v3 internally. DMs send v3 text; +channels send only v4 mixed GROUP_DATA (`0x0120`, subtype/version `0x14`). +Channels never fall back to text, including on older firmware. A radio that +rejects GROUP_DATA follows the existing failed-send path. + +A new image Send uses a fresh nonce before measuring its destination envelope. +Send Again refreshes and persists the prepared content before queue capture. +Automatic retries retain the nonce, matching the tagged client's +`_preparedOutboundTexts` and deferred `binaryOutbound` behavior. DM ACK prediction +uses its exact text. Binary channel images have no sender timestamp and do not +enter the text reaction index. + +To reproduce v3 verification from the MeshCore One worktree: + +```sh +mkdir -p tmp/mcoimg-module-cache +swiftc -parse-as-library -module-cache-path tmp/mcoimg-module-cache \ + MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3*.swift \ + MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageRaster.swift \ + MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette*.swift \ + MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift \ + MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBit*.swift \ + MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodecError.swift \ + scripts/mcoimg/verify-v3.swift -o tmp/mcoimg-v3-verify +tmp/mcoimg-v3-verify scripts/mcoimg/fixtures/v3-upstream-decoder.json \ + scripts/mcoimg/fixtures/v3-swift-encoded.json +``` + +This checks all 39 upstream fixtures and generates 73 Swift bodies: those same +images, a painted 16×16 image, a dense 16×16 image, and all 16 palette profiles +with nonce values 0 and 255. It also verifies Swift Base91 decoding against the +upstream text fixtures. The generated text and app payload fields always refer +to the generated body. + +From the tagged upstream Flutter package, run the independent verifier using +absolute paths to this worktree: + +```sh +MCOIMG_FIXTURES=/absolute/worktree/scripts/mcoimg/fixtures/v3-swift-encoded.json \ + flutter test --no-pub /absolute/worktree/scripts/mcoimg/verify-v3.dart +``` + +The verifier invokes the tagged Dart `MCOImageV3Codec` for body, app payload, +and text decoding and compares every pixel, palette profile, dimension, and +transparent color. It runs under Flutter because the original palette code +imports `dart:ui`. A minimal verification pubspec needs `flutter`, `crypto`, +and `flutter_test`; do not substitute codec or palette implementations. +`MCOImageV3CodecTests` additionally covers malformed dimensions, unknown +algorithm IDs, nonzero padding, every fixture truncation, trailing bytes, +invalid color references, nonce changes, and exact palette anchors. + + +## Swift v4 mixed raster verification + +`verify-v4-raster.swift` wraps all 73 Swift v3 fixtures and seven dimension-mode +boundaries as v4 mixed documents. It checks Swift decode equality and writes +`fixtures/v4-swift-raster.json`. Build it with the same v3 sources above plus +`MCOImageV4*.swift`, `MCOImageCodec.swift`, `MCOImageContent.swift`, +`MCOImageFigure.swift`, and `MCOText*.swift`, substituting the verifier filename. +Then run the unchanged tagged Dart codec from its Flutter package: + +```sh +MCOIMG_FIXTURES=/absolute/worktree/scripts/mcoimg/fixtures/v4-swift-raster.json \ + flutter test --no-pub /absolute/worktree/scripts/mcoimg/verify-v4-raster.dart +``` + +Dart compares every raster pixel, dimension, palette, transparency, origin, mixed +mode and nonce for both body and text decoding. Transparent rasters preserve a +nil document background. The seven white-raster dimension cases also reproduce +the tagged encoder's canonical bytes. These are locally generated +cross-runtime checks, not a published upstream v4 fixture exchange. The wrapper +retains Swift's selected v3 compression; it does not claim the Dart optimizer +would choose identical compressed bytes. + +## Scope and retained state + +DMs and channels render v3 and v4 text. Channels also receive the registered +`0x0120` binary envelope, including during initial sync. Rooms render both text +versions through the shared renderer; their separate composer has no paint +entry. Outgoing DM drawings use v3 text; channel drawings use v4 mixed binary +GROUP_DATA. Both retain the existing service-owned queue and stored text content. +The channel `im4:` value is an internal persistence representation; it is never +sent as channel text. No queue or persisted payload field was added. Legacy v3 +queued channel images are deterministically wrapped as v4 at transmission, +preserving their compressed raster bytes and nonce. User retry upgrades and +persists v4 before capturing its queue envelope. + +The fixed 16×16 Master 8 editor supports painting and erasing with palette +colors. Done stages its pixels for the normal Send button. It never modifies +composer text. The conversation input owns unsent pixels in memory until +admission or conversation closure; closing the app also discards those pixels. +Reopening the editor resumes them. Encoding runs off the main actor from an +immutable snapshot. Editing is disabled during admission. Disconnection and +encoding/admission failure retain the drawing. Closing the conversation cancels +encoding before admission; after persistence, the service queue owns the send +and continues after UI dismissal. Existing text remains a separate Draft. + +V4 rendering clips overscan geometry, preserves paint order, uses cell-center +vector anchors and cell-edge raster origins, non-zero fills, square stroke caps, +miter joins with the reference painter's limit, and circular dots. Open paths +close for fill only. Text uses system fonts and client line metrics, which are +not specified as pixel-identical across platforms. Raster-only v4 mode and +unknown extensions show the unsupported placeholder; damaged documents show +the damaged placeholder without partially painting. + +V4 capability limits are 4,096 expanded figures and 64 nested groups. Limits +are checked before allocating repeat expansion, including zero-delta runs; +exceeding them is unsupported, rather than damaged. + +## Measured cost and validation + +The tagged Dart encoders measured the same 16×16 cross (nonce 42) as follows. +The sender is `Radio` (5 UTF-8 bytes). Values include all application envelopes. + +| Representation | V3 raster | V4 mixed | +| --- | ---: | ---: | +| Body | 28 | 34 | +| Binary channel application payload | 35 | 41 | +| Binary flood host command | 40 | 46 | +| Complete text wrapper | 40 | 46 | +| Channel text including `Radio: ` | 47 | 53 | +| Channel text host command | 47 | 53 | +| DM text host command | 53 | 59 | + +The binary app budget is 165 bytes. The text budget is 150 UTF-8 bytes for a +DM, and `139 - senderNameUTF8Bytes - 2` for a channel (132 for `Radio`, 128 for +`救援隊`). The editor measures the final random-nonce v3 text for a DM, or the +complete v4 binary sender envelope for a channel. The service revalidates the +current sender name at drain. A stored Base91 string can exceed the channel +text budget while its binary envelope fits. V4 mixed adds document fields around +the compressed v3 raster; v4 raster-only mode remains reserved. V3 is the smaller +DM pixel format; channels use v4 binary so clients without MCOimg do not display +encoded text. +Host command sizes include command/header fields and the binary data type; +RF routing, encryption padding and airtime vary with the actual radio path. + +On 2026-10-26: + +- All 39 published upstream v3 decoder fixtures matched exactly. +- Tagged Dart independently decoded 73 Swift-generated images through body, + app payload and text paths, including every palette profile and nonce variants. +- Swift matched 126 v4 tagged-decoder document/error fixtures and 17 MCOtxt + vectors covering the seven frozen generation-0 language tables. The independent + command assembly's canonical encoder assertions also passed under tagged Dart. +- 2,370 MC1Services tests passed serially after the binary channel change, + including backup, receive, send queue, pool backoff, retry and disconnect suites. +- All 538 MeshCore tests passed, including text/binary scope serialization and + cancellation/ACK ordering. +- Tagged Dart independently decoded 80 Swift v4 mixed rasters. Seven white-raster + dimension cases matched its canonical encoder bytes exactly. +- 65 focused app regressions passed after the binary change on iPhone 17e/iOS + 27.0. Two presentation tests passed separately: full-screen cover, dismissal guard, + upper-right Done, retained pixels on reopen/disconnect, and hardware Send + preserving the existing text while preventing repeated submission. +- SwiftLint and whitespace checks passed. SwiftGen was regenerated and stable. + The final simulator build passed with three warnings in unchanged concurrency + code (`MessageBubbleSecondaryClick` and `MessagePathPreviewSnapshot`). + +The normal pinned simulator was occupied by another chat, so app verification +used an isolated iPhone 17e on the same iOS 27.0 runtime. No physical-radio +exchange or published v4 cross-runtime fixture set was available. New strings +use L10n in all twelve locales; non-English additions are marked English +translation placeholders, following the repository localization workflow. + +## Binary channel change preflight + +| Check | Result | +| --- | --- | +| SwiftLint | Passed, zero violations | +| Project generation | `make test-app` regenerated the project; project.yml unchanged | +| SwiftGen | Regenerated, output unchanged | +| UI copy and state naming | No new strings; L10n and errorMessage retained | +| Persistence/backup | No stored-field or DTO schema changes; full backup suite passed | +| Build | iPhone 17e/iOS 27.0 passed; three pre-existing concurrency warnings | +| Whitespace | `git diff --check` passed | + +Binary tests cover inline/pending/resend, legacy v3 replay across disconnect, +TABLE_FULL backoff and durable replay, stable automatic nonces, prepared user +resends, malformed/unsupported rejection without text fallback, and UTF-8 +165/166-byte boundaries at admission and drain. The two presentation tests passed +on the isolated simulator after its accessibility service was initialized with +MobileBuildMCP `snapshot_ui`; an inactive service returns an empty in-process +SwiftUI accessibility tree. No physical-radio exchange was available. diff --git a/scripts/mcoimg/export_text_reference.dart b/scripts/mcoimg/export_text_reference.dart new file mode 100644 index 0000000000..7751bff485 --- /dev/null +++ b/scripts/mcoimg/export_text_reference.dart @@ -0,0 +1,75 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/MCOtxt/mcotxt.dart'; + +// Independent MSB-first field assembly exercises every frozen prediction entry. +class _Bits { + final bits = []; + void put(int value, int count) { + for (var index = count - 1; index >= 0; index--) { + bits.add((value >> index) & 1); + } + } + Uint8List get bytes { + final result = Uint8List((bits.length + 7) ~/ 8); + for (var index = 0; index < bits.length; index++) { + result[index ~/ 8] |= bits[index] << (7 - index % 8); + } + return result; + } +} + +void main() { + test('export frozen generation 0 decoder vectors', () { + final fixtures = >[]; + void record(String name, Uint8List bytes, int length, String text) { + expect(MCOtxtCodec.decode(bytes, bitLength: length).text, text); + fixtures.add({'name':name,'dataBase64':base64.encode(bytes),'bitLength':length,'text':text}); + } + for (final model in MCOtxtModelRegistry.latest.models) { + final b = _Bits()..put(1,3)..put(0,3)..put(model.id.wireId,3)..put(7,3); + final expected = []; + void literal(int index) { + if (index < model.primarySymbols.length) { b.put(2,2); b.put(index,5); } + else { b.put(14,4); b.put(index-model.primarySymbols.length,5); } + } + void rank(int rank) { + const values = [0,2,6,7]; + const lengths = [2,3,4,4]; + b.put(values[rank],lengths[rank]); + } + for (var index=0; index>{}; +Object? _color(MCOImageV4Document d, int? value) => value == null ? null : d.palette[value]; +Map _style(MCOImageV4Document d, MCOImageV4Style s) => { + 'fillColor': _color(d, s.fillColor), 'strokeColor': _color(d, s.strokeColor), 'strokeWidth': s.strokeWidth, +}; +List _point(MCOImageV4Point p) => [p.x, p.y]; +Map _figure(MCOImageV4Document d, MCOImageV4Figure f) { + final result = {'style': _style(d, f.style)}; + switch (f) { + case MCOImageV4Dot(:final point): result.addAll({'kind':'dot','point':_point(point)}); + case MCOImageV4Line(:final start,:final end): result.addAll({'kind':'line','start':_point(start),'end':_point(end)}); + case MCOImageV4Rect(:final first,:final second,:final third): result.addAll({'kind':'rectangle','first':_point(first),'second':_point(second),'third':_point(third)}); + case MCOImageV4Ellipse(:final first,:final second,:final third): result.addAll({'kind':'ellipse','first':_point(first),'second':_point(second),'third':_point(third)}); + case MCOImageV4Path(:final points,:final closed): result.addAll({'kind':'path','points':points.map(_point).toList(),'closed':closed}); + case MCOImageV4Wave(:final start,:final end,:final depth,:final closed): result.addAll({'kind':'wave','start':_point(start),'end':_point(end),'depth':depth,'closed':closed}); + case MCOImageV4Text(:final origin,:final fontSize,:final align,:final text): result.addAll({'kind':'text','origin':_point(origin),'width':f.resolvedWidth(d.width),'fontSize':fontSize,'alignment':align.index,'text':text}); + case MCOImageV4Group(:final figures): result.addAll({'kind':'group','figures':figures.map((child)=>_figure(d,child)).toList()}); + case MCOImageV4RasterLayer(:final x,:final y,:final width,:final height,:final pixels,:final transparentColor): result.addAll({'kind':'raster','origin':[x,y],'width':width,'height':height,'profile':d.paletteProfile.index,'pixels':pixels,'transparentColor':transparentColor}); + } + return result; +} +DecodedMCOImageV4 _recordDecode(Uint8List body) { + final key = base64.encode(body); + try { + final decoded = _codec.decodeBody(body); + final d = decoded.document; + _recorded[key] = {'bodyBase64':key,'document':{ + 'width':d.width,'height':d.height,'profile':d.paletteProfile.index, + 'backgroundColor':_color(d,d.backgroundColor),'figures':d.figures.map((f)=>_figure(d,f)).toList(), + 'targetName':decoded.targetName,'replyTimestamp':decoded.replyTimestamp, + }}; + return decoded; + } catch(error) { + _recorded[key] = {'bodyBase64':key,'error':error is MCOImageUnsupportedFormatException ? 'unsupported':'damaged'}; + rethrow; + } +} +''' +metadata = "'decoderTag':'9.5.1-mod-1.9.0','decoderCommit':'fe375741226588440e268002b4975349b2e95ffe','assemblyCommit':'d388ee8444078635d74dd98ab288269c3a8a9162','source':'independent command-test bit assembly','fixtures':_recorded.values.toList()" +source = source.replace("void main() {", "void main() {\n tearDownAll(() {\n File(" + repr(str(destination / "MCOimgV4Fixtures.json")) + ").writeAsStringSync(const JsonEncoder.withIndent(' ').convert({" + metadata + "}));\n });", 1) +source += helper +output = upstream / "test/helpers/mcoimg_v4_export_test.dart" +output.write_text(source) +print("flutter test test/helpers/mcoimg_v4_export_test.dart") diff --git a/scripts/mcoimg/fixtures/v3-swift-encoded.json b/scripts/mcoimg/fixtures/v3-swift-encoded.json new file mode 100644 index 0000000000..a8b74dbcf5 --- /dev/null +++ b/scripts/mcoimg/fixtures/v3-swift-encoded.json @@ -0,0 +1,2073 @@ +{ + "fixtures" : [ + { + "appPayloadBase64" : "E3oBjQBCvgE=", + "bodyBase64" : "egGNAEK+AQ==", + "height" : 2, + "name" : "swift-rawGlobal", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 1, + 2, + 3, + 3, + 2, + 1, + 0 + ], + "text" : "im3:g\/5WjAL`NA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3ohjVAg1g==", + "bodyBase64" : "eiGNUCDW", + "height" : 2, + "name" : "swift-rawLocal", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "text" : "im3:g\/oZ74qiN", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3ohjVAgxg==", + "bodyBase64" : "eiGNUCDG", + "height" : 2, + "name" : "swift-compactRle", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 0 + ], + "text" : "im3:g\/oZ74qiM", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oBjQDCwwA=", + "bodyBase64" : "egGNAMLDAA==", + "height" : 2, + "name" : "swift-compactSparse", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 3, + 0, + 0, + 3, + 0, + 0 + ], + "text" : "im3:g\/5WjA0KGA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3ohjVAg1g==", + "bodyBase64" : "eiGNUCDW", + "height" : 2, + "name" : "swift-biColorMask", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "text" : "im3:g\/oZ74qiN", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oBjVAg1g==", + "bodyBase64" : "egGNUCDW", + "height" : 2, + "name" : "swift-rowRepeat", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "text" : "im3:g\/5W74qiN", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oBjVAg1g==", + "bodyBase64" : "egGNUCDW", + "height" : 2, + "name" : "swift-lzPixels", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "text" : "im3:g\/5W74qiN", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oBBCA8", + "bodyBase64" : "egEEIDw=", + "height" : 2, + "name" : "swift-quadtree", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 3, + 0 + ], + "text" : "im3:g\/N\"XL8A", + "transparentColor" : null, + "width" : 2 + }, + { + "appPayloadBase64" : "E3oBjQBC5A4=", + "bodyBase64" : "egGNAELkDg==", + "height" : 2, + "name" : "swift-bitplanesRawAndRle", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 1, + 0, + 1, + 2, + 3, + 2, + 3 + ], + "text" : "im3:g\/5WjA~LcB", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3ohjVAg1g==", + "bodyBase64" : "eiGNUCDW", + "height" : 2, + "name" : "swift-adaptiveBitplanesRaw", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "text" : "im3:g\/oZ74qiN", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oIjQCCaKwP", + "bodyBase64" : "egiNAIJorA8=", + "height" : 2, + "name" : "swift-directBitplanes", + "paletteProfile" : "grayscale8", + "pixels" : [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "text" : "im3:g\/WXjA`X9]D", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oBjVAg1g==", + "bodyBase64" : "egGNUCDW", + "height" : 2, + "name" : "swift-compactRowDelta", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "text" : "im3:g\/5W74qiN", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oIjQCCaIgG", + "bodyBase64" : "egiNAIJoiAY=", + "height" : 2, + "name" : "swift-directRowDelta", + "paletteProfile" : "grayscale8", + "pixels" : [ + 0, + 1, + 2, + 3, + 0, + 1, + 2, + 3 + ], + "text" : "im3:g\/WXjA`XA5B", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oBjVAg1g==", + "bodyBase64" : "egGNUCDW", + "height" : 2, + "name" : "swift-rowDelta", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "text" : "im3:g\/5W74qiN", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3ohjVAgxg==", + "bodyBase64" : "eiGNUCDG", + "height" : 2, + "name" : "swift-varUintRle", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 0 + ], + "text" : "im3:g\/oZ74qiM", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oBjQDCwwA=", + "bodyBase64" : "egGNAMLDAA==", + "height" : 2, + "name" : "swift-varUintSparse", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 3, + 0, + 0, + 3, + 0, + 0 + ], + "text" : "im3:g\/5WjA0KGA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3pBHRDGMQ==", + "bodyBase64" : "ekEdEMYx", + "height" : 1, + "name" : "swift-adaptiveLegacyRle", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 0, + 0, + 0, + 3, + 3, + 3, + 3 + ], + "text" : "im3:g\/XceL~JD", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "E3pBHQAm\/Q==", + "bodyBase64" : "ekEdACb9", + "height" : 1, + "name" : "swift-adaptiveShortRle", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 0, + 3, + 3, + 3, + 0, + 0, + 0 + ], + "text" : "im3:g\/XcHAA]H", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "E3pBHQAM", + "bodyBase64" : "ekEdAAw=", + "height" : 1, + "name" : "swift-adaptiveConstantZero", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "text" : "im3:g\/XcHAMA", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "E3oBHTAM", + "bodyBase64" : "egEdMAw=", + "height" : 1, + "name" : "swift-adaptiveConstantOne", + "paletteProfile" : "master4", + "pixels" : [ + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3 + ], + "text" : "im3:g\/5WXDASAwD>W", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E3oPDQASLFm0ZA==", + "bodyBase64" : "eg8NABIsWbRk", + "height" : 1, + "name" : "swift-paletteOrderedSingleBank", + "paletteProfile" : "dynamicGlobal512", + "pixels" : [ + 193, + 201, + 209, + 201 + ], + "text" : "im3:g\/>XDA|hXDASAOJTX", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwBCPGUzmYRZVVUJAGBCFXgCAJiqqgI=", + "bodyBase64" : "AEI8ZTOZhFlVVQkAYEIVeAIAmKqqAg==", + "height" : 16, + "name" : "swift-painted16", + "paletteProfile" : "master8", + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 3, + 3, + 3, + 3, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 3, + 3, + 3, + 3, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 3, + 3, + 3, + 3, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 3, + 3, + 3, + 3, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "text" : "im3:TA^v2j[+OiC8u0AA!urtnA@QB8qA", + "transparentColor" : null, + "width" : 16 + }, + { + "appPayloadBase64" : "E\/8FPCBAJM5EZd5Ipu5M5\/7dG0zlnWztH431ka16A85Gxv5SiS9eTFzX+k\/n\/oz38s3H9g504s1IJx9cbGxwob3R2U\/pX63B1Q7ZW2xuwc1KiD9mT61CBh\/LuE\/rsM3LuE\/rsM1ooM1M6V9wIu5Ua3zFl0\/tEe7Vm4z9FS9ij81OSnx6BS9mwN3\/dk\/vcg7ffs3Peoxcbs1Qq5xE6G94JT\/5VU\/x0y7pUQ7h3+1WTc1SDL1Oy6xKipzzNE\/zNE\/zNE\/zNE8=", + "bodyBase64" : "\/wU8IEAkzkRl3kim7kzn\/t0bTOWdbO0fjfWRrXoDzkbG\/lKJL15MXNf6T+f+jPfyzcf2DnTizUgnH1xsbHChvdHZT+lfrcHVDtlbbG7BzUqIP2ZPrUIGH8u4T+uwzcu4T+uwzWigzUzpX3Ai7lRrfMWXT+0R7tWbjP0VL2KPzU5KfHoFL2bA3f92T+9yDt9+zc96jFxuzVCrnETob3glP\/lVT\/HTLulRDuHf7VZNzVIMvU7LrEqKnPM0T\/M0T\/M0T\/M0Tw==", + "height" : 16, + "name" : "swift-dense16", + "paletteProfile" : "master64", + "pixels" : [ + 0, + 17, + 34, + 51, + 4, + 21, + 38, + 55, + 8, + 25, + 42, + 59, + 12, + 29, + 46, + 63, + 29, + 47, + 1, + 19, + 37, + 55, + 9, + 27, + 45, + 63, + 17, + 35, + 53, + 7, + 25, + 43, + 58, + 13, + 32, + 51, + 6, + 25, + 44, + 63, + 18, + 37, + 56, + 11, + 30, + 49, + 4, + 23, + 23, + 43, + 63, + 19, + 39, + 59, + 15, + 35, + 55, + 11, + 31, + 51, + 7, + 27, + 47, + 3, + 52, + 9, + 30, + 51, + 8, + 29, + 50, + 7, + 28, + 49, + 6, + 27, + 48, + 5, + 26, + 47, + 17, + 39, + 61, + 19, + 41, + 63, + 21, + 43, + 1, + 23, + 45, + 3, + 25, + 47, + 5, + 27, + 46, + 5, + 28, + 51, + 10, + 33, + 56, + 15, + 38, + 61, + 20, + 43, + 2, + 25, + 48, + 7, + 11, + 35, + 59, + 19, + 43, + 3, + 27, + 51, + 11, + 35, + 59, + 19, + 43, + 3, + 27, + 51, + 40, + 1, + 26, + 51, + 12, + 37, + 62, + 23, + 48, + 9, + 34, + 59, + 20, + 45, + 6, + 31, + 5, + 31, + 57, + 19, + 45, + 7, + 33, + 59, + 21, + 47, + 9, + 35, + 61, + 23, + 49, + 11, + 34, + 61, + 24, + 51, + 14, + 41, + 4, + 31, + 58, + 21, + 48, + 11, + 38, + 1, + 28, + 55, + 63, + 27, + 55, + 19, + 47, + 11, + 39, + 3, + 31, + 59, + 23, + 51, + 15, + 43, + 7, + 35, + 28, + 57, + 22, + 51, + 16, + 45, + 10, + 39, + 4, + 33, + 62, + 27, + 56, + 21, + 50, + 15, + 57, + 23, + 53, + 19, + 49, + 15, + 45, + 11, + 41, + 7, + 37, + 3, + 33, + 63, + 29, + 59, + 22, + 53, + 20, + 51, + 18, + 49, + 16, + 47, + 14, + 45, + 12, + 43, + 10, + 41, + 8, + 39, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19 + ], + "text" : "im3:m|x\"eL|LLSU,[xVdRS!=F>Fi8qj<3~:*XZMeUBNTo!h6l|yQ\/n}fLc`{]?=@]rjrU\/T&2Z6|IIXck*O&h%E\/#5!w*m$fTaDfWdrW8kE0!t=^8D$8,Us!U62bCOkI6TEKM@6nJ?w&|&{.$Orox>9Nx:Ka^FNY]A?_j#^t(@3uQyvn}.|Qrc@Sg;4Z,FMj(y9SW:9rdD78zkOtuJ&zemlZH`q4#ierO6o4Sd2P.I[y`+qjVB", + "transparentColor" : null, + "width" : 16 + }, + { + "appPayloadBase64" : "EwAADQGipQ==", + "bodyBase64" : "AAANAaKl", + "height" : 3, + "name" : "swift-profile-0-nonce-0", + "paletteProfile" : "mono", + "pixels" : [ + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 0, + 0, + 1, + 0, + 1 + ], + "text" : "im3:TAY4hA`0C", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8ADQGipQ==", + "bodyBase64" : "\/wANAaKl", + "height" : 3, + "name" : "swift-profile-0-nonce-255", + "paletteProfile" : "mono", + "pixels" : [ + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 0, + 0, + 1, + 0, + 1 + ], + "text" : "im3:m|1W(A=PF", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwABDQHCFmsM", + "bodyBase64" : "AAENAcIWaww=", + "height" : 3, + "name" : "swift-profile-1-nonce-0", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 2, + 1, + 1, + 0, + 3, + 2, + 2, + 1, + 0, + 3 + ], + "text" : "im3:TAc4hABg%xB", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8BDQHCFmsM", + "bodyBase64" : "\/wENAcIWaww=", + "height" : 3, + "name" : "swift-profile-1-nonce-255", + "paletteProfile" : "master4", + "pixels" : [ + 0, + 3, + 2, + 1, + 1, + 0, + 3, + 2, + 2, + 1, + 0, + 3 + ], + "text" : "im3:m|9W(AC$lJD", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwACDQGCu+Wk4A==", + "bodyBase64" : "AAINAYK75aTg", + "height" : 3, + "name" : "swift-profile-2-nonce-0", + "paletteProfile" : "master8", + "pixels" : [ + 0, + 7, + 6, + 5, + 5, + 4, + 3, + 2, + 2, + 1, + 0, + 7 + ], + "text" : "im3:TAg4hA$^J3\">", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8CDQGCu+Wk4A==", + "bodyBase64" : "\/wINAYK75aTg", + "height" : 3, + "name" : "swift-profile-2-nonce-255", + "paletteProfile" : "master8", + "pixels" : [ + 0, + 7, + 6, + 5, + 5, + 4, + 3, + 2, + 2, + 1, + 0, + 7 + ], + "text" : "im3:m|*W(Aj=RU}(B", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwADDQEC59W0ooEP", + "bodyBase64" : "AAMNAQLn1bSigQ8=", + "height" : 3, + "name" : "swift-profile-3-nonce-0", + "paletteProfile" : "master16", + "pixels" : [ + 0, + 7, + 14, + 5, + 13, + 4, + 11, + 2, + 10, + 1, + 8, + 15 + ], + "text" : "im3:TAk4hA?2l2T54rA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8DDQEC59W0ooEP", + "bodyBase64" : "\/wMNAQLn1bSigQ8=", + "height" : 3, + "name" : "swift-profile-3-nonce-255", + "paletteProfile" : "master16", + "pixels" : [ + 0, + 7, + 14, + 5, + 13, + 4, + 11, + 2, + 10, + 1, + 8, + 15 + ], + "text" : "im3:m|=W(A%T\/SlYW|A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAEDQECjqudLKkDeg==", + "bodyBase64" : "AAQNAQKOq50sqQN6", + "height" : 3, + "name" : "swift-profile-4-nonce-0", + "paletteProfile" : "master32", + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 4, + 11, + 18, + 26, + 1, + 8, + 15 + ], + "text" : "im3:TAo4hA$T\/#!PbK&K", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8EDQECjqudLKkDeg==", + "bodyBase64" : "\/wQNAQKOq50sqQN6", + "height" : 3, + "name" : "swift-profile-4-nonce-255", + "paletteProfile" : "master32", + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 4, + 11, + 18, + 26, + 1, + 8, + 15 + ], + "text" : "im3:m|`W(Aln1lif2UpV", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAFDQECHE7VkausB8gD", + "bodyBase64" : "AAUNAQIcTtWRq6wHyAM=", + "height" : 3, + "name" : "swift-profile-5-nonce-0", + "paletteProfile" : "master64", + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 36, + 43, + 50, + 58, + 1, + 8, + 15 + ], + "text" : "im3:TAs4hAkn#7Zz6j9AeB", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8FDQECHE7VkausB8gD", + "bodyBase64" : "\/wUNAQIcTtWRq6wHyAM=", + "height" : 3, + "name" : "swift-profile-5-nonce-255", + "paletteProfile" : "master64", + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 36, + 43, + 50, + 58, + 1, + 8, + 15 + ], + "text" : "im3:m|CX(A.>hdxMa,fBdFA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAGDQEC59W0ooEP", + "bodyBase64" : "AAYNAQLn1bSigQ8=", + "height" : 3, + "name" : "swift-profile-6-nonce-0", + "paletteProfile" : "grayscale16", + "pixels" : [ + 0, + 7, + 14, + 5, + 13, + 4, + 11, + 2, + 10, + 1, + 8, + 15 + ], + "text" : "im3:TAw4hA?2l2T54rA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8GDQEC59W0ooEP", + "bodyBase64" : "\/wYNAQLn1bSigQ8=", + "height" : 3, + "name" : "swift-profile-6-nonce-255", + "paletteProfile" : "grayscale16", + "pixels" : [ + 0, + 7, + 14, + 5, + 13, + 4, + 11, + 2, + 10, + 1, + 8, + 15 + ], + "text" : "im3:m|KX(A%T\/SlYW|A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAHDQECjqudLKkDeg==", + "bodyBase64" : "AAcNAQKOq50sqQN6", + "height" : 3, + "name" : "swift-profile-7-nonce-0", + "paletteProfile" : "grayscale32", + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 4, + 11, + 18, + 26, + 1, + 8, + 15 + ], + "text" : "im3:TA04hA$T\/#!PbK&K", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8HDQECjqudLKkDeg==", + "bodyBase64" : "\/wcNAQKOq50sqQN6", + "height" : 3, + "name" : "swift-profile-7-nonce-255", + "paletteProfile" : "grayscale32", + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 4, + 11, + 18, + 26, + 1, + 8, + 15 + ], + "text" : "im3:m|SX(Aln1lif2UpV", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAIDQGCu+Wk4A==", + "bodyBase64" : "AAgNAYK75aTg", + "height" : 3, + "name" : "swift-profile-8-nonce-0", + "paletteProfile" : "grayscale8", + "pixels" : [ + 0, + 7, + 6, + 5, + 5, + 4, + 3, + 2, + 2, + 1, + 0, + 7 + ], + "text" : "im3:TA44hA$^J3\">", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8IDQGCu+Wk4A==", + "bodyBase64" : "\/wgNAYK75aTg", + "height" : 3, + "name" : "swift-profile-8-nonce-255", + "paletteProfile" : "grayscale8", + "pixels" : [ + 0, + 7, + 6, + 5, + 5, + 4, + 3, + 2, + 2, + 1, + 0, + 7 + ], + "text" : "im3:m|aX(Aj=RU}(B", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAJDQGCu+Wk4A==", + "bodyBase64" : "AAkNAYK75aTg", + "height" : 3, + "name" : "swift-profile-9-nonce-0", + "paletteProfile" : "dynamicGlobal8", + "pixels" : [ + 0, + 484, + 401, + 283, + 283, + 210, + 91, + 63, + 63, + 83, + 0, + 484 + ], + "text" : "im3:TA84hA$^J3\">", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8JDQGCu+Wk4A==", + "bodyBase64" : "\/wkNAYK75aTg", + "height" : 3, + "name" : "swift-profile-9-nonce-255", + "paletteProfile" : "dynamicGlobal8", + "pixels" : [ + 0, + 484, + 401, + 283, + 283, + 210, + 91, + 63, + 63, + 83, + 0, + 484 + ], + "text" : "im3:m|iX(Aj=RU}(B", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAKDQEC59W0ooEP", + "bodyBase64" : "AAoNAQLn1bSigQ8=", + "height" : 3, + "name" : "swift-profile-10-nonce-0", + "paletteProfile" : "dynamicGlobal16", + "pixels" : [ + 0, + 210, + 492, + 155, + 447, + 118, + 338, + 63, + 310, + 84, + 246, + 511 + ], + "text" : "im3:TA$4hA?2l2T54rA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8KDQEC59W0ooEP", + "bodyBase64" : "\/woNAQLn1bSigQ8=", + "height" : 3, + "name" : "swift-profile-10-nonce-255", + "paletteProfile" : "dynamicGlobal16", + "pixels" : [ + 0, + 210, + 492, + 155, + 447, + 118, + 338, + 63, + 310, + 84, + 246, + 511 + ], + "text" : "im3:m|qX(A%T\/SlYW|A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwALDQECjqudLKkDeg==", + "bodyBase64" : "AAsNAQKOq50sqQN6", + "height" : 3, + "name" : "swift-profile-11-nonce-0", + "paletteProfile" : "dynamicGlobal32", + "pixels" : [ + 0, + 118, + 237, + 347, + 457, + 64, + 182, + 310, + 429, + 18, + 128, + 255 + ], + "text" : "im3:TA)4hA$T\/#!PbK&K", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8LDQECjqudLKkDeg==", + "bodyBase64" : "\/wsNAQKOq50sqQN6", + "height" : 3, + "name" : "swift-profile-11-nonce-255", + "paletteProfile" : "dynamicGlobal32", + "pixels" : [ + 0, + 118, + 237, + 347, + 457, + 64, + 182, + 310, + 429, + 18, + 128, + 255 + ], + "text" : "im3:m|yX(Aln1lif2UpV", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAMDQECHE7VkausB8gD", + "bodyBase64" : "AAwNAQIcTtWRq6wHyAM=", + "height" : 3, + "name" : "swift-profile-12-nonce-0", + "paletteProfile" : "dynamicGlobal64", + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 9, + 64, + 127 + ], + "text" : "im3:TA.4hAkn#7Zz6j9AeB", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8MDQECHE7VkausB8gD", + "bodyBase64" : "\/wwNAQIcTtWRq6wHyAM=", + "height" : 3, + "name" : "swift-profile-12-nonce-255", + "paletteProfile" : "dynamicGlobal64", + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 9, + 64, + 127 + ], + "text" : "im3:m|6X(A.>hdxMa,fBdFA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwANDQECODgqHdJKpgsinw==", + "bodyBase64" : "AA0NAQI4OCod0kqmCyKf", + "height" : 3, + "name" : "swift-profile-13-nonce-0", + "paletteProfile" : "dynamicGlobal128", + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 2, + 10, + 17 + ], + "text" : "im3:TA<4hA,>}YXKoeM]`XtD", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8NDQECODgqHdJKpgsinw==", + "bodyBase64" : "\/w0NAQI4OCod0kqmCyKf", + "height" : 3, + "name" : "swift-profile-13-nonce-255", + "paletteProfile" : "dynamicGlobal128", + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 2, + 10, + 17 + ], + "text" : "im3:m|&X(Ax({xuU@8W:@v\"G", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAODQECcOBQ0UGyIqMThPQE", + "bodyBase64" : "AA4NAQJw4FDRQbIioxOE9AQ=", + "height" : 3, + "name" : "swift-profile-14-nonce-0", + "paletteProfile" : "dynamicGlobal256", + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 2, + 10, + 17 + ], + "text" : "im3:TA@4hAw(>J3\/gzz+\/NlZ?A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8ODQECcOBQ0UGyIqMThPQE", + "bodyBase64" : "\/w4NAQJw4FDRQbIioxOE9AQ=", + "height" : 3, + "name" : "swift-profile-14-nonce-255", + "paletteProfile" : "dynamicGlobal256", + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 2, + 10, + 17 + ], + "text" : "im3:m|:X(ADt&TR5#MKz4b:y(B", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "EwAPDQEC4ICDCh1IrJChIwiSJw==", + "bodyBase64" : "AA8NAQLggIMKHUiskKEjCJIn", + "height" : 3, + "name" : "swift-profile-15-nonce-0", + "paletteProfile" : "dynamicGlobal512", + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 36, + 43, + 50, + 58, + 65, + 72, + 79 + ], + "text" : "im3:TA_4hACtmn#D;WNP3X.t!+T", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "E\/8PDQEC4ICDCh1IrJChIwiSJw==", + "bodyBase64" : "\/w8NAQLggIMKHUiskKEjCJIn", + "height" : 3, + "name" : "swift-profile-15-nonce-255", + "paletteProfile" : "dynamicGlobal512", + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 36, + 43, + 50, + 58, + 65, + 72, + 79 + ], + "text" : "im3:m|]X(AE\"mn#D;WNP3X.t!+T", + "transparentColor" : null, + "width" : 4 + } + ], + "generator" : "scripts\/mcoimg\/verify-v3.swift", + "schema" : 1 +} \ No newline at end of file diff --git a/scripts/mcoimg/fixtures/v3-upstream-decoder.json b/scripts/mcoimg/fixtures/v3-upstream-decoder.json new file mode 100644 index 0000000000..b8a3f6f0cf --- /dev/null +++ b/scripts/mcoimg/fixtures/v3-upstream-decoder.json @@ -0,0 +1,847 @@ +{ + "schema": 1, + "generator": "docs/mcoimg-js/tests/v3-decoder-fixtures.js", + "fixtures": [ + { + "name": "rawGlobal", + "bodyBase64": "egGNAEK+AQ==", + "appPayloadBase64": "E3oBjQBCvgE=", + "text": "im3:g/5WjAL`NA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 1, + 2, + 3, + 3, + 2, + 1, + 0 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawGlobal" + }, + { + "name": "rawLocal", + "bodyBase64": "egGNECLWAg==", + "appPayloadBase64": "E3oBjRAi1gI=", + "text": "im3:g/5W6LuitA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "compactRle", + "bodyBase64": "egGNICCmIQ==", + "appPayloadBase64": "E3oBjSAgpiE=", + "text": "im3:g/5W[Wqi^F", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRle" + }, + { + "name": "compactSparse", + "bodyBase64": "egGNMABOIgA=", + "appPayloadBase64": "E3oBjTAATiIA", + "text": "im3:g/5WNi+>CGA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 3, + 0, + 0, + 3, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactSparse" + }, + { + "name": "biColorMask", + "bodyBase64": "egGNQMJa", + "appPayloadBase64": "E3oBjUDCWg==", + "text": "im3:g/5Wktw8F", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "biColorMask" + }, + { + "name": "rowRepeat", + "bodyBase64": "egGNUCDW", + "appPayloadBase64": "E3oBjVAg1g==", + "text": "im3:g/5W74qiN", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "rowRepeat" + }, + { + "name": "lzPixels", + "bodyBase64": "egGNYCAWHw==", + "appPayloadBase64": "E3oBjWAgFh8=", + "text": "im3:g/5W](qiqF", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "lzPixels" + }, + { + "name": "quadtree", + "bodyBase64": "egEEB2J9", + "appPayloadBase64": "E3oBBAdifQ==", + "text": "im3:g/N\"qC8]D", + "width": 2, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 3, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "quadtree" + }, + { + "name": "bitplanesRawAndRle", + "bodyBase64": "egGNgGByqm0=", + "appPayloadBase64": "E3oBjYBgcqpt", + "text": "im3:g/5Wl\"#zslb", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 1, + 0, + 1, + 2, + 3, + 2, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "bitplanes" + }, + { + "name": "adaptiveBitplanesRaw", + "bodyBase64": "egGNkCCmBQ==", + "appPayloadBase64": "E3oBjZAgpgU=", + "text": "im3:g/5W6Lri\"A", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "directBitplanes", + "bodyBase64": "egiNoEAVM3g=", + "appPayloadBase64": "E3oIjaBAFTN4", + "text": "im3:g/WX[Wyd~I8", + "width": 4, + "height": 2, + "paletteProfile": "grayscale8", + "pixels": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "transparentColor": null, + "container": "block", + "algorithm": "directBitplanes" + }, + { + "name": "compactRowDelta", + "bodyBase64": "egGNsCCmAA==", + "appPayloadBase64": "E3oBjbAgpgA=", + "text": "im3:g/5WNiriKA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRowDelta" + }, + { + "name": "directRowDelta", + "bodyBase64": "egiNwADRAA==", + "appPayloadBase64": "E3oIjcAA0QA=", + "text": "im3:g/WXkt6FNA", + "width": 4, + "height": 2, + "paletteProfile": "grayscale8", + "pixels": [ + 0, + 1, + 2, + 3, + 0, + 1, + 2, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "directRowDelta" + }, + { + "name": "rowDelta", + "bodyBase64": "egGN0CBGAw==", + "appPayloadBase64": "E3oBjdAgRgM=", + "text": "im3:g/5W74ri0A", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "rowDelta" + }, + { + "name": "varUintRle", + "bodyBase64": "egGN4CA2UMAA", + "appPayloadBase64": "E3oBjeAgNlDAAA==", + "text": "im3:g/5W](riJOFBA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "varUintRle" + }, + { + "name": "varUintSparse", + "bodyBase64": "egGN8AAWCBAQCAA=", + "appPayloadBase64": "E3oBjfAAFggQEAgA", + "text": "im3:g/5WO?+hmB2WgAA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 3, + 0, + 0, + 3, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "varUintSparse" + }, + { + "name": "adaptiveLegacyRle", + "bodyBase64": "egEdkCDOBg==", + "appPayloadBase64": "E3oBHZAgzgY=", + "text": "im3:g/5WeLs?RB", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 3, + 3, + 3, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveShortRle", + "bodyBase64": "egEdkCCeNg==", + "appPayloadBase64": "E3oBHZAgnjY=", + "text": "im3:g/5WeLs?2J", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 3, + 3, + 3, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveConstantZero", + "bodyBase64": "egEdkCA+", + "appPayloadBase64": "E3oBHZAgPg==", + "text": "im3:g/5WeLs?D", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveConstantOne", + "bodyBase64": "egEdkCB+", + "appPayloadBase64": "E3oBHZAgfg==", + "text": "im3:g/5WeLs?H", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveSparseOne", + "bodyBase64": "egEdkCC+CQE=", + "appPayloadBase64": "E3oBHZAgvgkB", + "text": "im3:g/5WeLs?%uA", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 0, + 0, + 0, + 3, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveSparseZero", + "bodyBase64": "egEdkCD+CQE=", + "appPayloadBase64": "E3oBHZAg/gkB", + "text": "im3:g/5WeLs?*uA", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 3, + 0, + 3, + 3, + 3, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "boundsBlock", + "bodyBase64": "egEMQgQEBATgAQ==", + "appPayloadBase64": "E3oBDEIEBAQE4AE=", + "text": "im3:g/N\"UXbLi\"+>BA", + "width": 4, + "height": 4, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 3, + 3, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "boundsBlock", + "algorithm": "compactRle" + }, + { + "name": "compactBoundsBlock", + "bodyBase64": "egEMYFTlAQ==", + "appPayloadBase64": "E3oBDGBU5QE=", + "text": "im3:g/N\"+h\"OPA", + "width": 4, + "height": 4, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 1, + 2, + 0, + 0, + 3, + 1, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "compactBoundsBlock", + "algorithm": "rawGlobal" + }, + { + "name": "regions", + "bodyBase64": "egEMgAQEBAQEtQE=", + "appPayloadBase64": "E3oBDIAEBAQEBLUB", + "text": "im3:g/N\"CtbLi\"lB/EA", + "width": 4, + "height": 4, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 1, + 3, + 0, + 0, + 3, + 1, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "regions", + "algorithm": "rawGlobal" + }, + { + "name": "compactRegionsSharedDelta", + "bodyBase64": "egGNEMqDGrUAQAI=", + "appPayloadBase64": "E3oBjRDKgxq1AEAC", + "text": "im3:g/5W6LdV9x\"AdZA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 1, + 3, + 3, + 1, + 3, + 1, + 1, + 3 + ], + "transparentColor": null, + "container": "compactRegionsStream", + "algorithm": "rawGlobal" + }, + { + "name": "solidBackground", + "bodyBase64": "egEAwg==", + "appPayloadBase64": "E3oBAMI=", + "text": "im3:g/LAU)", + "width": 1, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 2 + ], + "transparentColor": null, + "container": "solidBackground", + "algorithm": "rawGlobal" + }, + { + "name": "solidRects", + "bodyBase64": "egEM4GBV", + "appPayloadBase64": "E3oBDOBgVQ==", + "text": "im3:g/N\",>M8C", + "width": 4, + "height": 4, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 3, + 3, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "solidRects", + "algorithm": "rawGlobal" + }, + { + "name": "implicitWhiteSolid", + "bodyBase64": "ekEEwA==", + "appPayloadBase64": "E3pBBMA=", + "text": "im3:g/)FCtB", + "width": 2, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "solidBackground", + "algorithm": "rawGlobal" + }, + { + "name": "transparentSolid", + "bodyBase64": "eoEEwgM=", + "appPayloadBase64": "E3qBBMID", + "text": "im3:g/iLnuHA", + "width": 2, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 2, + 2, + 2, + 2 + ], + "transparentColor": 3, + "container": "solidBackground", + "algorithm": "rawGlobal" + }, + { + "name": "scanV", + "bodyBase64": "ehGJIGByEGQQ", + "appPayloadBase64": "E3oRiSBgchBkEA==", + "text": "im3:g/DY@WhN[CFXA", + "width": 3, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 2, + 0, + 1, + 3, + 1 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRle" + }, + { + "name": "scanS", + "bodyBase64": "eiGJIGByEGQQ", + "appPayloadBase64": "E3ohiSBgchBkEA==", + "text": "im3:g/oZ@WhN[CFXA", + "width": 3, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 1, + 2, + 1, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRle" + }, + { + "name": "scanSV", + "bodyBase64": "ejGJIGByEGQQ", + "appPayloadBase64": "E3oxiSBgchBkEA==", + "text": "im3:g/=a@WhN[CFXA", + "width": 3, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 1, + 2, + 1 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRle" + }, + { + "name": "paletteBitmap", + "bodyBase64": "egENEJI0", + "appPayloadBase64": "E3oBDRCSNA==", + "text": "im3:g/5WaL%ZD", + "width": 4, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 3, + 0 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "paletteSortedDelta", + "bodyBase64": "egINEDJBIgM=", + "appPayloadBase64": "E3oCDRAyQSID", + "text": "im3:g/%WaL&GDzB", + "width": 4, + "height": 1, + "paletteProfile": "master8", + "pixels": [ + 0, + 2, + 4, + 2 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "paletteRangeRuns", + "bodyBase64": "egINENJAFTk=", + "appPayloadBase64": "E3oCDRDSQBU5", + "text": "im3:g/%WaL4E)wc", + "width": 4, + "height": 1, + "paletteProfile": "master8", + "pixels": [ + 0, + 1, + 5, + 6 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "paletteBankBitmaps", + "bodyBase64": "eg8NEPIrEAAAAAAAAAAgAAAAAAAAAFA=", + "appPayloadBase64": "E3oPDRDyKxAAAAAAAAAAIAAAAAAAAABQ", + "text": "im3:g/>XaLT(XaL$stPmGlE", + "width": 4, + "height": 1, + "paletteProfile": "dynamicGlobal512", + "pixels": [ + 193, + 201, + 209, + 201 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "paletteOrderedMultiBank", + "bodyBase64": "eg8NEPI3LBAUDAly", + "appPayloadBase64": "E3oPDRDyNywQFAwJcg==", + "text": "im3:g/>XaL$s+HUc,LJo", + "width": 4, + "height": 1, + "paletteProfile": "dynamicGlobal512", + "pixels": [ + 1, + 130, + 3, + 132 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + } + ] +} diff --git a/scripts/mcoimg/fixtures/v4-swift-raster.json b/scripts/mcoimg/fixtures/v4-swift-raster.json new file mode 100644 index 0000000000..3e6c2b39fd --- /dev/null +++ b/scripts/mcoimg/fixtures/v4-swift-raster.json @@ -0,0 +1,13197 @@ +{ + "fixtures" : [ + { + "appPayloadBase64" : "FHpFI3hPUDQCCPkGAA==", + "bodyBase64" : "ekUjeE9QNAII+QYA", + "height" : 2, + "name" : "swift-rawGlobal", + "nonce" : 122, + "pixels" : [ + 0, + 1, + 2, + 3, + 3, + 2, + 1, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNAEK+AQ==", + "text" : "im4:lPJD[3YYjAL`NAA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEjRCgVgD", + "bodyBase64" : "ekUjeE8SNEKBWAM=", + "height" : 2, + "name" : "swift-rawLocal", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "eiGNUCDW", + "text" : "im4:lPJD[3]W74qiNA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEjRCgRgD", + "bodyBase64" : "ekUjeE8SNEKBGAM=", + "height" : 2, + "name" : "swift-compactRle", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "eiGNUCDG", + "text" : "im4:lPJD[3]W74qiMA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPUDQCCA8DAA==", + "bodyBase64" : "ekUjeE9QNAIIDwMA", + "height" : 2, + "name" : "swift-compactSparse", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 3, + 0, + 0, + 3, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNAMLDAA==", + "text" : "im4:lPJD[3YYjA0KGAA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEjRCgVgD", + "bodyBase64" : "ekUjeE8SNEKBWAM=", + "height" : 2, + "name" : "swift-biColorMask", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "eiGNUCDW", + "text" : "im4:lPJD[3]W74qiNA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEDRCgVgD", + "bodyBase64" : "ekUjeE8QNEKBWAM=", + "height" : 2, + "name" : "swift-rowRepeat", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNUCDW", + "text" : "im4:lPJD[3>W74qiNA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEDRCgVgD", + "bodyBase64" : "ekUjeE8QNEKBWAM=", + "height" : 2, + "name" : "swift-lzPixels", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNUCDW", + "text" : "im4:lPJD[3>W74qiNA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHoFgfcCE4DwAA==", + "bodyBase64" : "egWB9wITgPAA", + "height" : 2, + "name" : "swift-quadtree", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 3, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egEEIDw=", + "text" : "im4:lP>>HCmANVA", + "transparentColor" : null, + "width" : 2 + }, + { + "appPayloadBase64" : "FHpFI3hPUDQCCJE7AA==", + "bodyBase64" : "ekUjeE9QNAIIkTsA", + "height" : 2, + "name" : "swift-bitplanesRawAndRle", + "nonce" : 122, + "pixels" : [ + 0, + 1, + 0, + 1, + 2, + 3, + 2, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNAELkDg==", + "text" : "im4:lPJD[3YYjA~LcBA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEjRCgVgD", + "bodyBase64" : "ekUjeE8SNEKBWAM=", + "height" : 2, + "name" : "swift-adaptiveBitplanesRaw", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "eiGNUCDW", + "text" : "im4:lPJD[3]W74qiNA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHphI3hPkDQCCKKxPgA=", + "bodyBase64" : "emEjeE+QNAIIorE+AA==", + "height" : 2, + "name" : "swift-directBitplanes", + "nonce" : 122, + "pixels" : [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "profile" : 8, + "sourceV3BodyBase64" : "egiNAIJorA8=", + "text" : "im4:OEKD[39ZjA`X9]DA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEDRCgVgD", + "bodyBase64" : "ekUjeE8QNEKBWAM=", + "height" : 2, + "name" : "swift-compactRowDelta", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNUCDW", + "text" : "im4:lPJD[3>W74qiNA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHphI3hPkDQCCKIhGgA=", + "bodyBase64" : "emEjeE+QNAIIoiEaAA==", + "height" : 2, + "name" : "swift-directRowDelta", + "nonce" : 122, + "pixels" : [ + 0, + 1, + 2, + 3, + 0, + 1, + 2, + 3 + ], + "profile" : 8, + "sourceV3BodyBase64" : "egiNAIJoiAY=", + "text" : "im4:OEKD[39ZjA`XA5BA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEDRCgVgD", + "bodyBase64" : "ekUjeE8QNEKBWAM=", + "height" : 2, + "name" : "swift-rowDelta", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNUCDW", + "text" : "im4:lPJD[3>W74qiNA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPEjRCgRgD", + "bodyBase64" : "ekUjeE8SNEKBGAM=", + "height" : 2, + "name" : "swift-varUintRle", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "eiGNUCDG", + "text" : "im4:lPJD[3]W74qiMA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPUDQCCA8DAA==", + "bodyBase64" : "ekUjeE9QNAIIDwMA", + "height" : 2, + "name" : "swift-varUintSparse", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 3, + 0, + 0, + 3, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNAMLDAA==", + "text" : "im4:lPJD[3YYjA0KGAA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFB3iPKOiAMI4B", + "bodyBase64" : "ekUHeI8o6IAwjgE=", + "height" : 1, + "name" : "swift-adaptiveLegacyRle", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 0, + 3, + 3, + 3, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "ekEdEMYx", + "text" : "im4:lP6Apy{WeL~JDA", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "FHpFB3iPKOgAMOkH", + "bodyBase64" : "ekUHeI8o6AAw6Qc=", + "height" : 1, + "name" : "swift-adaptiveShortRle", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 3, + 3, + 3, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "ekEdACb9", + "text" : "im4:lP6Apy{WHAA]HA", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "FHpFB3iPyB0ADAA=", + "bodyBase64" : "ekUHeI\/IHQAMAA==", + "height" : 1, + "name" : "swift-adaptiveConstantZero", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "ekEdAAw=", + "text" : "im4:lP6Apy,^C\"BA", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "FHpFB3iPwB0wDAA=", + "bodyBase64" : "ekUHeI\/AHTAMAA==", + "height" : 1, + "name" : "swift-adaptiveConstantOne", + "nonce" : 122, + "pixels" : [ + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egEdMAw=", + "text" : "im4:lP6Apy#^UEDA", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "FHpFB3iPoOgAEAYYAA==", + "bodyBase64" : "ekUHeI+g6AAQBhgA", + "height" : 1, + "name" : "swift-adaptiveSparseOne", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 0, + 0, + 0, + 3, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egEdAMIAAw==", + "text" : "im4:lP6ApyYYHAMCYAA", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "FHpFB3iPoOgAkPlnAA==", + "bodyBase64" : "ekUHeI+g6ACQ+WcA", + "height" : 1, + "name" : "swift-adaptiveSparseZero", + "nonce" : 122, + "pixels" : [ + 3, + 0, + 3, + 3, + 3, + 3, + 0, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egEdADL\/DA==", + "text" : "im4:lP6ApyYYHA*|MBA", + "transparentColor" : null, + "width" : 8 + }, + { + "appPayloadBase64" : "FHoFg\/eEAgawqn8A", + "bodyBase64" : "egWD94QCBrCqfwA=", + "height" : 4, + "name" : "swift-boundsBlock", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 3, + 3, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "ekEMYFX\/", + "text" : "im4:lPD?sD:h{ey~BA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHoFg\/eEAgawqjwA", + "bodyBase64" : "egWD94QCBrCqPAA=", + "height" : 4, + "name" : "swift-compactBoundsBlock", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 1, + 2, + 0, + 0, + 3, + 1, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "ekEMYFV5", + "text" : "im4:lPD?sD:h{ee`AA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHoFg\/eEAgawqj4A", + "bodyBase64" : "egWD94QCBrCqPgA=", + "height" : 4, + "name" : "swift-regions", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 1, + 3, + 0, + 0, + 3, + 1, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "ekEMYFV9", + "text" : "im4:lPD?sD:h{eN}AA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpFI3hPUDQCSN81AA==", + "bodyBase64" : "ekUjeE9QNAJI3zUA", + "height" : 2, + "name" : "swift-compactRegionsSharedDelta", + "nonce" : 122, + "pixels" : [ + 1, + 3, + 3, + 1, + 3, + 1, + 1, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGNANJ3DQ==", + "text" : "im4:lPJD[3YYjAB(QBA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHoFgPcCAggD", + "bodyBase64" : "egWA9wICCAM=", + "height" : 1, + "name" : "swift-solidBackground", + "nonce" : 122, + "pixels" : [ + 2 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egEAwg==", + "text" : "im4:lP+>HCFtwA", + "transparentColor" : null, + "width" : 1 + }, + { + "appPayloadBase64" : "FHoFg\/eEAgawqn8A", + "bodyBase64" : "egWD94QCBrCqfwA=", + "height" : 4, + "name" : "swift-solidRects", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 3, + 3, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "ekEMYFX\/", + "text" : "im4:lPD?sD:h{ey~BA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHoFgfciEgAD", + "bodyBase64" : "egWB9yISAAM=", + "height" : 2, + "name" : "swift-implicitWhiteSolid", + "nonce" : 122, + "pixels" : [ + 0, + 0, + 0, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "ekEEwA==", + "text" : "im4:lP>>1YkAYA", + "transparentColor" : null, + "width" : 2 + }, + { + "appPayloadBase64" : "FHoFQe+FJhAeAA==", + "bodyBase64" : "egVB74UmEB4A", + "height" : 2, + "name" : "swift-transparentSolid", + "nonce" : 122, + "pixels" : [ + 2, + 2, + 2, + 2 + ], + "profile" : 1, + "sourceV3BodyBase64" : "eoEEwgM=", + "text" : "im4:lPV\/PE?\"6CA", + "transparentColor" : 3, + "width" : 2 + }, + { + "appPayloadBase64" : "FHpFInhPECQCCNIB", + "bodyBase64" : "ekUieE8QJAII0gE=", + "height" : 2, + "name" : "swift-scanV", + "nonce" : 122, + "pixels" : [ + 0, + 2, + 0, + 1, + 3, + 1 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGJAIJ0", + "text" : "im4:lPBD[3>WiA#5DA", + "transparentColor" : null, + "width" : 3 + }, + { + "appPayloadBase64" : "FHpFInhPECQCCBkD", + "bodyBase64" : "ekUieE8QJAIIGQM=", + "height" : 2, + "name" : "swift-scanS", + "nonce" : 122, + "pixels" : [ + 0, + 1, + 2, + 1, + 0, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGJAELG", + "text" : "im4:lPBD[3>WiA3RGA", + "transparentColor" : null, + "width" : 3 + }, + { + "appPayloadBase64" : "FHpFInhPECQCCJMB", + "bodyBase64" : "ekUieE8QJAIIkwE=", + "height" : 2, + "name" : "swift-scanSV", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 0, + 1, + 2, + 1 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egGJAMJk", + "text" : "im4:lPBD[3>WiAjNDA", + "transparentColor" : null, + "width" : 3 + }, + { + "appPayloadBase64" : "FHpFA3hPEDQACA8A", + "bodyBase64" : "ekUDeE8QNAAIDwA=", + "height" : 1, + "name" : "swift-paletteBitmap", + "nonce" : 122, + "pixels" : [ + 0, + 3, + 3, + 0 + ], + "profile" : 1, + "sourceV3BodyBase64" : "egENAMID", + "text" : "im4:lPaA{bo4BAaFAA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpJA3hPEDQACEQB", + "bodyBase64" : "ekkDeE8QNAAIRAE=", + "height" : 1, + "name" : "swift-paletteSortedDelta", + "nonce" : 122, + "pixels" : [ + 0, + 2, + 4, + 2 + ], + "profile" : 2, + "sourceV3BodyBase64" : "egINAAJR", + "text" : "im4:8aaA{bo4BA_XBA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHpJA3hPEDQACFID", + "bodyBase64" : "ekkDeE8QNAAIUgM=", + "height" : 1, + "name" : "swift-paletteRangeRuns", + "nonce" : 122, + "pixels" : [ + 0, + 1, + 5, + 6 + ], + "profile" : 2, + "sourceV3BodyBase64" : "egINAILU", + "text" : "im4:8aaA{bo4BA=cDA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHp9A3hP0DQASABBAQQB", + "bodyBase64" : "en0DeE\/QNABIAEEBBAE=", + "height" : 1, + "name" : "swift-paletteBankBitmaps", + "nonce" : 122, + "pixels" : [ + 1, + 130, + 1, + 130 + ], + "profile" : 15, + "sourceV3BodyBase64" : "eg8NABJAUABB", + "text" : "im4:_]bA{by6BAL\"*BnLA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHp9A3hP0DQASLBk0ZIB", + "bodyBase64" : "en0DeE\/QNABIsGTRkgE=", + "height" : 1, + "name" : "swift-paletteOrderedSingleBank", + "nonce" : 122, + "pixels" : [ + 193, + 201, + 209, + 201 + ], + "profile" : 15, + "sourceV3BodyBase64" : "eg8NABIsWbRk", + "text" : "im4:_]bA{by6BA\"9_wljA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FHp9A3hP0DQASABBAwgB", + "bodyBase64" : "en0DeE\/QNABIAEEDCAE=", + "height" : 1, + "name" : "swift-paletteOrderedMultiBank", + "nonce" : 122, + "pixels" : [ + 1, + 130, + 3, + 132 + ], + "profile" : 15, + "sourceV3BodyBase64" : "eg8NABJA0ABC", + "text" : "im4:_]bA{by6BAL\"0E3LA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FAAJj3chaAA8ZTOZhFlVVQkAYEIVeAIAmKqqAgA=", + "bodyBase64" : "AAmPdyFoADxlM5mEWVVVCQBgQhV4AgCYqqoCAA==", + "height" : 16, + "name" : "swift-painted16", + "nonce" : 0, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 3, + 3, + 3, + 3, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 3, + 3, + 3, + 3, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 3, + 3, + 3, + 3, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 3, + 3, + 3, + 3, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 2, + "sourceV3BodyBase64" : "AEI8ZTOZhFlVVQkAYEIVeAIAmKqqAg==", + "text" : "im4:dZI@wXaCz3a.(zrfB8:A*h\/7z3AA\/dB8AA", + "transparentColor" : null, + "width" : 16 + }, + { + "appPayloadBase64" : "FP8Vj3chYK48IEAkzkRl3kim7kzn\/t0bTOWdbO0fjfWRrXoDzkbG\/lKJL15MXNf6T+f+jPfyzcf2DnTizUgnH1xsbHChvdHZT+lfrcHVDtlbbG7BzUqIP2ZPrUIGH8u4T+uwzcu4T+uwzWigzUzpX3Ai7lRrfMWXT+0R7tWbjP0VL2KPzU5KfHoFL2bA3f92T+9yDt9+zc96jFxuzVCrnETob3glP\/lVT\/HTLulRDuHf7VZNzVIMvU7LrEqKnPM0T\/M0T\/M0T\/M0TwA=", + "bodyBase64" : "\/xWPdyFgrjwgQCTORGXeSKbuTOf+3RtM5Z1s7R+N9ZGtegPORsb+UokvXkxc1\/pP5\/6M9\/LNx\/YOdOLNSCcfXGxscKG90dlP6V+twdUO2VtsbsHNSog\/Zk+tQgYfy7hP67DNy7hP67DNaKDNTOlfcCLuVGt8xZdP7RHu1ZuM\/RUvYo\/NTkp8egUvZsDd\/3ZP73IO337Nz3qMXG7NUKucROhveCU\/+VVP8dMu6VEO4d\/tVk3NUgy9TsusSoqc8zRP8zRP8zRP8zRPAA==", + "height" : 16, + "name" : "swift-dense16", + "nonce" : 255, + "pixels" : [ + 0, + 17, + 34, + 51, + 4, + 21, + 38, + 55, + 8, + 25, + 42, + 59, + 12, + 29, + 46, + 63, + 29, + 47, + 1, + 19, + 37, + 55, + 9, + 27, + 45, + 63, + 17, + 35, + 53, + 7, + 25, + 43, + 58, + 13, + 32, + 51, + 6, + 25, + 44, + 63, + 18, + 37, + 56, + 11, + 30, + 49, + 4, + 23, + 23, + 43, + 63, + 19, + 39, + 59, + 15, + 35, + 55, + 11, + 31, + 51, + 7, + 27, + 47, + 3, + 52, + 9, + 30, + 51, + 8, + 29, + 50, + 7, + 28, + 49, + 6, + 27, + 48, + 5, + 26, + 47, + 17, + 39, + 61, + 19, + 41, + 63, + 21, + 43, + 1, + 23, + 45, + 3, + 25, + 47, + 5, + 27, + 46, + 5, + 28, + 51, + 10, + 33, + 56, + 15, + 38, + 61, + 20, + 43, + 2, + 25, + 48, + 7, + 11, + 35, + 59, + 19, + 43, + 3, + 27, + 51, + 11, + 35, + 59, + 19, + 43, + 3, + 27, + 51, + 40, + 1, + 26, + 51, + 12, + 37, + 62, + 23, + 48, + 9, + 34, + 59, + 20, + 45, + 6, + 31, + 5, + 31, + 57, + 19, + 45, + 7, + 33, + 59, + 21, + 47, + 9, + 35, + 61, + 23, + 49, + 11, + 34, + 61, + 24, + 51, + 14, + 41, + 4, + 31, + 58, + 21, + 48, + 11, + 38, + 1, + 28, + 55, + 63, + 27, + 55, + 19, + 47, + 11, + 39, + 3, + 31, + 59, + 23, + 51, + 15, + 43, + 7, + 35, + 28, + 57, + 22, + 51, + 16, + 45, + 10, + 39, + 4, + 33, + 62, + 27, + 56, + 21, + 50, + 15, + 57, + 23, + 53, + 19, + 49, + 15, + 45, + 11, + 41, + 7, + 37, + 3, + 33, + 63, + 29, + 59, + 22, + 53, + 20, + 51, + 18, + 49, + 16, + 47, + 14, + 45, + 12, + 43, + 10, + 41, + 8, + 39, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19, + 51, + 19 + ], + "profile" : 5, + "sourceV3BodyBase64" : "\/wU8IEAkzkRl3kim7kzn\/t0bTOWdbO0fjfWRrXoDzkbG\/lKJL15MXNf6T+f+jPfyzcf2DnTizUgnH1xsbHChvdHZT+lfrcHVDtlbbG7BzUqIP2ZPrUIGH8u4T+uwzcu4T+uwzWigzUzpX3Ai7lRrfMWXT+0R7tWbjP0VL2KPzU5KfHoFL2bA3f92T+9yDt9+zc96jFxuzVCrnETob3glP\/lVT\/HTLulRDuHf7VZNzVIMvU7LrEqKnPM0T\/M0T\/M0T\/M0Tw==", + "text" : "im4:@9I@wX@@8KS\"z?J5)q%+^^wU^s2T\/d*b[#85f{Pmb>>2cj.sKN3*=a%%z~7.K\/vr4Tb|lZ#+I\/@Kk_8[z9[()\/+Y`Z{n|>%tVDF!~^%j2*PQv&U{1Xaa@lV$3=b`6r:Vl4S?AA", + "transparentColor" : null, + "width" : 16 + }, + { + "appPayloadBase64" : "FABBQ3hPIGgIEC0F", + "bodyBase64" : "AEFDeE8gaAgQLQU=", + "height" : 3, + "name" : "swift-profile-0-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 0, + 0, + 1, + 0, + 1 + ], + "profile" : 0, + "sourceV3BodyBase64" : "AAANAaKl", + "text" : "im4::C^F[3%trBj#UA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9BQ3hPIGgIEC0F", + "bodyBase64" : "\/0FDeE8gaAgQLQU=", + "height" : 3, + "name" : "swift-profile-0-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 0, + 0, + 1, + 0, + 1 + ], + "profile" : 0, + "sourceV3BodyBase64" : "\/wANAaKl", + "text" : "im4:4F^F[3%trBj#UA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABFQ3hPIGkIELZYYwA=", + "bodyBase64" : "AEVDeE8gaQgQtlhjAA==", + "height" : 3, + "name" : "swift-profile-1-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 3, + 2, + 1, + 1, + 0, + 3, + 2, + 2, + 1, + 0, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "AAENAcIWaww=", + "text" : "im4:GO^F[3fzrBE<7lMA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9FQ3hPIGkIELZYYwA=", + "bodyBase64" : "\/0VDeE8gaQgQtlhjAA==", + "height" : 3, + "name" : "swift-profile-1-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 3, + 2, + 1, + 1, + 0, + 3, + 2, + 2, + 1, + 0, + 3 + ], + "profile" : 1, + "sourceV3BodyBase64" : "\/wENAcIWaww=", + "text" : "im4:?Q^F[3fzrBE<7lMA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABJQ3hPoGkIENwtJwUH", + "bodyBase64" : "AElDeE+gaQgQ3C0nBQc=", + "height" : 3, + "name" : "swift-profile-2-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 7, + 6, + 5, + 5, + 4, + 3, + 2, + 2, + 1, + 0, + 7 + ], + "profile" : 2, + "sourceV3BodyBase64" : "AAINAYK75aTg", + "text" : "im4:dZ^F[3O2rBrn,@\/BHA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9JQ3hPoGkIENwtJwUH", + "bodyBase64" : "\/0lDeE+gaQgQ3C0nBQc=", + "height" : 3, + "name" : "swift-profile-2-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 7, + 6, + 5, + 5, + 4, + 3, + 2, + 2, + 1, + 0, + 7 + ], + "profile" : 2, + "sourceV3BodyBase64" : "\/wINAYK75aTg", + "text" : "im4:Lc^F[3O2rBrn,@\/BHA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABNQ3hPoGoIEDivphUNfAA=", + "bodyBase64" : "AE1DeE+gaggQOK+mFQ18AA==", + "height" : 3, + "name" : "swift-profile-3-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 7, + 14, + 5, + 13, + 4, + 11, + 2, + 10, + 1, + 8, + 15 + ], + "profile" : 3, + "sourceV3BodyBase64" : "AAMNAQLn1bSigQ8=", + "text" : "im4:0k^F[3,7rB>>T;3H^>DA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9NQ3hPoGoIEDivphUNfAA=", + "bodyBase64" : "\/01DeE+gaggQOK+mFQ18AA==", + "height" : 3, + "name" : "swift-profile-3-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 7, + 14, + 5, + 13, + 4, + 11, + 2, + 10, + 1, + 8, + 15 + ], + "profile" : 3, + "sourceV3BodyBase64" : "\/wMNAQLn1bSigQ8=", + "text" : "im4:in^F[3,7rB>>T;3H^>DA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABRQ3hPIGsIEHBc7WRJHdAD", + "bodyBase64" : "AFFDeE8gawgQcFztZEkd0AM=", + "height" : 3, + "name" : "swift-profile-4-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 4, + 11, + 18, + 26, + 1, + 8, + 15 + ], + "profile" : 4, + "sourceV3BodyBase64" : "AAQNAQKOq50sqQN6", + "text" : "im4:;v^F[32!rB3(d8sjj]\/`A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9RQ3hPIGsIEHBc7WRJHdAD", + "bodyBase64" : "\/1FDeE8gawgQcFztZEkd0AM=", + "height" : 3, + "name" : "swift-profile-4-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 4, + 11, + 18, + 26, + 1, + 8, + 15 + ], + "profile" : 4, + "sourceV3BodyBase64" : "\/wQNAQKOq50sqQN6", + "text" : "im4:5y^F[32!rB3(d8sjj]\/`A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABVQ3hPIGwIEOBwqo5cZT1AHgA=", + "bodyBase64" : "AFVDeE8gbAgQ4HCqjlxlPUAeAA==", + "height" : 3, + "name" : "swift-profile-5-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 36, + 43, + 50, + 58, + 1, + 8, + 15 + ], + "profile" : 5, + "sourceV3BodyBase64" : "AAUNAQIcTtWRq6wHyAM=", + "text" : "im4:H7^F[3U)rBJtqbPyHPkFZVAA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9VQ3hPIGwIEOBwqo5cZT1AHgA=", + "bodyBase64" : "\/1VDeE8gbAgQ4HCqjlxlPUAeAA==", + "height" : 3, + "name" : "swift-profile-5-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 36, + 43, + 50, + 58, + 1, + 8, + 15 + ], + "profile" : 5, + "sourceV3BodyBase64" : "\/wUNAQIcTtWRq6wHyAM=", + "text" : "im4:@9^F[3U)rBJtqbPyHPkFZVAA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABZQ3hPoGoIEDivphUNfAA=", + "bodyBase64" : "AFlDeE+gaggQOK+mFQ18AA==", + "height" : 3, + "name" : "swift-profile-6-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 7, + 14, + 5, + 13, + 4, + 11, + 2, + 10, + 1, + 8, + 15 + ], + "profile" : 6, + "sourceV3BodyBase64" : "AAYNAQLn1bSigQ8=", + "text" : "im4:e+^F[3,7rB>>T;3H^>DA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9ZQ3hPoGoIEDivphUNfAA=", + "bodyBase64" : "\/1lDeE+gaggQOK+mFQ18AA==", + "height" : 3, + "name" : "swift-profile-6-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 7, + 14, + 5, + 13, + 4, + 11, + 2, + 10, + 1, + 8, + 15 + ], + "profile" : 6, + "sourceV3BodyBase64" : "\/wYNAQLn1bSigQ8=", + "text" : "im4:M\/^F[3,7rB>>T;3H^>DA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABdQ3hPIGsIEHBc7WRJHdAD", + "bodyBase64" : "AF1DeE8gawgQcFztZEkd0AM=", + "height" : 3, + "name" : "swift-profile-7-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 4, + 11, + 18, + 26, + 1, + 8, + 15 + ], + "profile" : 7, + "sourceV3BodyBase64" : "AAcNAQKOq50sqQN6", + "text" : "im4:1[^F[32!rB3(d8sjj]\/`A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9dQ3hPIGsIEHBc7WRJHdAD", + "bodyBase64" : "\/11DeE8gawgQcFztZEkd0AM=", + "height" : 3, + "name" : "swift-profile-7-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 7, + 14, + 21, + 29, + 4, + 11, + 18, + 26, + 1, + 8, + 15 + ], + "profile" : 7, + "sourceV3BodyBase64" : "\/wcNAQKOq50sqQN6", + "text" : "im4:j_^F[32!rB3(d8sjj]\/`A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABhQ3hPoGkIENwtJwUH", + "bodyBase64" : "AGFDeE+gaQgQ3C0nBQc=", + "height" : 3, + "name" : "swift-profile-8-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 7, + 6, + 5, + 5, + 4, + 3, + 2, + 2, + 1, + 0, + 7 + ], + "profile" : 8, + "sourceV3BodyBase64" : "AAgNAYK75aTg", + "text" : "im4::C_F[3O2rBrn,@\/BHA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9hQ3hPoGkIENwtJwUH", + "bodyBase64" : "\/2FDeE+gaQgQ3C0nBQc=", + "height" : 3, + "name" : "swift-profile-8-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 7, + 6, + 5, + 5, + 4, + 3, + 2, + 2, + 1, + 0, + 7 + ], + "profile" : 8, + "sourceV3BodyBase64" : "\/wgNAYK75aTg", + "text" : "im4:4F_F[3O2rBrn,@\/BHA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABlQ3hPoGkIENwtJwUH", + "bodyBase64" : "AGVDeE+gaQgQ3C0nBQc=", + "height" : 3, + "name" : "swift-profile-9-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 484, + 401, + 283, + 283, + 210, + 91, + 63, + 63, + 83, + 0, + 484 + ], + "profile" : 9, + "sourceV3BodyBase64" : "AAkNAYK75aTg", + "text" : "im4:GO_F[3O2rBrn,@\/BHA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9lQ3hPoGkIENwtJwUH", + "bodyBase64" : "\/2VDeE+gaQgQ3C0nBQc=", + "height" : 3, + "name" : "swift-profile-9-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 484, + 401, + 283, + 283, + 210, + 91, + 63, + 63, + 83, + 0, + 484 + ], + "profile" : 9, + "sourceV3BodyBase64" : "\/wkNAYK75aTg", + "text" : "im4:?Q_F[3O2rBrn,@\/BHA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABpQ3hPoGoIEDivphUNfAA=", + "bodyBase64" : "AGlDeE+gaggQOK+mFQ18AA==", + "height" : 3, + "name" : "swift-profile-10-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 210, + 492, + 155, + 447, + 118, + 338, + 63, + 310, + 84, + 246, + 511 + ], + "profile" : 10, + "sourceV3BodyBase64" : "AAoNAQLn1bSigQ8=", + "text" : "im4:dZ_F[3,7rB>>T;3H^>DA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9pQ3hPoGoIEDivphUNfAA=", + "bodyBase64" : "\/2lDeE+gaggQOK+mFQ18AA==", + "height" : 3, + "name" : "swift-profile-10-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 210, + 492, + 155, + 447, + 118, + 338, + 63, + 310, + 84, + 246, + 511 + ], + "profile" : 10, + "sourceV3BodyBase64" : "\/woNAQLn1bSigQ8=", + "text" : "im4:Lc_F[3,7rB>>T;3H^>DA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABtQ3hPIGsIEHBc7WRJHdAD", + "bodyBase64" : "AG1DeE8gawgQcFztZEkd0AM=", + "height" : 3, + "name" : "swift-profile-11-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 118, + 237, + 347, + 457, + 64, + 182, + 310, + 429, + 18, + 128, + 255 + ], + "profile" : 11, + "sourceV3BodyBase64" : "AAsNAQKOq50sqQN6", + "text" : "im4:0k_F[32!rB3(d8sjj]\/`A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9tQ3hPIGsIEHBc7WRJHdAD", + "bodyBase64" : "\/21DeE8gawgQcFztZEkd0AM=", + "height" : 3, + "name" : "swift-profile-11-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 118, + 237, + 347, + 457, + 64, + 182, + 310, + 429, + 18, + 128, + 255 + ], + "profile" : 11, + "sourceV3BodyBase64" : "\/wsNAQKOq50sqQN6", + "text" : "im4:in_F[32!rB3(d8sjj]\/`A", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FABxQ3hPIGwIEOBwqo5cZT1AHgA=", + "bodyBase64" : "AHFDeE8gbAgQ4HCqjlxlPUAeAA==", + "height" : 3, + "name" : "swift-profile-12-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 9, + 64, + 127 + ], + "profile" : 12, + "sourceV3BodyBase64" : "AAwNAQIcTtWRq6wHyAM=", + "text" : "im4:;v_F[3U)rBJtqbPyHPkFZVAA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP9xQ3hPIGwIEOBwqo5cZT1AHgA=", + "bodyBase64" : "\/3FDeE8gbAgQ4HCqjlxlPUAeAA==", + "height" : 3, + "name" : "swift-profile-12-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 9, + 64, + 127 + ], + "profile" : 12, + "sourceV3BodyBase64" : "\/wwNAQIcTtWRq6wHyAM=", + "text" : "im4:5y_F[3U)rBJtqbPyHPkFZVAA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FAB1Q3hPoGwIEMDBUemQVjJdEPkE", + "bodyBase64" : "AHVDeE+gbAgQwMFR6ZBWMl0Q+QQ=", + "height" : 3, + "name" : "swift-profile-13-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 2, + 10, + 17 + ], + "profile" : 13, + "sourceV3BodyBase64" : "AA0NAQI4OCod0kqmCyKf", + "text" : "im4:H7_F[3D,rBK\"@JCp(fr6)F\"NA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FP91Q3hPoGwIEMDBUemQVjJdEPkE", + "bodyBase64" : "\/3VDeE+gbAgQwMFR6ZBWMl0Q+QQ=", + "height" : 3, + "name" : "swift-profile-13-nonce-255", + "nonce" : 255, + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 2, + 10, + 17 + ], + "profile" : 13, + "sourceV3BodyBase64" : "\/w0NAQI4OCod0kqmCyKf", + "text" : "im4:@9_F[3D,rBK\"@JCp(fr6)F\"NA", + "transparentColor" : null, + "width" : 4 + }, + { + "appPayloadBase64" : "FAB5Q3hPoG0IEIADh4oOkhUZnSCkJwA=", + "bodyBase64" : "AHlDeE+gbQgQgAOHig6SFRmdIKQnAA==", + "height" : 3, + "name" : "swift-profile-14-nonce-0", + "nonce" : 0, + "pixels" : [ + 0, + 63, + 118, + 173, + 237, + 292, + 347, + 402, + 466, + 2, + 10, + 17 + ], + "profile" : 14, + "sourceV3BodyBase64" : "AA4NAQJw4FDRQbIioxOE9AQ=", + "text" : "im4:e+_F[381YEAYA", + "transparentColor" : null, + "width" : 1 + }, + { + "appPayloadBase64" : "FCpJ33snCHLfAwMA", + "bodyBase64" : "KknfeycIct8DAwA=", + "height" : 31, + "name" : "dimensions-32x31", + "nonce" : 42, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 2, + "sourceV3BodyBase64" : "KkJ9Dww=", + "text" : "im4:,ZN|*bnLb_VEAA", + "transparentColor" : null, + "width" : 32 + }, + { + "appPayloadBase64" : "FCqJ4Oe9IMiCHzAA", + "bodyBase64" : "Kong570gyIIfMAA=", + "height" : 32, + "name" : "dimensions-33x32", + "nonce" : 42, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 2, + "sourceV3BodyBase64" : "KkKCHzA=", + "text" : "im4:,ZX|wr&tA)!(AA", + "transparentColor" : null, + "width" : 33 + }, + { + "appPayloadBase64" : "FCoJv3cEgsgPDA==", + "bodyBase64" : "Kgm\/dwSCyA8M", + "height" : 64, + "name" : "dimensions-64x64", + "nonce" : 42, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 2, + "sourceV3BodyBase64" : "KkL8wA==", + "text" : "im4:,Zc_MD?v+CG", + "transparentColor" : null, + "width" : 64 + }, + { + "appPayloadBase64" : "FCrJgLwnEuQBAQMA", + "bodyBase64" : "KsmAvCcS5AEBAwA=", + "height" : 65, + "name" : "dimensions-65x65", + "nonce" : 42, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 2, + "sourceV3BodyBase64" : "KkIDAgY=", + "text" : "im4:,ZdL{b]WftUEAA", + "transparentColor" : null, + "width" : 65 + }, + { + "appPayloadBase64" : "FCrJ\/wG8Q4iC\/wMAAwA=", + "bodyBase64" : "Ksn\/AbxDiIL\/AwADAA==", + "height" : 1, + "name" : "dimensions-256x1", + "nonce" : 42, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 2, + "sourceV3BodyBase64" : "KkL\/BwAG", + "text" : "im4:,Z\"sSqtu|(4F*hAA", + "transparentColor" : null, + "width" : 256 + }, + { + "appPayloadBase64" : "FCrJAf69B4GCA\/wDAwA=", + "bodyBase64" : "KskB\/r0HgYID\/AMDAA==", + "height" : 256, + "name" : "dimensions-1x256", + "nonce" : 42, + "pixels" : [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "profile" : 2, + "sourceV3BodyBase64" : "KkIH+AcG", + "text" : "im4:,ZPt2r.F|(l__hAA", + "transparentColor" : null, + "width" : 1 + } + ] +} \ No newline at end of file diff --git a/scripts/mcoimg/generate_text_tables.py b/scripts/mcoimg/generate_text_tables.py new file mode 100644 index 0000000000..3620fc1192 --- /dev/null +++ b/scripts/mcoimg/generate_text_tables.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Generate Swift MCOtxt tables from meshcore-open tag 9.5.1-mod-1.9.0. + +The source commit is fe375741226588440e268002b4975349b2e95ffe. +Usage: generate_text_tables.py UPSTREAM +""" +import pathlib +import re +import sys + +upstream = pathlib.Path(sys.argv[1]) +output = pathlib.Path(__file__).resolve().parents[2] / "MC1Services/Sources/MC1Services/Utilities/MCOimg" + +for language in ["en", "ru", "fr", "de", "it", "uk", "be"]: + source = (upstream / f"lib/MCOtxt/models/generated/v1/model_{language}.dart").read_text() + prefix = "mcotxt" + language.capitalize() + + def array(suffix): + pattern = r"const List " + prefix + suffix + r" = \[(.*?)\];" + match = re.search(pattern, source, re.S) + body = re.sub(r"//[^\n]*", "", match.group(1)) + return [int(value, 0) for value in re.findall(r"0x[0-9A-Fa-f]+|\d+", body)] + + def lines(values): + return ",\n ".join( + ", ".join(str(value) for value in values[index:index + 16]) + for index in range(0, len(values), 16) + ) + + match = re.search(r"const Map " + prefix + r"UppercaseToLowercase = \{(.*?)\};", source, re.S) + pairs = re.findall(r"(0x[\dA-Fa-f]+): (0x[\dA-Fa-f]+)", match.group(1)) + uppercase = {int(lower, 0): int(upper, 0) for upper, lower in pairs} + entries = [f"{lower}: {upper}" for lower, upper in uppercase.items()] + upper_lines = ",\n ".join( + ", ".join(entries[index:index + 4]) for index in range(0, len(entries), 4) + ) + primary = array("PrimarySymbols") + extensions = array("ExtensionSymbols") + predictions = array("Top4Indexes") + assert len(predictions) == (len(primary) + len(extensions)) * 4 + swift = f"""// Frozen MCOtxt generation 0 wire tables. +extension MCOTextModels {{ + static let {language} = MCOTextModel( + primary: [ + {lines(primary)} + ], + extensionSymbols: [ + {lines(extensions)} + ], + start: [{lines(array('StartTop4Indexes'))}], + punctuationStart: [{lines(array('PunctStartTop4Indexes'))}], + top4: [ + {lines(predictions)} + ], + uppercase: [ + {upper_lines} + ] + ) +}} +""" + (output / f"MCOTextModels+{language.upper()}.swift").write_text(swift) diff --git a/scripts/mcoimg/measure_wire_cost_test.dart b/scripts/mcoimg/measure_wire_cost_test.dart new file mode 100644 index 0000000000..cf3cfbe5c4 --- /dev/null +++ b/scripts/mcoimg/measure_wire_cost_test.dart @@ -0,0 +1,50 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/mcoimg_types.dart'; +import 'package:meshcore_open/helpers/mcoimg_v3_codec.dart'; +import 'package:meshcore_open/helpers/mcoimg_v4_codec.dart'; +import 'package:meshcore_open/helpers/mcoimg_v4_model.dart'; + +void main() { + test('v3 raster versus v4 mixed complete transport cost', () { + final output = >[]; + for (final dense in [false, true]) { + const side = 16; + final pixels = List.generate(side * side, (i) { + final x = i % side, y = i ~/ side; + return dense ? ((x * 3 + y * 5) % 8) : (x == y || x + y == side - 1 ? 3 : 0); + }); + final image = MCOImage(width: side, height: side, paletteProfile: PaletteProfile.master8, + pixels: pixels, encodingVersion: MCOImageEncodingVersion.v3); + final raster = MCOImageV3Codec().encode(image); + final v3Body = MCOImageV3Codec.refreshPacketNonce(raster.body, nonce: 42); + final document = MCOImageV4Document(width: side, height: side, + paletteProfile: PaletteProfile.master8, palette: [0, 2], backgroundColor: 0, + figures: [MCOImageV4RasterLayer(x: 0, y: 0, width: side, height: side, pixels: pixels)]); + final mixed = const MCOImageV4Codec().encode(document, nonce: 42); + final v3Text = MCOImageV3Codec.textFromBody(v3Body); + final v4Text = const MCOImageV4Codec().textFromBody(mixed.body); + for (final name in ['Radio', '救援隊']) { + final nameBytes = utf8.encode(name).length; + output.add({'art': dense ? 'dense16' : 'cross16', 'senderName':name, 'senderNameBytes':nameBytes, + 'v3BodyBytes':v3Body.length, 'v4MixedBodyBytes':mixed.body.length, + 'v3ChannelDataBytes':1+nameBytes+1+v3Body.length, + 'v4ChannelDataBytes':1+nameBytes+1+mixed.body.length, + 'channelDataBudget':165, 'channelTextBudget':139-nameBytes-2, + 'v3TextBytes':utf8.encode(v3Text).length,'v4TextBytes':utf8.encode(v4Text).length, + 'v3ComposedChannelTextBytes':nameBytes+2+utf8.encode(v3Text).length, + 'v4ComposedChannelTextBytes':nameBytes+2+utf8.encode(v4Text).length, + 'v3BinaryHostCommandBytes':5+1+nameBytes+1+v3Body.length, + 'v4BinaryHostCommandBytes':5+1+nameBytes+1+mixed.body.length, + 'v3ChannelTextHostCommandBytes':7+utf8.encode(v3Text).length, + 'v4ChannelTextHostCommandBytes':7+utf8.encode(v4Text).length, + 'v3DirectTextHostCommandBytes':13+utf8.encode(v3Text).length, + 'v4DirectTextHostCommandBytes':13+utf8.encode(v4Text).length, + 'directTextBudget':150}); + } + } + File(Platform.environment['MCOIMG_COST_OUTPUT'] ?? 'mcoimg-wire-cost.json') + .writeAsStringSync(const JsonEncoder.withIndent(' ').convert(output)); + }); +} diff --git a/scripts/mcoimg/verify-v3.dart b/scripts/mcoimg/verify-v3.dart new file mode 100644 index 0000000000..fa3b143e4c --- /dev/null +++ b/scripts/mcoimg/verify-v3.dart @@ -0,0 +1,35 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/mcoimg_types.dart'; +import 'package:meshcore_open/helpers/mcoimg_v3_codec.dart'; + +void main() { + test('tagged Dart codec decodes Swift-generated MCOimg v3 bodies', () async { + final path = Platform.environment['MCOIMG_FIXTURES']; + expect(path, isNotNull, reason: 'Set MCOIMG_FIXTURES to v3-swift-encoded.json'); + final document = jsonDecode(await File(path!).readAsString()) as Map; + final fixtures = document['fixtures'] as List; + final codec = MCOImageV3Codec(); + for (final raw in fixtures) { + final fixture = Map.from(raw as Map); + final name = fixture['name'] as String; + final body = Uint8List.fromList(base64Decode(fixture['bodyBase64'] as String)); + final app = Uint8List.fromList(base64Decode(fixture['appPayloadBase64'] as String)); + final expectedProfile = PaletteProfile.values.firstWhere((profile) => profile.name == fixture['paletteProfile']); + for (final image in [codec.decodeBody(body), codec.decodeAppPayloadWithoutSender(app), codec.decodeText(fixture['text'] as String)]) { + expect(image.width, fixture['width'], reason: name); + expect(image.height, fixture['height'], reason: name); + expect(image.paletteProfile, expectedProfile, reason: name); + expect(image.transparentColor, fixture['transparentColor'], reason: name); + expect(image.pixels, fixture['pixels'], reason: name); + } + expect(MCOImageV3Codec.bodyFromText(fixture['text'] as String), body, reason: name); + } + // Printed only by this reproducible development verifier, never by application code. + // ignore: avoid_print + print('Tagged Dart verified ${fixtures.length} Swift v3 fixtures (body, app payload, text)'); + }); +} diff --git a/scripts/mcoimg/verify-v3.swift b/scripts/mcoimg/verify-v3.swift new file mode 100644 index 0000000000..591b575717 --- /dev/null +++ b/scripts/mcoimg/verify-v3.swift @@ -0,0 +1,68 @@ +import Foundation + +@main +struct VerifyV3 { + static let profileNames = [ + "mono", "master4", "master8", "master16", "master32", "master64", "grayscale16", "grayscale32", "grayscale8", + "dynamicGlobal8", "dynamicGlobal16", "dynamicGlobal32", "dynamicGlobal64", "dynamicGlobal128", "dynamicGlobal256", "dynamicGlobal512" + ] + + static func generatedFixture(_ name: String, width: Int, height: Int, profile: Int, pixels: [Int], nonce: UInt8) throws -> [String: Any] { + let image = MCOImageRaster(width: width, height: height, profile: profile, pixels: pixels) + let body = try MCOImageV3Codec.encode(image, nonce: nonce) + return ["name": name, "width": width, "height": height, "paletteProfile": profileNames[profile], "pixels": pixels, + "transparentColor": NSNull(), "bodyBase64": body.base64EncodedString(), "text": "im3:" + MCOImageBase91.encode(Data([0x13]) + body)] + } + + static func main() throws { + let fixtureURL = URL(fileURLWithPath: CommandLine.arguments[1]) + let document = try JSONSerialization.jsonObject(with: Data(contentsOf: fixtureURL)) as! [String: Any] + var fixtures = document["fixtures"] as! [[String: Any]] + var painted = Array(repeating: 0, count: 16 * 16) + for y in 3...12 { + for x in 3...12 where y == 3 || y == 12 || x == 3 || x == 12 { painted[y * 16 + x] = 6 } + } + for y in 6...9 { for x in 6...9 { painted[y * 16 + x] = 3 } } + fixtures.append(try generatedFixture("painted16", width: 16, height: 16, profile: 2, pixels: painted, nonce: 0)) + let dense = (0..<(16 * 16)).map { (($0 % 16) * 17 + ($0 / 16) * 29 + (($0 % 16) * ($0 / 16))) % 64 } + fixtures.append(try generatedFixture("dense16", width: 16, height: 16, profile: 5, pixels: dense, nonce: 255)) + for profile in 0..<16 { + let refs = MCOImagePalette.profileReferences(profile) + let pixels = (0..<12).map { refs[($0 * 7 + $0 / 4) % refs.count] } + for nonce: UInt8 in [0, 255] { + fixtures.append(try generatedFixture("profile-\(profile)-nonce-\(nonce)", width: 4, height: 3, profile: profile, pixels: pixels, nonce: nonce)) + } + } + var generated: [[String: Any]] = [] + for fixture in fixtures { + let name = fixture["name"] as! String + let body = Data(base64Encoded: fixture["bodyBase64"] as! String)! + let profile = profileNames.firstIndex(of: fixture["paletteProfile"] as! String)! + let expected = MCOImageRaster(width: fixture["width"] as! Int, height: fixture["height"] as! Int, + profile: profile, pixels: fixture["pixels"] as! [Int], transparentColor: fixture["transparentColor"] as? Int) + do { + let actual = try MCOImageV3Codec.decodeBody(body) + guard actual == expected else { fatalError("Fixture differs: \(name)") } + guard try MCOImageBase91.decode(String((fixture["text"] as! String).dropFirst(4))) == Data([0x13]) + body else { + fatalError("Base91 differs: \(name)") + } + let encoded = try MCOImageV3Codec.encode(expected, nonce: body.first!) + guard try MCOImageV3Codec.decodeBody(encoded) == expected else { fatalError("Roundtrip differs: \(name)") } + var output = fixture + output["name"] = "swift-\(name)" + output["bodyBase64"] = encoded.base64EncodedString() + let app = Data([0x13]) + encoded + output["appPayloadBase64"] = app.base64EncodedString() + output["text"] = "im3:" + MCOImageBase91.encode(app) + output.removeValue(forKey: "container") + output.removeValue(forKey: "algorithm") + generated.append(output) + } catch { fatalError("Fixture \(name): \(error)") } + } + if CommandLine.arguments.count > 2 { + try JSONSerialization.data(withJSONObject: ["schema": 1, "generator": "scripts/mcoimg/verify-v3.swift", "fixtures": generated], options: [.prettyPrinted, .sortedKeys]) + .write(to: URL(fileURLWithPath: CommandLine.arguments[2])) + } + print("Verified 39 upstream v3 fixtures and \(fixtures.count) Swift encoder roundtrips") + } +} diff --git a/scripts/mcoimg/verify-v4-raster.dart b/scripts/mcoimg/verify-v4-raster.dart new file mode 100644 index 0000000000..8d9740c528 --- /dev/null +++ b/scripts/mcoimg/verify-v4-raster.dart @@ -0,0 +1,48 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/mcoimg_types.dart'; +import 'package:meshcore_open/helpers/mcoimg_v4_codec.dart'; +import 'package:meshcore_open/helpers/mcoimg_v4_model.dart'; + +void main() { + test('tagged Dart decodes Swift v4 mixed raster payloads', () async { + final path = Platform.environment['MCOIMG_FIXTURES']!; + final fixtures = (jsonDecode(await File(path).readAsString()) as Map)['fixtures'] as List; + const codec = MCOImageV4Codec(); + for (final raw in fixtures) { + final fixture = Map.from(raw as Map); + final body = Uint8List.fromList(base64Decode(fixture['bodyBase64'] as String)); + final app = base64Decode(fixture['appPayloadBase64'] as String); + final name = fixture['name'] as String; + expect(app, [0x14, ...body], reason: name); + expect(codec.bodyFromText(fixture['text'] as String), body, reason: name); + for (final decoded in [codec.decodeBody(body), codec.decodeText(fixture['text'] as String)]) { + final document = decoded.document; + expect(decoded.nonce, fixture['nonce'], reason: name); + expect(document.mode, MCOImageV4Mode.mixed, reason: name); + expect(document.width, fixture['width'], reason: name); + expect(document.height, fixture['height'], reason: name); + expect(document.paletteProfile, PaletteProfile.values[fixture['profile'] as int], reason: name); + expect(document.figures.length, 1, reason: name); + final layer = document.figures.single as MCOImageV4RasterLayer; + if (fixture['transparentColor'] != null) { + expect(document.backgroundColor, isNull, reason: name); + } + expect([layer.x, layer.y, layer.width, layer.height], + [0, 0, fixture['width'], fixture['height']], reason: name); + expect(layer.transparentColor, fixture['transparentColor'], reason: name); + expect(layer.pixels, fixture['pixels'], reason: name); + expect(decoded.targetName, isNull, reason: name); + expect(decoded.replyTimestamp, isNull, reason: name); + if (name.startsWith('dimensions-')) { + expect(codec.encode(document, nonce: decoded.nonce).body, body, reason: name); + } + } + } + // ignore: avoid_print + print('Tagged Dart verified ${fixtures.length} Swift v4 mixed rasters'); + }); +} diff --git a/scripts/mcoimg/verify-v4-raster.swift b/scripts/mcoimg/verify-v4-raster.swift new file mode 100644 index 0000000000..49995f901c --- /dev/null +++ b/scripts/mcoimg/verify-v4-raster.swift @@ -0,0 +1,38 @@ +import Foundation + +@main +struct VerifyV4Raster { + static func main() throws { + let input = try Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1])) + let document = try JSONSerialization.jsonObject(with: input) as! [String: Any] + var fixtures = document["fixtures"] as! [[String: Any]] + for (width, height) in [(1, 1), (32, 31), (33, 32), (64, 64), (65, 65), (256, 1), (1, 256)] { + let image = MCOImageRaster(width: width, height: height, profile: 2, pixels: Array(repeating: 0, count: width * height)) + fixtures.append(["name": "dimensions-\(width)x\(height)", + "bodyBase64": try MCOImageV3Codec.encode(image, nonce: 42).base64EncodedString()]) + } + var output: [[String: Any]] = [] + for fixture in fixtures { + let source = Data(base64Encoded: fixture["bodyBase64"] as! String)! + let image = try MCOImageV3Codec.decodeBody(source) + let body = try MCOImageV4Codec.wrappingV3Body(source) + let decoded = try MCOImageV4Codec.decodeBody(body) + let background = image.transparentColor == nil ? MCOImagePalette.white(profile: image.profile) : nil + guard decoded.width == image.width, decoded.height == image.height, decoded.profile == image.profile, + decoded.backgroundColor == background, + decoded.figures == [.raster(origin: .init(x: 0, y: 0), image: image)], body.first == source.first else { + fatalError("Swift mixed raster differs: \(fixture["name"]!)") + } + let app = Data([MCOImageCodec.v4Subtype]) + body + output.append(["name": fixture["name"]!, "width": image.width, "height": image.height, + "profile": image.profile, "pixels": image.pixels, + "transparentColor": image.transparentColor as Any? ?? NSNull(), + "nonce": Int(source.first!), "sourceV3BodyBase64": source.base64EncodedString(), + "bodyBase64": body.base64EncodedString(), "appPayloadBase64": app.base64EncodedString(), + "text": try MCOImageCodec.text(fromAppPayload: app)]) + } + try JSONSerialization.data(withJSONObject: ["fixtures": output], options: [.prettyPrinted, .sortedKeys]) + .write(to: URL(fileURLWithPath: CommandLine.arguments[2])) + print("Verified \(output.count) Swift v4 mixed raster wraps") + } +} From 8fb58211a96aabc3451c20f8ca03db73772a5319 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:33:06 -0800 Subject: [PATCH 02/13] feat: send pixel drawings from the cover - Cover Send admits the drawing immediately, so the staged preview is gone - Failures keep the pixels and use a title for connection, encode, or size - The cover shows progress while sending, and Clear and the canvas stay idle - The Pixel Paint strings are translated in the other locales --- MC1/Resources/Generated/L10n.swift | 14 +- .../Localization/de.lproj/Chats.strings | 59 +-- .../Localization/en.lproj/Chats.strings | 17 +- .../Localization/es.lproj/Chats.strings | 59 +-- .../Localization/fr.lproj/Chats.strings | 59 +-- .../Localization/it.lproj/Chats.strings | 59 +-- .../Localization/ko.lproj/Chats.strings | 59 +-- .../Localization/nl.lproj/Chats.strings | 59 +-- .../Localization/pl.lproj/Chats.strings | 59 +-- .../Localization/pt.lproj/Chats.strings | 59 +-- .../Localization/ru.lproj/Chats.strings | 59 +-- .../Localization/uk.lproj/Chats.strings | 59 +-- .../Localization/zh-Hans.lproj/Chats.strings | 59 +-- .../Chats/ChatConversationInputBar.swift | 101 +--- MC1/Views/Chats/ChatConversationView.swift | 3 +- MC1/Views/Chats/Components/ChatInputBar.swift | 15 +- MC1/Views/Chats/MCOimg/PixelPaintDraft.swift | 196 +++++++- MC1/Views/Chats/MCOimg/PixelPaintEditor.swift | 52 +- .../ChatKeyboardTransitionTests.swift | 2 +- .../ChatNativeSplitLayoutTests.swift | 3 +- .../Views/Chats/PixelPaintDraftTests.swift | 230 ++++++++- .../Chats/PixelPaintPresentationTests.swift | 459 +++++++++++++++--- scripts/mcoimg/README.md | 23 +- 23 files changed, 1249 insertions(+), 515 deletions(-) diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index d41b921b99..2e6058879c 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -569,28 +569,30 @@ public enum L10n { } /// Placeholder when an MCOimg payload cannot be decoded public static let damaged = L10n.tr("Chats", "chats.mcoimg.damaged", fallback: "Damaged image") - /// Status shown when a pixel drawing is staged for Send - public static let draft = L10n.tr("Chats", "chats.mcoimg.draft", fallback: "Drawing ready to send") - /// Reopens the editor for a staged pixel drawing - public static let edit = L10n.tr("Chats", "chats.mcoimg.edit", fallback: "Edit Drawing") /// Progress label while a pixel drawing is encoded public static let encoding = L10n.tr("Chats", "chats.mcoimg.encoding", fallback: "Encoding Drawing") /// Error when a pixel drawing cannot be encoded public static let encodingFailed = L10n.tr("Chats", "chats.mcoimg.encodingFailed", fallback: "Unable to encode the drawing.") + /// Alert title when a pixel drawing cannot be encoded + public static let encodingFailedTitle = L10n.tr("Chats", "chats.mcoimg.encodingFailedTitle", fallback: "Unable to Encode") /// VoiceOver name for a rendered MCOimg public static let image = L10n.tr("Chats", "chats.mcoimg.image", fallback: "MCOimg image") /// VoiceOver name for one cell; arguments are 1-based column and row public static func pixel(_ p1: Int, _ p2: Int) -> String { return L10n.tr("Chats", "chats.mcoimg.pixel", p1, p2, fallback: "Pixel %d, %d") } - /// Removes a staged pixel drawing from the composer - public static let remove = L10n.tr("Chats", "chats.mcoimg.remove", fallback: "Remove Drawing") + /// Sends the open pixel drawing + public static let send = L10n.tr("Chats", "chats.mcoimg.send", fallback: "Send") + /// Progress label once a pixel drawing has been handed to the conversation + public static let sending = L10n.tr("Chats", "chats.mcoimg.sending", fallback: "Sending drawing") /// Editor title and the compose-menu action for a pixel drawing public static let title = L10n.tr("Chats", "chats.mcoimg.title", fallback: "Pixel Paint") /// Error when a pixel drawing exceeds the conversation limit; arguments are size then limit public static func tooLarge(_ p1: Int, _ p2: Int) -> String { return L10n.tr("Chats", "chats.mcoimg.tooLarge", p1, p2, fallback: "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again.") } + /// Alert title when a pixel drawing exceeds the conversation limit + public static let tooLargeTitle = L10n.tr("Chats", "chats.mcoimg.tooLargeTitle", fallback: "Drawing Too Large") /// Placeholder when an MCOimg version cannot be shown public static let unsupported = L10n.tr("Chats", "chats.mcoimg.unsupported", fallback: "Unsupported image format") } diff --git a/MC1/Resources/Localization/de.lproj/Chats.strings b/MC1/Resources/Localization/de.lproj/Chats.strings index 351e67ccdf..eb45dc9cc7 100644 --- a/MC1/Resources/Localization/de.lproj/Chats.strings +++ b/MC1/Resources/Localization/de.lproj/Chats.strings @@ -1058,47 +1058,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel malen"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Nicht unterstütztes Bildformat"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Beschädigtes Bild"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg Bild"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Zeichnung löschen"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Senden"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Farbe %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixel-Leinwand"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; - -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +/* VoiceOver name for one cell; arguments are 1-based column and row */ "chats.mcoimg.pixel" = "Pixel %d, %d"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Zeichnung zu groß"; + +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Die Zeichnung ist %d Bytes groß; diese Unterhaltung erlaubt %d Bytes. Vereinfache die Zeichnung und versuche es erneut."; + +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Kodieren nicht möglich"; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Die Zeichnung konnte nicht kodiert werden."; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Zeichnung wird kodiert"; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Zeichnung wird gesendet"; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Bild"; diff --git a/MC1/Resources/Localization/en.lproj/Chats.strings b/MC1/Resources/Localization/en.lproj/Chats.strings index da28c00261..f4119e87eb 100644 --- a/MC1/Resources/Localization/en.lproj/Chats.strings +++ b/MC1/Resources/Localization/en.lproj/Chats.strings @@ -1083,11 +1083,8 @@ /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Clear Drawing"; -/* Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; - -/* Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Send"; /* VoiceOver name for a palette swatch; the argument is 1-based */ "chats.mcoimg.color" = "Color %d"; @@ -1098,18 +1095,24 @@ /* VoiceOver name for one cell; arguments are 1-based column and row */ "chats.mcoimg.pixel" = "Pixel %d, %d"; -/* Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Drawing Too Large"; /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Unable to Encode"; + /* Error when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; /* Progress label while a pixel drawing is encoded */ "chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Sending drawing"; + // MARK: - Image Viewer /* Location: FullScreenImageViewer.swift - Close button label */ diff --git a/MC1/Resources/Localization/es.lproj/Chats.strings b/MC1/Resources/Localization/es.lproj/Chats.strings index 732fa5eed1..8413bcfe9c 100644 --- a/MC1/Resources/Localization/es.lproj/Chats.strings +++ b/MC1/Resources/Localization/es.lproj/Chats.strings @@ -1058,47 +1058,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pintura de píxeles"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Formato de imagen no compatible"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Imagen dañada"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "Imagen MCOimg"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Borrar dibujo"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Enviar"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; - -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ +/* VoiceOver name for a palette swatch; the argument is 1-based */ "chats.mcoimg.color" = "Color %d"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Lienzo de píxeles"; + +/* VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Píxel %d, %d"; + +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Dibujo demasiado grande"; -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "El dibujo es de %d bytes; esta conversación permite %d. Simplifica el dibujo e inténtalo de nuevo."; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "No se puede codificar"; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "No se puede codificar el dibujo."; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Codificando el dibujo"; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Enviando el dibujo"; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Imagen"; diff --git a/MC1/Resources/Localization/fr.lproj/Chats.strings b/MC1/Resources/Localization/fr.lproj/Chats.strings index a25cf028ad..34c98e9869 100644 --- a/MC1/Resources/Localization/fr.lproj/Chats.strings +++ b/MC1/Resources/Localization/fr.lproj/Chats.strings @@ -1058,47 +1058,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Peinture pixel"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Format d'image non pris en charge"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Image endommagée"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "Image MCOimg"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Effacer le dessin"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Envoyer"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Couleur %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Canevas de pixels"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; - -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +/* VoiceOver name for one cell; arguments are 1-based column and row */ "chats.mcoimg.pixel" = "Pixel %d, %d"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Dessin trop volumineux"; + +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Le dessin fait %d octets ; cette conversation en autorise %d. Simplifiez le dessin et réessayez."; + +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Encodage impossible"; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Impossible d'encoder le dessin."; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encodage du dessin"; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Envoi du dessin"; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Image"; diff --git a/MC1/Resources/Localization/it.lproj/Chats.strings b/MC1/Resources/Localization/it.lproj/Chats.strings index a3d1d11bc3..2e205fe7e8 100644 --- a/MC1/Resources/Localization/it.lproj/Chats.strings +++ b/MC1/Resources/Localization/it.lproj/Chats.strings @@ -1051,47 +1051,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Disegno a pixel"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Formato immagine non supportato"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Immagine danneggiata"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "Immagine MCOimg"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Cancella disegno"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Invia"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Colore %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Area di disegno a pixel"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; - -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +/* VoiceOver name for one cell; arguments are 1-based column and row */ "chats.mcoimg.pixel" = "Pixel %d, %d"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Disegno troppo grande"; + +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Il disegno è di %d byte; questa conversazione consente %d byte. Semplifica il disegno e riprova."; + +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Impossibile codificare"; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Impossibile codificare il disegno."; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Codifica del disegno"; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Invio del disegno"; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Immagine"; diff --git a/MC1/Resources/Localization/ko.lproj/Chats.strings b/MC1/Resources/Localization/ko.lproj/Chats.strings index ee67a6ab47..554758ce71 100644 --- a/MC1/Resources/Localization/ko.lproj/Chats.strings +++ b/MC1/Resources/Localization/ko.lproj/Chats.strings @@ -1051,47 +1051,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "픽셀 그리기"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "지원되지 않는 이미지 형식"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "손상된 이미지"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg 이미지"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "그림 지우기"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "보내기"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "색상 %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "픽셀 캔버스"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; +/* VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "픽셀 %d, %d"; -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "그림이 너무 큼"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "그림이 %d바이트입니다. 이 대화는 %d바이트까지 허용합니다. 그림을 단순화한 후 다시 시도하십시오."; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "인코딩할 수 없음"; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "그림을 인코딩할 수 없습니다."; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "그림 인코딩 중..."; + +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "그림 보내는 중..."; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "이미지"; diff --git a/MC1/Resources/Localization/nl.lproj/Chats.strings b/MC1/Resources/Localization/nl.lproj/Chats.strings index 4f8182715d..2bf453502d 100644 --- a/MC1/Resources/Localization/nl.lproj/Chats.strings +++ b/MC1/Resources/Localization/nl.lproj/Chats.strings @@ -1058,47 +1058,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixeltekenen"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Niet-ondersteund afbeeldingsformaat"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Beschadigde afbeelding"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg-afbeelding"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Tekening wissen"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Verzenden"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Kleur %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Pixelcanvas"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; - -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ +/* VoiceOver name for one cell; arguments are 1-based column and row */ "chats.mcoimg.pixel" = "Pixel %d, %d"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Tekening te groot"; + +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "De tekening is %d bytes; dit gesprek staat %d toe. Vereenvoudig de tekening en probeer het opnieuw."; + +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Kan niet coderen"; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Kan de tekening niet coderen."; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Tekening wordt gecodeerd"; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Tekening wordt verzonden"; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Afbeelding"; diff --git a/MC1/Resources/Localization/pl.lproj/Chats.strings b/MC1/Resources/Localization/pl.lproj/Chats.strings index 364abac136..8badaccdbe 100644 --- a/MC1/Resources/Localization/pl.lproj/Chats.strings +++ b/MC1/Resources/Localization/pl.lproj/Chats.strings @@ -1050,47 +1050,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Malowanie pikseli"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Nieobsługiwany format obrazu"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Uszkodzony obraz"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "Obraz MCOimg"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Wyczyść rysunek"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Wyślij"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Kolor %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Płótno pikseli"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; +/* VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Piksel %d, %d"; -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Rysunek za duży"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Rysunek ma %d bajtów; ta rozmowa pozwala na %d. Uprość rysunek i spróbuj ponownie."; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Nie można zakodować"; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Nie można zakodować rysunku."; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Kodowanie rysunku"; + +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Wysyłanie rysunku"; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Obraz"; diff --git a/MC1/Resources/Localization/pt.lproj/Chats.strings b/MC1/Resources/Localization/pt.lproj/Chats.strings index 584101b785..d8882543c1 100644 --- a/MC1/Resources/Localization/pt.lproj/Chats.strings +++ b/MC1/Resources/Localization/pt.lproj/Chats.strings @@ -1051,47 +1051,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pintura de píxeis"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Formato de imagem não suportado"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Imagem danificada"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "Imagem MCOimg"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Limpar desenho"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Enviar"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Cor %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Área de píxeis"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; +/* VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Píxel %d, %d"; -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Desenho demasiado grande"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "O desenho tem %d bytes; esta conversa permite %d. Simplifique o desenho e tente novamente."; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Não foi possível codificar"; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Não foi possível codificar o desenho."; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "A codificar o desenho..."; + +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "A enviar o desenho..."; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Imagem"; diff --git a/MC1/Resources/Localization/ru.lproj/Chats.strings b/MC1/Resources/Localization/ru.lproj/Chats.strings index 4f9e66c7b2..a8664e8664 100644 --- a/MC1/Resources/Localization/ru.lproj/Chats.strings +++ b/MC1/Resources/Localization/ru.lproj/Chats.strings @@ -1049,47 +1049,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Пиксель-арт"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Неподдерживаемый формат изображения"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Повреждённое изображение"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "Изображение MCOimg"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Очистить рисунок"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Отправить"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Цвет %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Пиксельный холст"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; +/* VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Пиксель %d, %d"; -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Рисунок слишком большой"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Рисунок — %d байт; этот разговор допускает %d. Упрости рисунок и попробуй снова."; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Не удалось закодировать"; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Не удалось закодировать рисунок."; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Кодирование рисунка"; + +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Отправка рисунка"; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Изображение"; diff --git a/MC1/Resources/Localization/uk.lproj/Chats.strings b/MC1/Resources/Localization/uk.lproj/Chats.strings index d137c22872..e7f25f32fe 100644 --- a/MC1/Resources/Localization/uk.lproj/Chats.strings +++ b/MC1/Resources/Localization/uk.lproj/Chats.strings @@ -1049,47 +1049,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Піксельний малюнок"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Непідтримуваний формат зображення"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Пошкоджене зображення"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "Зображення MCOimg"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Очистити малюнок"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Надіслати"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "Колір %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "Піксельне полотно"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; +/* VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "Піксель %d, %d"; -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Малюнок занадто великий"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "Малюнок займає %d байт; ця розмова дозволяє %d. Спрости малюнок і спробуй ще раз."; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "Не вдалося закодувати"; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Не вдалося закодувати малюнок."; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Кодування малюнка"; + +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "Надсилання малюнка"; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Зображення"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings index 2a2fb460b6..f16ddb0863 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings @@ -1115,47 +1115,50 @@ // MARK: - MCOimg -/* TODO: translate - Editor title and the compose-menu action for a pixel drawing */ -"chats.mcoimg.title" = "Pixel Paint"; +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "像素画"; -/* TODO: translate - Placeholder when an MCOimg version cannot be shown */ -"chats.mcoimg.unsupported" = "Unsupported image format"; +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "不支持的图片格式"; -/* TODO: translate - Placeholder when an MCOimg payload cannot be decoded */ -"chats.mcoimg.damaged" = "Damaged image"; +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "图片已损坏"; -/* TODO: translate - VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* VoiceOver name for a rendered MCOimg */ +"chats.mcoimg.image" = "MCOimg 图片"; -/* TODO: translate - Erases every pixel in the editor */ -"chats.mcoimg.clear" = "Clear Drawing"; +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "清除绘图"; -/* TODO: translate - Removes a staged pixel drawing from the composer */ -"chats.mcoimg.remove" = "Remove Drawing"; +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "发送"; -/* TODO: translate - Reopens the editor for a staged pixel drawing */ -"chats.mcoimg.edit" = "Edit Drawing"; +/* VoiceOver name for a palette swatch; the argument is 1-based */ +"chats.mcoimg.color" = "颜色 %d"; -/* TODO: translate - VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for the pixel drawing canvas */ +"chats.mcoimg.canvas" = "像素画布"; -/* TODO: translate - VoiceOver name for the pixel drawing canvas */ -"chats.mcoimg.canvas" = "Pixel canvas"; +/* VoiceOver name for one cell; arguments are 1-based column and row */ +"chats.mcoimg.pixel" = "像素,第 %d 列,第 %d 行"; -/* TODO: translate - VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "绘图过大"; -/* TODO: translate - Status shown when a pixel drawing is staged for Send */ -"chats.mcoimg.draft" = "Drawing ready to send"; +/* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ +"chats.mcoimg.tooLarge" = "绘图为 %d 字节,此对话允许 %d 字节。请简化绘图并重试。"; -/* TODO: translate - Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ -"chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Alert title when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailedTitle" = "无法编码"; -/* TODO: translate - Error when a pixel drawing cannot be encoded */ -"chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "无法编码此绘图。"; -/* TODO: translate - Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "正在编码绘图..."; + +/* Progress label once a pixel drawing has been handed to the conversation */ +"chats.mcoimg.sending" = "正在发送绘图..."; /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "图片"; diff --git a/MC1/Views/Chats/ChatConversationInputBar.swift b/MC1/Views/Chats/ChatConversationInputBar.swift index c1cbf2a244..c5e2eca883 100644 --- a/MC1/Views/Chats/ChatConversationInputBar.swift +++ b/MC1/Views/Chats/ChatConversationInputBar.swift @@ -9,28 +9,22 @@ struct ChatConversationInputBar: View { let nodeNameByteCount: Int let onSend: (String) async -> Bool let onWillSend: () -> Void + let onDrawingRejected: () -> Void @Environment(\.appState) private var appState @State private var drawing = PixelPaintDraft() @State private var isShowingPainter = false - @State private var submissionTask: Task? - private static let previewSide: CGFloat = 56 var body: some View { - VStack(spacing: 0) { - if drawing.isStaged { stagedDrawing } - inputBar - } + inputBar .fullScreenCover(isPresented: $isShowingPainter) { - PixelPaintEditor(draft: drawing) + PixelPaintEditor(draft: drawing, onSend: sendDrawing) } - .errorAlert($drawing.errorMessage) .onChange(of: conversationType.coordinatorID) { - submissionTask?.cancel() drawing.remove() isShowingPainter = false } - .onDisappear { submissionTask?.cancel() } + .onDisappear { drawing.remove() } } @ViewBuilder @@ -44,10 +38,7 @@ struct ChatConversationInputBar: View { maxBytes: ProtocolLimits.maxDirectMessageLength, isEncrypted: true, leading: { ChatShareMenu(onInsert: insertShared, onPaint: openPainter) }, - onSend: send, - hasAttachment: drawing.isStaged, - isSubmittingAttachment: drawing.isSubmitting, - onSendAttachment: sendDrawing + onSend: send ) case let .channel(channel): @@ -63,34 +54,11 @@ struct ChatConversationInputBar: View { maxBytes: maxBytes, isEncrypted: channel.isEncryptedChannel, leading: { ChatShareMenu(onInsert: insertShared, onPaint: openPainter) }, - onSend: send, - hasAttachment: drawing.isStaged, - isSubmittingAttachment: drawing.isSubmitting, - onSendAttachment: sendDrawing + onSend: send ) } } - private var stagedDrawing: some View { - HStack { - Button(action: openPainter) { - MCOImageRenderer(content: .raster(drawing.image)) - .frame(width: Self.previewSide, height: Self.previewSide) - } - .accessibilityLabel(L10n.Chats.Chats.Mcoimg.edit) - .accessibilityIdentifier("stagedPixelDrawing") - Text(L10n.Chats.Chats.Mcoimg.draft).font(.caption) - Spacer() - if drawing.isSubmitting { - ProgressView().accessibilityLabel(L10n.Chats.Chats.Mcoimg.encoding) - } - Button(L10n.Chats.Chats.Mcoimg.remove, systemImage: "xmark.circle") { drawing.remove() } - .labelStyle(.iconOnly) - } - .disabled(drawing.isSubmitting) - .padding(.horizontal) - } - private func openPainter() { guard !drawing.isSubmitting else { return } ChatKeyboardLift.resignFirstResponder() @@ -98,39 +66,25 @@ struct ChatConversationInputBar: View { } private func sendDrawing() { - guard drawing.isStaged, !drawing.isSubmitting, appState.connectionState == .ready else { return } - let snapshot = drawing.image let isChannel: Bool = if case .channel = conversationType { true } else { false } - drawing.isSubmitting = true - drawing.errorMessage = nil - submissionTask = Task { - defer { drawing.isSubmitting = false } - do { - let text = try await encodeDrawing(snapshot, channel: isChannel) - try Task.checkCancellation() - guard appState.connectionState == .ready, - appState.connectedDevice?.radioID == conversationType.radioID else { - drawing.errorMessage = L10n.Chats.Chats.Alert.UnableToSend.message - return - } - let bytes = if isChannel { - try MCOImageTransport.encode(text: text, senderName: appState.connectedDevice?.nodeName ?? "").count - } else { - text.utf8.count - } - let limit = isChannel ? MCOImageWireBudget.maximumChannelDataBytes : ProtocolLimits.maxDirectMessageLength - guard bytes <= limit else { - drawing.errorMessage = L10n.Chats.Chats.Mcoimg.tooLarge(bytes, limit) - return - } - onWillSend() - if await onSend(text) { drawing.remove() } - } catch is CancellationError { - return - } catch { - drawing.errorMessage = L10n.Chats.Chats.Mcoimg.encodingFailed - } + let radioID = conversationType.radioID + let ready = { + appState.connectionState == .ready && appState.connectedDevice?.radioID == radioID } + guard let attempt = drawing.begin(isReady: ready) else { return } + let task = Task { + await drawing.run( + attempt, + isChannel: isChannel, + senderName: { appState.connectedDevice?.nodeName ?? "" }, + isReady: ready, + onSend: onSend, + onWillSend: onWillSend, + onRejected: onDrawingRejected, + onAdmitted: { isShowingPainter = false } + ) + } + drawing.track(task) } private func send(_ text: String) { @@ -152,12 +106,3 @@ struct ChatConversationInputBar: View { focusRequest += 1 } } - -@concurrent -private func encodeDrawing(_ image: MCOImageRaster, channel: Bool) async throws -> String { - let body = try MCOImageV3Codec.encode(image, nonce: UInt8.random(in: .min ... .max)) - let payload = channel - ? try Data([MCOImageCodec.v4Subtype]) + MCOImageV4Codec.wrappingV3Body(body) - : Data([MCOImageCodec.v3Subtype]) + body - return try MCOImageCodec.text(fromAppPayload: payload) -} diff --git a/MC1/Views/Chats/ChatConversationView.swift b/MC1/Views/Chats/ChatConversationView.swift index 9f905e7658..141fe4b38f 100644 --- a/MC1/Views/Chats/ChatConversationView.swift +++ b/MC1/Views/Chats/ChatConversationView.swift @@ -200,7 +200,8 @@ struct ChatConversationView: View { await chatViewModel.sendChannelMessage(text: text) } }, - onWillSend: { scrollToBottomRequest += 1 } + onWillSend: { scrollToBottomRequest += 1 }, + onDrawingRejected: { chatViewModel.sendErrorMessage = nil } ) } .navigationHeader( diff --git a/MC1/Views/Chats/Components/ChatInputBar.swift b/MC1/Views/Chats/Components/ChatInputBar.swift index 9a84435d14..2fa05b2e50 100644 --- a/MC1/Views/Chats/Components/ChatInputBar.swift +++ b/MC1/Views/Chats/Components/ChatInputBar.swift @@ -34,9 +34,6 @@ struct ChatInputBar: View { let isEncrypted: Bool @ViewBuilder let leading: () -> Leading let onSend: (String) -> Void - var hasAttachment = false - var isSubmittingAttachment = false - var onSendAttachment: (() -> Void)? @State private var isCoolingDown = false @State private var sendInvocationCounter: Int = 0 @@ -48,11 +45,11 @@ struct ChatInputBar: View { } private var isOverLimit: Bool { - !hasAttachment && byteCount > maxBytes + byteCount > maxBytes } private var shouldShowCharacterCount: Bool { - !hasAttachment && byteCount >= maxBytes - 20 + byteCount >= maxBytes - 20 } var body: some View { @@ -121,8 +118,8 @@ struct ChatInputBar: View { private var canSend: Bool { !isCoolingDown && appState.connectionState == .ready && - !isSubmittingAttachment && - (hasAttachment || !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) && !isOverLimit + !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && + !isOverLimit } /// Hardware Return: `true` consumes it and sends under the same gates as the send @@ -135,10 +132,6 @@ struct ChatInputBar: View { private func send() { composerProxy.commitPendingInput() - if hasAttachment { - onSendAttachment?() - return - } let captured = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !captured.isEmpty else { return } isCoolingDown = true diff --git a/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift b/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift index d0f4919709..9f6628a50b 100644 --- a/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift +++ b/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift @@ -1,7 +1,8 @@ +import Foundation import MC1Services import Observation -/// Pixels belong to the conversation composer, so presenting or closing the editor never replaces them. +/// In-memory pixels for one conversation's Pixel Paint cover. @Observable @MainActor final class PixelPaintDraft { @@ -12,10 +13,14 @@ final class PixelPaintDraft { var pixels = Array(repeating: background, count: side * side) var selectedColor = initialBrush - var isStaged = false var isSubmitting = false + /// True once this submission has called `onSend`. Cancel stays enabled until then. + var isAdmitting = false + var errorTitle: String? var errorMessage: String? + private var submissionGeneration: UInt = 0 private var previousCell: (x: Int, y: Int)? + private var submissionTask: Task? var image: MCOImageRaster { MCOImageRaster(width: Self.side, height: Self.side, profile: Self.profile, pixels: pixels) @@ -40,13 +45,192 @@ final class PixelPaintDraft { func endStroke() { previousCell = nil } func clear() { - pixels = Array(repeating: Self.background, count: Self.side * Self.side) - endStroke() + guard !isSubmitting else { return } + resetPixels() } + /// Drops the current pixels and retires the in-flight submission. func remove() { - clear() - isStaged = false + submissionGeneration &+= 1 + submissionTask?.cancel() + submissionTask = nil + resetPixels() + isSubmitting = false + isAdmitting = false + errorTitle = nil + errorMessage = nil + } + + /// Pixels and generation captured when a submission starts. Painting is already frozen. + struct Attempt { + let snapshot: MCOImageRaster + let generation: UInt + } + + /// Starts a submission synchronously so a second tap cannot start another one. + /// Returns nil when one is already running or the connection is not ready. + func begin(isReady: () -> Bool) -> Attempt? { + guard !isSubmitting, isReady() else { return nil } + isSubmitting = true + isAdmitting = false + errorTitle = nil errorMessage = nil + return Attempt(snapshot: image, generation: submissionGeneration) + } + + /// Remembers the task `remove()` cancels when the drawing is retired. + func track(_ task: Task) { + submissionTask = task + } + + /// Encodes `attempt` and admits it only while that generation is still current. + func run( + _ attempt: Attempt, + isChannel: Bool, + senderName: @escaping () -> String, + isReady: @escaping () -> Bool, + onSend: @escaping (String) async -> Bool, + onWillSend: @escaping () -> Void, + onRejected: @escaping () -> Void, + onAdmitted: @escaping () -> Void, + encode: @escaping @Sendable (MCOImageRaster, Bool) async throws -> String = encodePixelDrawing + ) async { + guard isCurrent(attempt.generation) else { return } + let result = await outcome( + snapshot: attempt.snapshot, + isChannel: isChannel, + generation: attempt.generation, + senderName: senderName, + isReady: isReady, + onSend: onSend, + onWillSend: onWillSend, + encode: encode + ) + settle(result, generation: attempt.generation, onRejected: onRejected, onAdmitted: onAdmitted) + } + + private func resetPixels() { + pixels = Array(repeating: Self.background, count: Self.side * Self.side) + endStroke() + } + + private func outcome( + snapshot: MCOImageRaster, + isChannel: Bool, + generation: UInt, + senderName: @escaping () -> String, + isReady: @escaping () -> Bool, + onSend: @escaping (String) async -> Bool, + onWillSend: @escaping () -> Void, + encode: @escaping @Sendable (MCOImageRaster, Bool) async throws -> String + ) async -> SubmissionResult { + let text: String + do { + text = try await encode(snapshot, isChannel) + } catch is CancellationError { + return .retired + } catch { + guard isCurrent(generation) else { return .retired } + return Self.encodeFailed + } + // A retired submission must not admit, and must not write pixels, the error, or submission state. + guard isCurrent(generation) else { return .retired } + guard isReady() else { + return Self.unableToSend + } + let bytes: Int + do { + bytes = try Self.encodedByteCount(text: text, isChannel: isChannel, senderName: senderName()) + } catch { + guard isCurrent(generation) else { return .retired } + return Self.encodeFailed + } + guard isCurrent(generation) else { return .retired } + let limit = Self.byteLimit(isChannel: isChannel) + guard bytes <= limit else { + return .failed( + title: L10n.Chats.Chats.Mcoimg.tooLargeTitle, + message: L10n.Chats.Chats.Mcoimg.tooLarge(bytes, limit) + ) + } + guard isCurrent(generation) else { return .retired } + isAdmitting = true + onWillSend() + let accepted = await onSend(text) + guard isCurrent(generation) else { return .retired } + return accepted ? .admitted : .rejected + } + + private func settle( + _ result: SubmissionResult, + generation: UInt, + onRejected: () -> Void, + onAdmitted: () -> Void + ) { + guard isCurrent(generation) else { return } + switch result { + case .admitted: + remove() + onAdmitted() + case .rejected: + onRejected() + errorTitle = L10n.Chats.Chats.Alert.UnableToSend.title + errorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + isSubmitting = false + isAdmitting = false + case let .failed(title, message): + errorTitle = title + errorMessage = message + isSubmitting = false + isAdmitting = false + case .retired: + break + } + } + + private func isCurrent(_ generation: UInt) -> Bool { + submissionGeneration == generation && !Task.isCancelled + } + + private static func encodedByteCount(text: String, isChannel: Bool, senderName: String) throws -> Int { + if isChannel { + try MCOImageTransport.encode(text: text, senderName: senderName).count + } else { + text.utf8.count + } } + + private static func byteLimit(isChannel: Bool) -> Int { + isChannel ? MCOImageWireBudget.maximumChannelDataBytes : ProtocolLimits.maxDirectMessageLength + } + + private static var unableToSend: SubmissionResult { + .failed( + title: L10n.Chats.Chats.Alert.UnableToSend.title, + message: L10n.Chats.Chats.Alert.UnableToSend.message + ) + } + + private static var encodeFailed: SubmissionResult { + .failed( + title: L10n.Chats.Chats.Mcoimg.encodingFailedTitle, + message: L10n.Chats.Chats.Mcoimg.encodingFailed + ) + } + + private enum SubmissionResult { + case admitted + case rejected + case failed(title: String, message: String) + case retired + } +} + +@concurrent +func encodePixelDrawing(_ image: MCOImageRaster, channel: Bool) async throws -> String { + let body = try MCOImageV3Codec.encode(image, nonce: UInt8.random(in: .min ... .max)) + let payload = channel + ? try Data([MCOImageCodec.v4Subtype]) + MCOImageV4Codec.wrappingV3Body(body) + : Data([MCOImageCodec.v3Subtype]) + body + return try MCOImageCodec.text(fromAppPayload: payload) } diff --git a/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift b/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift index 15302d2c35..e0be396174 100644 --- a/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift +++ b/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift @@ -3,7 +3,9 @@ import SwiftUI struct PixelPaintEditor: View { @Bindable var draft: PixelPaintDraft + let onSend: () -> Void @Environment(\.dismiss) private var dismiss + @Environment(\.appState) private var appState private static let swatchSize: CGFloat = 36 private static let maximumCanvasSize: CGFloat = 480 private static let gridWidth: CGFloat = 0.5 @@ -15,6 +17,7 @@ struct PixelPaintEditor: View { NavigationStack { ScrollView { VStack(spacing: Self.contentSpacing) { + coverStatus canvas .aspectRatio(1, contentMode: .fit) .frame(maxWidth: Self.maximumCanvasSize) @@ -39,6 +42,7 @@ struct PixelPaintEditor: View { } } Button(L10n.Chats.Chats.Mcoimg.clear, systemImage: "eraser") { draft.clear() } + .disabled(draft.isSubmitting) } .padding() .frame(maxWidth: .infinity) @@ -46,20 +50,57 @@ struct PixelPaintEditor: View { .navigationTitle(L10n.Chats.Chats.Mcoimg.title) .navigationBarTitleDisplayMode(.inline) .toolbar { - ToolbarItem(placement: .topBarTrailing) { - Button(L10n.Localizable.Common.done) { + ToolbarItem(placement: .cancellationAction) { + Button(L10n.Localizable.Common.cancel, systemImage: "xmark") { draft.endStroke() - draft.isStaged = true + draft.remove() dismiss() } - .accessibilityIdentifier("pixelPaintDone") + .disabled(draft.isAdmitting) + .accessibilityHint(draft.isAdmitting ? L10n.Chats.Chats.Mcoimg.sending : "") + .accessibilityIdentifier("pixelPaintCancel") + } + ToolbarItem(placement: .confirmationAction) { + Button(L10n.Chats.Chats.Mcoimg.send, systemImage: "arrow.up") { + draft.endStroke() + onSend() + } + .disabled(!canSend) + .accessibilityHint(sendAccessibilityHint) + .accessibilityIdentifier("pixelPaintSend") } } } .interactiveDismissDisabled() + .errorAlert($draft.errorMessage, title: draft.errorTitle) .accessibilityIdentifier("pixelPaintEditor") } + private var canSend: Bool { + appState.connectionState == .ready && !draft.isSubmitting + } + + private var sendAccessibilityHint: String { + if draft.isSubmitting { + return draft.isAdmitting ? L10n.Chats.Chats.Mcoimg.sending : L10n.Chats.Chats.Mcoimg.encoding + } + if appState.connectionState != .ready { + return L10n.Chats.Chats.Input.requiresConnection + } + return "" + } + + @ViewBuilder + private var coverStatus: some View { + if draft.isSubmitting { + ProgressView(draft.isAdmitting ? L10n.Chats.Chats.Mcoimg.sending : L10n.Chats.Chats.Mcoimg.encoding) + } else if appState.connectionState != .ready { + Text(L10n.Chats.Chats.Input.requiresConnection) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + private var canvas: some View { Canvas { context, size in let cellSize = size.width / Double(PixelPaintDraft.side) @@ -81,10 +122,11 @@ struct PixelPaintEditor: View { draft.paint(x: Int(floor(value.location.x / side * Double(PixelPaintDraft.side))), y: Int(floor(value.location.y / side * Double(PixelPaintDraft.side)))) }.onEnded { _ in draft.endStroke() }) + .allowsHitTesting(!draft.isSubmitting) .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { canvasWidth = $0 } .accessibilityLabel(L10n.Chats.Chats.Mcoimg.canvas) .accessibilityIdentifier("pixelPaintCanvas") - .accessibilityRepresentation { accessiblePixels } + .accessibilityRepresentation { accessiblePixels.disabled(draft.isSubmitting) } } @State private var canvasWidth: CGFloat = 0 diff --git a/MC1Tests/Views/Chats/Components/ChatKeyboardTransitionTests.swift b/MC1Tests/Views/Chats/Components/ChatKeyboardTransitionTests.swift index 825871b3d1..4b1f9cdb89 100644 --- a/MC1Tests/Views/Chats/Components/ChatKeyboardTransitionTests.swift +++ b/MC1Tests/Views/Chats/Components/ChatKeyboardTransitionTests.swift @@ -61,7 +61,7 @@ struct ChatKeyboardTransitionTests { ChatConversationInputBar( conversationType: .channel(channel), composingText: $composerModel.text, focusRequest: $focusRequest, nodeNameByteCount: 0, - onSend: { _ in true }, onWillSend: {} + onSend: { _ in true }, onWillSend: {}, onDrawingRejected: {} ) .overlay(alignment: .bottomLeading) { Color(red: 1, green: 0, blue: 0) diff --git a/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift b/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift index 72252e3027..8da1fd8114 100644 --- a/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift +++ b/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift @@ -1031,7 +1031,8 @@ private struct ChatNativeSplitHarness: View { focusRequest: $model.inputFocusRequest, nodeNameByteCount: 0, onSend: { _ in true }, - onWillSend: { model.scrollToBottomRequest += 1 } + onWillSend: { model.scrollToBottomRequest += 1 }, + onDrawingRejected: {} ) .background { GateAIdentifierView(identifier: "gateA.composer") diff --git a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift index 99f93b2569..82aca9b383 100644 --- a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift @@ -5,35 +5,147 @@ import Testing @Suite("Pixel paint drafts") @MainActor struct PixelPaintDraftTests { - @Test func paintingInterpolatesAndRetainsPixelsAcrossEditorSessions() { + @Test func paintingInterpolatesAcrossTheCanvas() { let draft = PixelPaintDraft() draft.paint(x: 0, y: 0) draft.paint(x: PixelPaintDraft.side - 1, y: PixelPaintDraft.side - 1) draft.endStroke() - draft.isStaged = true - let staged = draft.image + let painted = draft.image for index in 0.. Task? { + guard let attempt = draft.begin(isReady: { self.ready }) else { return nil } + let pause = pause + let pauseOnEncode = pauseOnEncode + let pauseOnSend = pauseOnSend + let failEncode = failEncode + let oversized = oversized + let task = Task { + await draft.run( + attempt, + isChannel: false, + senderName: { "Radio" }, + isReady: { self.ready }, + onSend: { text in + self.payloads.append(text) + if pauseOnSend { await pause.pause() } + if !self.accept { + self.sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + } + return self.accept + }, + onWillSend: {}, + onRejected: { + self.rejected += 1 + self.sendErrorMessage = nil + }, + onAdmitted: { self.admitted += 1 }, + encode: { image, isChannel in + await MainActor.run { self.captured.append(image) } + if pauseOnEncode { await pause.pause() } + if failEncode { throw PixelEncodeFailure() } + if oversized { + return String(repeating: "a", count: ProtocolLimits.maxDirectMessageLength + 1) + } + return try await encodePixelDrawing(image, channel: isChannel) + } + ) + } + draft.track(task) + return task + } +} + +private struct PixelEncodeFailure: Error {} + +@MainActor +final class SubmissionPause { + private var release: CheckedContinuation? + private var entered: CheckedContinuation? + + func pause() async { + await withCheckedContinuation { (continuation: CheckedContinuation) in + release = continuation + entered?.resume() + entered = nil + } + } + + func untilPaused() async { + if release != nil { return } + await withCheckedContinuation { (continuation: CheckedContinuation) in + if release != nil { + continuation.resume() + } else { + entered = continuation + } + } + } + + func resume() { + release?.resume() + release = nil + } +} diff --git a/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift index b2e98a626d..fa4a8c4fec 100644 --- a/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift @@ -5,30 +5,27 @@ import Testing import UIKit @testable import MC1 +private struct AccessibilityDump: Error, CustomStringConvertible { + var description: String + init(_ description: String) { self.description = description } +} + @Suite("Pixel paint presentation", .serialized) @MainActor struct PixelPaintPresentationTests { - @Test func fullScreenEditorBlocksDismissalAndDoneRetainsPixelsThroughReopenAndDisconnect() async throws { + @Test func fullScreenCoverBlocksDismissalAndCancelDiscardsPixels() async throws { let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + appState.connectionManager.setTestState(connectionState: .ready) let draft = PixelPaintDraft() let presentation = Presentation() - let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) - let window = UIWindow(windowScene: scene) - let controller = UIHostingController(rootView: Harness(draft: draft, presentation: presentation).environment(\.appState, appState)) - window.rootViewController = controller - window.makeKeyAndVisible() - defer { - window.isHidden = true - window.rootViewController = nil - window.windowScene = nil - appState.shutdown() - } + let window = try host(Harness(draft: draft, presentation: presentation).environment(\.appState, appState)) + defer { release(window, appState: appState) } try await waitUntil("Harness should appear before presenting") { presentation.isReady } presentation.isPresented = true - try await waitUntil("Editor should present") { controller.presentedViewController != nil } - let presented = try #require(controller.presentedViewController) - #expect(presented.modalPresentationStyle == UIModalPresentationStyle.fullScreen || presented.modalPresentationStyle == UIModalPresentationStyle.overFullScreen) + try await waitUntil("Editor should present") { presentedController(in: window) != nil } + let presented = try #require(presentedController(in: window)) + #expect(presented.modalPresentationStyle == .fullScreen || presented.modalPresentationStyle == .overFullScreen) try await waitUntil("Editor should block interactive dismissal") { presented.isModalInPresentation || presented.presentationController.map { @@ -36,56 +33,192 @@ struct PixelPaintPresentationTests { } == true } do { - try await waitUntil("Done should be accessible") { descendants(presented.view).contains { $0.accessibilityLabel == L10n.Localizable.Common.done } } - } catch { - let labels = descendants(window).compactMap { object -> String? in - if let label = object.accessibilityLabel { return "\(type(of: object)): \(label) [\((object as? UIView)?.accessibilityIdentifier ?? "")]" } - return nil + try await waitUntil("Cancel and Send should be accessible") { + matching(L10n.Localizable.Common.cancel, in: window) != nil + && matching(L10n.Chats.Chats.Mcoimg.send, in: window) != nil } - Issue.record("Window accessibility labels: \(labels)") + } catch { + Issue.record(AccessibilityDump(accessibilityDump(window))) throw error } + #expect(isEnabled(L10n.Chats.Chats.Mcoimg.send, in: window) == true) + draft.paint(x: 1, y: 2) draft.endStroke() let pixels = draft.image appState.connectionManager.setTestState(connectionState: .disconnected, connectedDevice: .some(nil)) - #expect(controller.presentedViewController != nil) - #expect(draft.image == pixels) - try #require(await activate(L10n.Localizable.Common.done, in: try #require(controller.presentedViewController).view)) - try await waitUntil("Done should dismiss the editor") { controller.presentedViewController == nil } - #expect(draft.isStaged) + #expect(presentedController(in: window) != nil) #expect(draft.image == pixels) + try await waitUntil("Send disables when the connection drops") { + isEnabled(L10n.Chats.Chats.Mcoimg.send, in: window) == false + } + try #require(await activate(L10n.Localizable.Common.cancel, in: window)) + try await waitUntil("Cancel should dismiss the editor") { presentedController(in: window) == nil } + #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) + presentation.isPresented = true - try await waitUntil("Editor should reopen") { controller.presentedViewController != nil } - #expect(draft.image == pixels) - try #require(await activate(L10n.Localizable.Common.done, in: try #require(controller.presentedViewController).view)) - try await waitUntil("Done should dismiss the editor") { controller.presentedViewController == nil } - #expect(draft.image == pixels) + try await waitUntil("Editor should reopen") { presentedController(in: window) != nil } + #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) } - @Test func normalHardwareSendStagesImageWithoutClearingExistingText() async throws { + @Test func sendAdmitsOnceWithoutChangingTheTextDraft() async throws { let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) appState.connectionManager.setTestState(connectionState: .ready) - let model = InputModel() - let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) - let window = UIWindow(windowScene: scene) - window.rootViewController = UIHostingController(rootView: InputHarness(model: model).environment(\.appState, appState)) - window.makeKeyAndVisible() - defer { - window.isHidden = true - window.rootViewController = nil - window.windowScene = nil - appState.shutdown() + let draft = PixelPaintDraft() + draft.paint(x: 2, y: 3) + draft.endStroke() + let snapshot = draft.image + let model = SendModel() + let window = try host(SendHarness(draft: draft, model: model).environment(\.appState, appState)) + defer { release(window, appState: appState) } + + try await waitUntil("Harness should appear") { model.isReady } + model.isPresented = true + try await waitUntil("Editor should present") { presentedController(in: window) != nil } + let presented = try #require(presentedController(in: window)) + try #require(await activate(L10n.Chats.Chats.Mcoimg.send, in: window)) + try await waitUntil("Send should reach admission") { model.payloads.count == 1 } + #expect(draft.isAdmitting) + try await waitUntil("Cancel disables once admission starts") { + isEnabled(L10n.Localizable.Common.cancel, in: window) == false + } + // Clear is drawn in the SwiftUI hosting view, which does not expose a UIButton in this host. + // The button calls clear(), and that stays a no-op for the whole submission. + let pixelsDuringSend = draft.image + draft.clear() + #expect(draft.image == pixelsDuringSend) + #expect(hasActivityIndicator(in: window)) + #expect(isEnabled(L10n.Chats.Chats.Mcoimg.send, in: window) == false) + _ = await activate(L10n.Chats.Chats.Mcoimg.send, in: window) + #expect(model.payloads.count == 1) + #expect(model.text == SendModel.originalText) + model.pause.resume() + try await waitUntil("Admission should dismiss the editor") { presentedController(in: window) == nil } + #expect(model.payloads.count == 1) + #expect(model.text == SendModel.originalText) + #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) + #expect(draft.image != snapshot) + } + + @Test func rejectedAdmissionShowsOneCoverAlertAndKeepsPixels() async throws { + let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + appState.connectionManager.setTestState(connectionState: .ready) + let draft = PixelPaintDraft() + draft.paint(x: 4, y: 1) + draft.endStroke() + let snapshot = draft.image + let model = SendModel() + model.accept = false + let window = try host(SendHarness(draft: draft, model: model).environment(\.appState, appState)) + defer { release(window, appState: appState) } + + try await waitUntil { model.isReady } + model.isPresented = true + try await waitUntil("Editor should present") { presentedController(in: window) != nil } + let presented = try #require(presentedController(in: window)) + try #require(await activate(L10n.Chats.Chats.Mcoimg.send, in: window)) + try await waitUntil("Send should be waiting") { model.payloads.count == 1 } + model.pause.resume() + try await waitUntil("Cover should show the admission alert") { + alertTitled( + L10n.Chats.Chats.Alert.UnableToSend.title, + message: L10n.Chats.Chats.Alert.UnableToSend.message, + from: window.rootViewController + ) + } + #expect(presentedController(in: window) != nil) + #expect(model.sendErrorMessage == nil) + #expect(draft.image == snapshot) + #expect(model.text == SendModel.originalText) + } + + @Test func disconnectAfterTheTapShowsOneCoverAlertAndKeepsPixels() async throws { + let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + appState.connectionManager.setTestState(connectionState: .ready) + let draft = PixelPaintDraft() + draft.paint(x: 5, y: 6) + draft.endStroke() + let snapshot = draft.image + let model = SendModel() + let presentation = Presentation() + let pause = SubmissionPause() + let window = try host(Harness(draft: draft, presentation: presentation).environment(\.appState, appState)) + defer { release(window, appState: appState) } + try await waitUntil("Harness should appear") { presentation.isReady } + presentation.isPresented = true + try await waitUntil("Editor should present") { presentedController(in: window) != nil } + + guard let attempt = draft.begin(isReady: { appState.connectionState == .ready }) else { + Issue.record("Submission should start while connected") + return + } + let task = Task { + await draft.run( + attempt, + isChannel: false, + senderName: { "" }, + isReady: { appState.connectionState == .ready }, + onSend: { _ in + model.payloads.append("admitted") + return true + }, + onWillSend: {}, + onRejected: { model.sendErrorMessage = nil }, + onAdmitted: {}, + encode: { image, isChannel in + await pause.pause() + return try await encodePixelDrawing(image, channel: isChannel) + } + ) + } + draft.track(task) + await pause.untilPaused() + appState.connectionManager.setTestState(connectionState: .disconnected, connectedDevice: .some(nil)) + pause.resume() + await task.value + try await waitUntil("Cover should show the disconnect alert") { + alertTitled( + L10n.Chats.Chats.Alert.UnableToSend.title, + message: L10n.Chats.Chats.Alert.UnableToSend.message, + from: window.rootViewController + ) } + #expect(model.payloads.isEmpty) + #expect(model.sendErrorMessage == nil) + #expect(draft.image == snapshot) + #expect(presentedController(in: window) != nil) + } + + @Test func hardwareReturnSendsOnlyNonEmptyText() async throws { + let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + appState.connectionManager.setTestState(connectionState: .ready) + let model = InputModel() + model.text = String(repeating: "a", count: InputModel.maxBytes + 1) + let window = try host(InputHarness(model: model).environment(\.appState, appState)) + defer { release(window, appState: appState) } try await waitUntil { descendants(window).contains { $0 is ChatComposerUITextView } } let composer = try #require(descendants(window).compactMap { $0 as? ChatComposerUITextView }.first) + try await waitUntil("Over-limit text reaches the composer") { + composer.text.count == InputModel.maxBytes + 1 && composer.onSend != nil + } + + #expect(composer.onSend?() == false) + #expect(model.submissions.isEmpty) + #expect(model.text.count == InputModel.maxBytes + 1) + + model.text = " " + try await waitUntil("Whitespace reaches the composer") { composer.text == " " } + #expect(composer.onSend?() == false) + #expect(model.submissions.isEmpty) + #expect(model.text == " ") + + model.text = "Hello" + try await waitUntil("Text reaches the composer") { composer.text == "Hello" } #expect(composer.onSend?() == true) - #expect(model.imageSubmissions == 1) - #expect(model.textSubmissions == 0) - #expect(model.text == InputModel.originalText) - try await Task.sleep(for: .milliseconds(50)) + #expect(model.submissions == ["Hello"]) + #expect(model.text.isEmpty) #expect(composer.onSend?() == false) - #expect(model.imageSubmissions == 1) + #expect(model.submissions == ["Hello"]) } private struct Harness: View { @@ -93,11 +226,47 @@ struct PixelPaintPresentationTests { @Bindable var presentation: Presentation var body: some View { Color.clear - .fullScreenCover(isPresented: $presentation.isPresented) { PixelPaintEditor(draft: draft) } + .fullScreenCover(isPresented: $presentation.isPresented) { + PixelPaintEditor(draft: draft, onSend: {}) + } .onAppear { presentation.isReady = true } } } + private struct SendHarness: View { + @Bindable var draft: PixelPaintDraft + @Bindable var model: SendModel + var body: some View { + Text(model.text) + .fullScreenCover(isPresented: $model.isPresented) { + PixelPaintEditor(draft: draft) { + guard let attempt = draft.begin(isReady: { model.ready }) else { return } + let task = Task { + await draft.run( + attempt, + isChannel: false, + senderName: { "" }, + isReady: { model.ready }, + onSend: { text in + model.payloads.append(text) + await model.pause.pause() + if !model.accept { + model.sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + } + return model.accept + }, + onWillSend: {}, + onRejected: { model.sendErrorMessage = nil }, + onAdmitted: { model.isPresented = false } + ) + } + draft.track(task) + } + } + .onAppear { model.isReady = true } + } + } + @Observable @MainActor final class Presentation { @@ -107,55 +276,213 @@ struct PixelPaintPresentationTests { @Observable @MainActor - final class InputModel { - static let originalText = String(repeating: "Existing text ", count: 20) + final class SendModel { + static let originalText = "Existing text stays" var text = originalText - var imageSubmissions = 0 - var textSubmissions = 0 - var submitting = false + var isPresented = false + var isReady = false + var ready = true + var accept = true + var payloads: [String] = [] + var sendErrorMessage: String? + let pause = SubmissionPause() + } + + @Observable + @MainActor + final class InputModel { + static let maxBytes = 150 + var text = "" + var submissions: [String] = [] } private struct InputHarness: View { @Bindable var model: InputModel var body: some View { - ChatInputBar(text: $model.text, focusRequest: 0, placeholder: "Text", maxBytes: 150, - isEncrypted: true, leading: { EmptyView() }, - onSend: { _ in model.textSubmissions += 1 }, hasAttachment: true, - isSubmittingAttachment: model.submitting, onSendAttachment: { - model.submitting = true - model.imageSubmissions += 1 - }) + ChatInputBar( + text: $model.text, + focusRequest: 0, + placeholder: "Text", + maxBytes: InputModel.maxBytes, + isEncrypted: true, + leading: { EmptyView() }, + onSend: { model.submissions.append($0) } + ) } } - private func activate(_ identifier: String, in window: UIView) async -> Bool { + private func host(_ view: Content) throws -> UIWindow { + let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + let controller = UIHostingController(rootView: view) + window.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + window.rootViewController = controller + controller.view.frame = window.bounds + window.makeKeyAndVisible() + window.layoutIfNeeded() + return window + } + + private func release(_ window: UIWindow, appState: AppState) { + window.isHidden = true + window.rootViewController = nil + window.windowScene = nil + appState.shutdown() + } + + private func presentedController(in window: UIWindow) -> UIViewController? { + window.rootViewController?.presentedViewController + } + + private func activate(_ identifier: String, in root: NSObject) async -> Bool { for _ in 0..<100 { - window.layoutIfNeeded() - if let object = descendants(window).first(where: { $0.accessibilityLabel == identifier }) { + if let view = root as? UIView { view.layoutIfNeeded() } + if let object = matching(identifier, in: root) { if let button = object as? UIButton { - if button.allControlEvents.contains(.primaryActionTriggered) { button.performPrimaryAction() } else { button.sendActions(for: .touchUpInside) } + if button.allControlEvents.contains(.primaryActionTriggered) { + button.performPrimaryAction() + } else { + button.sendActions(for: .touchUpInside) + } + return true + } + if let control = object as? UIControl { + control.performPrimaryAction() return true } if object.accessibilityActivate() { return true } } try? await Task.sleep(for: .milliseconds(20)) } + Issue.record(AccessibilityDump(accessibilityDump(root))) return false } + private func matching(_ name: String, in root: NSObject) -> NSObject? { + if let labeled = labeledControl(named: name, in: root) { return labeled } + // A symbol-only bar button has no title until the accessibility tree is populated. + // Cancellation is the leading bar button and confirmation is the trailing one. + let buttons = barButtons(in: root) + guard buttons.count >= 2 else { return nil } + let direction = (root as? UIView)?.effectiveUserInterfaceLayoutDirection ?? .leftToRight + let leading = direction == .rightToLeft ? buttons.last : buttons.first + let trailing = direction == .rightToLeft ? buttons.first : buttons.last + if name == L10n.Localizable.Common.cancel { return leading } + if name == L10n.Chats.Chats.Mcoimg.send { return trailing } + return nil + } + + private func labeledControl(named name: String, in root: NSObject) -> NSObject? { + for object in descendants(root) { + let button = object as? UIButton + let texts = [ + object.accessibilityLabel, + button?.title(for: .normal), + button?.titleLabel?.text, + button?.titleLabel?.attributedText?.string, + button?.configuration?.title, + button?.configuration?.attributedTitle.map { String($0.characters) }, + (object as? UILabel)?.text, + (object as? UILabel)?.attributedText?.string, + (object as? UIAccessibilityIdentification)?.accessibilityIdentifier + ] + guard texts.contains(where: { $0 == name }) else { continue } + if object is UIControl { return object } + var view = object as? UIView + while let current = view { + if current is UIControl { return current } + view = current.superview + } + return object + } + return nil + } + + private func barButtons(in root: NSObject) -> [UIView] { + if let view = root as? UIView { view.layoutIfNeeded() } + return descendants(root).compactMap { object -> UIView? in + guard let view = object as? UIView else { return nil } + guard String(describing: type(of: view)).contains("ButtonBarButton") else { return nil } + return view + }.sorted { + $0.convert($0.bounds, to: nil).minX < $1.convert($1.bounds, to: nil).minX + } + } + + private func hasActivityIndicator(in root: NSObject) -> Bool { + descendants(root).contains { object in + let type = String(describing: type(of: object)) + return type.contains("ActivityIndicator") || type.contains("ProgressView") + } + } + + private func isEnabled(_ identifier: String, in root: NSObject) -> Bool? { + guard let object = matching(identifier, in: root) else { return nil } + if let control = object as? UIControl { return control.isEnabled } + return !object.accessibilityTraits.contains(.notEnabled) + } + + private func accessibilityDump(_ root: NSObject) -> String { + let objects = descendants(root) + let rows = objects.prefix(40).map { object -> String in + let label = object.accessibilityLabel ?? "" + let identifier = (object as? UIAccessibilityIdentification)?.accessibilityIdentifier ?? "" + let button = object as? UIButton + let title = button?.title(for: .normal) ?? button?.titleLabel?.text ?? button?.configuration?.title ?? "" + let labelText = (object as? UILabel)?.text ?? "" + return "\(type(of: object)) title=\(title) text=\(labelText) label=\(label) id=\(identifier)" + } + return "Count \(objects.count). \(rows.joined(separator: " | "))" + } + + private func contains(_ text: String, in window: UIWindow) -> Bool { + if alertMessage(text, from: window.rootViewController) { return true } + return descendants(window).contains { object in + if object.accessibilityLabel == text || object.accessibilityValue as? String == text { return true } + if let label = object as? UILabel { + return label.text == text || label.attributedText?.string == text + } + return false + } + } + + private func alertTitled(_ title: String, message: String, from controller: UIViewController?) -> Bool { + guard let controller else { return false } + if let alert = controller as? UIAlertController, alert.title == title, alert.message == message { + return true + } + if alertTitled(title, message: message, from: controller.presentedViewController) { return true } + return controller.children.contains { alertTitled(title, message: message, from: $0) } + } + + private func alertMessage(_ text: String, from controller: UIViewController?) -> Bool { + guard let controller else { return false } + if let alert = controller as? UIAlertController, alert.message == text { return true } + if alertMessage(text, from: controller.presentedViewController) { return true } + return controller.children.contains { alertMessage(text, from: $0) } + } + private func descendants(_ root: NSObject) -> [NSObject] { var seen: Set = [] var result: [NSObject] = [] func visit(_ object: NSObject) { guard seen.insert(ObjectIdentifier(object)).inserted else { return } result.append(object) - if let view = object as? UIView { view.subviews.forEach(visit) } let count = object.accessibilityElementCount() if count != NSNotFound, count > 0 { for index in 0.. Date: Mon, 16 Nov 2026 16:51:52 -0800 Subject: [PATCH 03/13] chore: stop tracking generated mcoimg dumps --- .gitignore | 2 + scripts/mcoimg/README.md | 156 +- scripts/mcoimg/fixtures/v3-swift-encoded.json | 2073 --- scripts/mcoimg/fixtures/v4-swift-raster.json | 13197 ---------------- 4 files changed, 21 insertions(+), 15407 deletions(-) delete mode 100644 scripts/mcoimg/fixtures/v3-swift-encoded.json delete mode 100644 scripts/mcoimg/fixtures/v4-swift-raster.json diff --git a/.gitignore b/.gitignore index 5857f8cae5..c31f703aeb 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,8 @@ scripts/ !/scripts/ /scripts/* !/scripts/mcoimg/ +/scripts/mcoimg/fixtures/v3-swift-encoded.json +/scripts/mcoimg/fixtures/v4-swift-raster.json !/scripts/test-app-ci.py !/scripts/tests/ /scripts/tests/* diff --git a/scripts/mcoimg/README.md b/scripts/mcoimg/README.md index e8520cec7e..8f592be6aa 100644 --- a/scripts/mcoimg/README.md +++ b/scripts/mcoimg/README.md @@ -6,9 +6,11 @@ model, MCOtxt generation-0 tables, and Flutter painter at that commit are the normative sources. The upstream code is GPL-3.0, as is MeshCore One. The Swift v3 decoder fixtures are copied from the upstream JavaScript fixture -exchange. `verify-v3.swift` runs every fixture and writes Swift encoder output. -The Swift encoder deliberately searches a smaller candidate set than Dart; -decoded pixels, rather than identical compressed bytes, establish compatibility. +exchange. `verify-v3.swift` runs every fixture and writes Swift encoder output +under `tmp/`. The v4 raster verifier writes its dump there too. Neither file +is checked in. The Swift encoder deliberately searches a smaller candidate set +than Dart. Decoded pixels, rather than identical compressed bytes, establish +compatibility. V4 has no published cross-runtime fixture exchange. Its fixture JSON records streams independently assembled by the later upstream command tests, decoded @@ -18,23 +20,6 @@ export command must accompany regenerated fixture evidence. Text and raster layers are compared as decoded values; platform fonts and antialiasing are client choices. -`measure_wire_cost_test.dart` measures v3 raster and v4 mixed encodings of the -same pixels. Copy it into the reference package's `test/helpers/` and run -`flutter test test/helpers/measure_wire_cost_test.dart` with -`MCOIMG_COST_OUTPUT` set to the desired JSON path. It includes the UTF-8 sender -envelope for GROUP_DATA and the complete Base91 wrappers and sender prefix for -text transport. A mixed raster still uses v3 internally. DMs send v3 text; -channels send only v4 mixed GROUP_DATA (`0x0120`, subtype/version `0x14`). -Channels never fall back to text, including on older firmware. A radio that -rejects GROUP_DATA follows the existing failed-send path. - -A new image Send uses a fresh nonce before measuring its destination envelope. -Send Again refreshes and persists the prepared content before queue capture. -Automatic retries retain the nonce, matching the tagged client's -`_preparedOutboundTexts` and deferred `binaryOutbound` behavior. DM ACK prediction -uses its exact text. Binary channel images have no sender timestamp and do not -enter the text reaction index. - To reproduce v3 verification from the MeshCore One worktree: ```sh @@ -48,7 +33,7 @@ swiftc -parse-as-library -module-cache-path tmp/mcoimg-module-cache \ MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodecError.swift \ scripts/mcoimg/verify-v3.swift -o tmp/mcoimg-v3-verify tmp/mcoimg-v3-verify scripts/mcoimg/fixtures/v3-upstream-decoder.json \ - scripts/mcoimg/fixtures/v3-swift-encoded.json + tmp/mcoimg-v3-swift-encoded.json ``` This checks all 39 upstream fixtures and generates 73 Swift bodies: those same @@ -61,7 +46,7 @@ From the tagged upstream Flutter package, run the independent verifier using absolute paths to this worktree: ```sh -MCOIMG_FIXTURES=/absolute/worktree/scripts/mcoimg/fixtures/v3-swift-encoded.json \ +MCOIMG_FIXTURES=/absolute/worktree/tmp/mcoimg-v3-swift-encoded.json \ flutter test --no-pub /absolute/worktree/scripts/mcoimg/verify-v3.dart ``` @@ -79,13 +64,21 @@ invalid color references, nonce changes, and exact palette anchors. `verify-v4-raster.swift` wraps all 73 Swift v3 fixtures and seven dimension-mode boundaries as v4 mixed documents. It checks Swift decode equality and writes -`fixtures/v4-swift-raster.json`. Build it with the same v3 sources above plus -`MCOImageV4*.swift`, `MCOImageCodec.swift`, `MCOImageContent.swift`, -`MCOImageFigure.swift`, and `MCOText*.swift`, substituting the verifier filename. +the JSON path given as its second argument. Build it with the same v3 sources +above plus `MCOImageV4*.swift`, `MCOImageCodec.swift`, `MCOImageContent.swift`, +`MCOImageFigure.swift`, and `MCOText*.swift`, and pass +`-o tmp/mcoimg-v4-raster-verify`. The input is the v3 file written above. +Both files stay under `tmp/`. + +```sh +tmp/mcoimg-v4-raster-verify tmp/mcoimg-v3-swift-encoded.json \ + tmp/mcoimg-v4-swift-raster.json +``` + Then run the unchanged tagged Dart codec from its Flutter package: ```sh -MCOIMG_FIXTURES=/absolute/worktree/scripts/mcoimg/fixtures/v4-swift-raster.json \ +MCOIMG_FIXTURES=/absolute/worktree/tmp/mcoimg-v4-swift-raster.json \ flutter test --no-pub /absolute/worktree/scripts/mcoimg/verify-v4-raster.dart ``` @@ -96,114 +89,3 @@ the tagged encoder's canonical bytes. These are locally generated cross-runtime checks, not a published upstream v4 fixture exchange. The wrapper retains Swift's selected v3 compression; it does not claim the Dart optimizer would choose identical compressed bytes. - -## Scope and retained state - -DMs and channels render v3 and v4 text. Channels also receive the registered -`0x0120` binary envelope, including during initial sync. Rooms render both text -versions through the shared renderer; their separate composer has no paint -entry. Outgoing DM drawings use v3 text; channel drawings use v4 mixed binary -GROUP_DATA. Both retain the existing service-owned queue and stored text content. -The channel `im4:` value is an internal persistence representation; it is never -sent as channel text. No queue or persisted payload field was added. Legacy v3 -queued channel images are deterministically wrapped as v4 at transmission, -preserving their compressed raster bytes and nonce. User retry upgrades and -persists v4 before capturing its queue envelope. - -The fixed 16×16 Master 8 editor supports painting and erasing with palette -colors. Send on the cover admits the current pixels. Cancel discards them. -Neither changes composer text. The conversation input owns unsent pixels in -memory until admission, cancellation, or conversation closure; closing the app -also discards those pixels. Encoding runs off the main actor from an immutable -snapshot. Painting and Clear do nothing during admission, and Cancel stays -enabled until admission begins. Disconnection and encoding or admission failure -keep the pixels on the cover. Closing the conversation retires the drawing -before admission. After a successful admission, the service queue owns the send -and continues after the cover closes. Existing text remains a separate Draft. - -V4 rendering clips overscan geometry, preserves paint order, uses cell-center -vector anchors and cell-edge raster origins, non-zero fills, square stroke caps, -miter joins with the reference painter's limit, and circular dots. Open paths -close for fill only. Text uses system fonts and client line metrics, which are -not specified as pixel-identical across platforms. Raster-only v4 mode and -unknown extensions show the unsupported placeholder; damaged documents show -the damaged placeholder without partially painting. - -V4 capability limits are 4,096 expanded figures and 64 nested groups. Limits -are checked before allocating repeat expansion, including zero-delta runs; -exceeding them is unsupported, rather than damaged. - -## Measured cost and validation - -The tagged Dart encoders measured the same 16×16 cross (nonce 42) as follows. -The sender is `Radio` (5 UTF-8 bytes). Values include all application envelopes. - -| Representation | V3 raster | V4 mixed | -| --- | ---: | ---: | -| Body | 28 | 34 | -| Binary channel application payload | 35 | 41 | -| Binary flood host command | 40 | 46 | -| Complete text wrapper | 40 | 46 | -| Channel text including `Radio: ` | 47 | 53 | -| Channel text host command | 47 | 53 | -| DM text host command | 53 | 59 | - -The binary app budget is 165 bytes. The text budget is 150 UTF-8 bytes for a -DM, and `139 - senderNameUTF8Bytes - 2` for a channel (132 for `Radio`, 128 for -`救援隊`). The editor measures the final random-nonce v3 text for a DM, or the -complete v4 binary sender envelope for a channel. The service revalidates the -current sender name at drain. A stored Base91 string can exceed the channel -text budget while its binary envelope fits. V4 mixed adds document fields around -the compressed v3 raster; v4 raster-only mode remains reserved. V3 is the smaller -DM pixel format; channels use v4 binary so clients without MCOimg do not display -encoded text. -Host command sizes include command/header fields and the binary data type; -RF routing, encryption padding and airtime vary with the actual radio path. - -On 2026-10-26: - -- All 39 published upstream v3 decoder fixtures matched exactly. -- Tagged Dart independently decoded 73 Swift-generated images through body, - app payload and text paths, including every palette profile and nonce variants. -- Swift matched 126 v4 tagged-decoder document/error fixtures and 17 MCOtxt - vectors covering the seven frozen generation-0 language tables. The independent - command assembly's canonical encoder assertions also passed under tagged Dart. -- 2,370 MC1Services tests passed serially after the binary channel change, - including backup, receive, send queue, pool backoff, retry and disconnect suites. -- All 538 MeshCore tests passed, including text/binary scope serialization and - cancellation/ACK ordering. -- Tagged Dart independently decoded 80 Swift v4 mixed rasters. Seven white-raster - dimension cases matched its canonical encoder bytes exactly. -- 65 focused app regressions passed after the binary change on iPhone 17e/iOS - 27.0. Presentation coverage is the full-screen cover, the dismissal guard, - Cancel discarding pixels, Send admitting once, one cover alert when admission - fails, and hardware Return sending only typed text. -- SwiftLint and whitespace checks passed. SwiftGen was regenerated and stable. - The final simulator build passed with three warnings in unchanged concurrency - code (`MessageBubbleSecondaryClick` and `MessagePathPreviewSnapshot`). - -The normal pinned simulator was occupied by another chat, so app verification -used an isolated iPhone 17e on the same iOS 27.0 runtime. No physical-radio -exchange or published v4 cross-runtime fixture set was available. New strings -use L10n in all twelve locales; non-English additions are marked English -translation placeholders, following the repository localization workflow. - -## Binary channel change preflight - -| Check | Result | -| --- | --- | -| SwiftLint | Passed, zero violations | -| Project generation | `make test-app` regenerated the project; project.yml unchanged | -| SwiftGen | Regenerated, output unchanged | -| UI copy and state naming | No new strings; L10n and errorMessage retained | -| Persistence/backup | No stored-field or DTO schema changes; full backup suite passed | -| Build | iPhone 17e/iOS 27.0 passed; three pre-existing concurrency warnings | -| Whitespace | `git diff --check` passed | - -Binary tests cover inline/pending/resend, legacy v3 replay across disconnect, -TABLE_FULL backoff and durable replay, stable automatic nonces, prepared user -resends, malformed/unsupported rejection without text fallback, and UTF-8 -165/166-byte boundaries at admission and drain. The two presentation tests passed -on the isolated simulator after its accessibility service was initialized with -MobileBuildMCP `snapshot_ui`; an inactive service returns an empty in-process -SwiftUI accessibility tree. No physical-radio exchange was available. diff --git a/scripts/mcoimg/fixtures/v3-swift-encoded.json b/scripts/mcoimg/fixtures/v3-swift-encoded.json deleted file mode 100644 index a8b74dbcf5..0000000000 --- a/scripts/mcoimg/fixtures/v3-swift-encoded.json +++ /dev/null @@ -1,2073 +0,0 @@ -{ - "fixtures" : [ - { - "appPayloadBase64" : "E3oBjQBCvgE=", - "bodyBase64" : "egGNAEK+AQ==", - "height" : 2, - "name" : "swift-rawGlobal", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 1, - 2, - 3, - 3, - 2, - 1, - 0 - ], - "text" : "im3:g\/5WjAL`NA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3ohjVAg1g==", - "bodyBase64" : "eiGNUCDW", - "height" : 2, - "name" : "swift-rawLocal", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 0, - 3, - 3, - 0, - 3, - 0 - ], - "text" : "im3:g\/oZ74qiN", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3ohjVAgxg==", - "bodyBase64" : "eiGNUCDG", - "height" : 2, - "name" : "swift-compactRle", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 0, - 0, - 3, - 3, - 0, - 0, - 0 - ], - "text" : "im3:g\/oZ74qiM", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oBjQDCwwA=", - "bodyBase64" : "egGNAMLDAA==", - "height" : 2, - "name" : "swift-compactSparse", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 3, - 0, - 0, - 3, - 0, - 0 - ], - "text" : "im3:g\/5WjA0KGA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3ohjVAg1g==", - "bodyBase64" : "eiGNUCDW", - "height" : 2, - "name" : "swift-biColorMask", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 0, - 3, - 3, - 0, - 3, - 0 - ], - "text" : "im3:g\/oZ74qiN", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oBjVAg1g==", - "bodyBase64" : "egGNUCDW", - "height" : 2, - "name" : "swift-rowRepeat", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 0, - 3, - 0, - 3, - 0, - 3 - ], - "text" : "im3:g\/5W74qiN", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oBjVAg1g==", - "bodyBase64" : "egGNUCDW", - "height" : 2, - "name" : "swift-lzPixels", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 0, - 3, - 0, - 3, - 0, - 3 - ], - "text" : "im3:g\/5W74qiN", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oBBCA8", - "bodyBase64" : "egEEIDw=", - "height" : 2, - "name" : "swift-quadtree", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 3, - 0 - ], - "text" : "im3:g\/N\"XL8A", - "transparentColor" : null, - "width" : 2 - }, - { - "appPayloadBase64" : "E3oBjQBC5A4=", - "bodyBase64" : "egGNAELkDg==", - "height" : 2, - "name" : "swift-bitplanesRawAndRle", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 1, - 0, - 1, - 2, - 3, - 2, - 3 - ], - "text" : "im3:g\/5WjA~LcB", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3ohjVAg1g==", - "bodyBase64" : "eiGNUCDW", - "height" : 2, - "name" : "swift-adaptiveBitplanesRaw", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 0, - 3, - 3, - 0, - 3, - 0 - ], - "text" : "im3:g\/oZ74qiN", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oIjQCCaKwP", - "bodyBase64" : "egiNAIJorA8=", - "height" : 2, - "name" : "swift-directBitplanes", - "paletteProfile" : "grayscale8", - "pixels" : [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7 - ], - "text" : "im3:g\/WXjA`X9]D", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oBjVAg1g==", - "bodyBase64" : "egGNUCDW", - "height" : 2, - "name" : "swift-compactRowDelta", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 0, - 3, - 0, - 3, - 0, - 3 - ], - "text" : "im3:g\/5W74qiN", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oIjQCCaIgG", - "bodyBase64" : "egiNAIJoiAY=", - "height" : 2, - "name" : "swift-directRowDelta", - "paletteProfile" : "grayscale8", - "pixels" : [ - 0, - 1, - 2, - 3, - 0, - 1, - 2, - 3 - ], - "text" : "im3:g\/WXjA`XA5B", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oBjVAg1g==", - "bodyBase64" : "egGNUCDW", - "height" : 2, - "name" : "swift-rowDelta", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 0, - 3, - 0, - 3, - 0, - 3 - ], - "text" : "im3:g\/5W74qiN", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3ohjVAgxg==", - "bodyBase64" : "eiGNUCDG", - "height" : 2, - "name" : "swift-varUintRle", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 0, - 0, - 3, - 3, - 0, - 0, - 0 - ], - "text" : "im3:g\/oZ74qiM", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oBjQDCwwA=", - "bodyBase64" : "egGNAMLDAA==", - "height" : 2, - "name" : "swift-varUintSparse", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 3, - 0, - 0, - 3, - 0, - 0 - ], - "text" : "im3:g\/5WjA0KGA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3pBHRDGMQ==", - "bodyBase64" : "ekEdEMYx", - "height" : 1, - "name" : "swift-adaptiveLegacyRle", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 0, - 0, - 0, - 3, - 3, - 3, - 3 - ], - "text" : "im3:g\/XceL~JD", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "E3pBHQAm\/Q==", - "bodyBase64" : "ekEdACb9", - "height" : 1, - "name" : "swift-adaptiveShortRle", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 0, - 3, - 3, - 3, - 0, - 0, - 0 - ], - "text" : "im3:g\/XcHAA]H", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "E3pBHQAM", - "bodyBase64" : "ekEdAAw=", - "height" : 1, - "name" : "swift-adaptiveConstantZero", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "text" : "im3:g\/XcHAMA", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "E3oBHTAM", - "bodyBase64" : "egEdMAw=", - "height" : 1, - "name" : "swift-adaptiveConstantOne", - "paletteProfile" : "master4", - "pixels" : [ - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3 - ], - "text" : "im3:g\/5WXDASAwD>W", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E3oPDQASLFm0ZA==", - "bodyBase64" : "eg8NABIsWbRk", - "height" : 1, - "name" : "swift-paletteOrderedSingleBank", - "paletteProfile" : "dynamicGlobal512", - "pixels" : [ - 193, - 201, - 209, - 201 - ], - "text" : "im3:g\/>XDA|hXDASAOJTX", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwBCPGUzmYRZVVUJAGBCFXgCAJiqqgI=", - "bodyBase64" : "AEI8ZTOZhFlVVQkAYEIVeAIAmKqqAg==", - "height" : 16, - "name" : "swift-painted16", - "paletteProfile" : "master8", - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 3, - 3, - 3, - 3, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 3, - 3, - 3, - 3, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 3, - 3, - 3, - 3, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 3, - 3, - 3, - 3, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "text" : "im3:TA^v2j[+OiC8u0AA!urtnA@QB8qA", - "transparentColor" : null, - "width" : 16 - }, - { - "appPayloadBase64" : "E\/8FPCBAJM5EZd5Ipu5M5\/7dG0zlnWztH431ka16A85Gxv5SiS9eTFzX+k\/n\/oz38s3H9g504s1IJx9cbGxwob3R2U\/pX63B1Q7ZW2xuwc1KiD9mT61CBh\/LuE\/rsM3LuE\/rsM1ooM1M6V9wIu5Ua3zFl0\/tEe7Vm4z9FS9ij81OSnx6BS9mwN3\/dk\/vcg7ffs3Peoxcbs1Qq5xE6G94JT\/5VU\/x0y7pUQ7h3+1WTc1SDL1Oy6xKipzzNE\/zNE\/zNE\/zNE8=", - "bodyBase64" : "\/wU8IEAkzkRl3kim7kzn\/t0bTOWdbO0fjfWRrXoDzkbG\/lKJL15MXNf6T+f+jPfyzcf2DnTizUgnH1xsbHChvdHZT+lfrcHVDtlbbG7BzUqIP2ZPrUIGH8u4T+uwzcu4T+uwzWigzUzpX3Ai7lRrfMWXT+0R7tWbjP0VL2KPzU5KfHoFL2bA3f92T+9yDt9+zc96jFxuzVCrnETob3glP\/lVT\/HTLulRDuHf7VZNzVIMvU7LrEqKnPM0T\/M0T\/M0T\/M0Tw==", - "height" : 16, - "name" : "swift-dense16", - "paletteProfile" : "master64", - "pixels" : [ - 0, - 17, - 34, - 51, - 4, - 21, - 38, - 55, - 8, - 25, - 42, - 59, - 12, - 29, - 46, - 63, - 29, - 47, - 1, - 19, - 37, - 55, - 9, - 27, - 45, - 63, - 17, - 35, - 53, - 7, - 25, - 43, - 58, - 13, - 32, - 51, - 6, - 25, - 44, - 63, - 18, - 37, - 56, - 11, - 30, - 49, - 4, - 23, - 23, - 43, - 63, - 19, - 39, - 59, - 15, - 35, - 55, - 11, - 31, - 51, - 7, - 27, - 47, - 3, - 52, - 9, - 30, - 51, - 8, - 29, - 50, - 7, - 28, - 49, - 6, - 27, - 48, - 5, - 26, - 47, - 17, - 39, - 61, - 19, - 41, - 63, - 21, - 43, - 1, - 23, - 45, - 3, - 25, - 47, - 5, - 27, - 46, - 5, - 28, - 51, - 10, - 33, - 56, - 15, - 38, - 61, - 20, - 43, - 2, - 25, - 48, - 7, - 11, - 35, - 59, - 19, - 43, - 3, - 27, - 51, - 11, - 35, - 59, - 19, - 43, - 3, - 27, - 51, - 40, - 1, - 26, - 51, - 12, - 37, - 62, - 23, - 48, - 9, - 34, - 59, - 20, - 45, - 6, - 31, - 5, - 31, - 57, - 19, - 45, - 7, - 33, - 59, - 21, - 47, - 9, - 35, - 61, - 23, - 49, - 11, - 34, - 61, - 24, - 51, - 14, - 41, - 4, - 31, - 58, - 21, - 48, - 11, - 38, - 1, - 28, - 55, - 63, - 27, - 55, - 19, - 47, - 11, - 39, - 3, - 31, - 59, - 23, - 51, - 15, - 43, - 7, - 35, - 28, - 57, - 22, - 51, - 16, - 45, - 10, - 39, - 4, - 33, - 62, - 27, - 56, - 21, - 50, - 15, - 57, - 23, - 53, - 19, - 49, - 15, - 45, - 11, - 41, - 7, - 37, - 3, - 33, - 63, - 29, - 59, - 22, - 53, - 20, - 51, - 18, - 49, - 16, - 47, - 14, - 45, - 12, - 43, - 10, - 41, - 8, - 39, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19 - ], - "text" : "im3:m|x\"eL|LLSU,[xVdRS!=F>Fi8qj<3~:*XZMeUBNTo!h6l|yQ\/n}fLc`{]?=@]rjrU\/T&2Z6|IIXck*O&h%E\/#5!w*m$fTaDfWdrW8kE0!t=^8D$8,Us!U62bCOkI6TEKM@6nJ?w&|&{.$Orox>9Nx:Ka^FNY]A?_j#^t(@3uQyvn}.|Qrc@Sg;4Z,FMj(y9SW:9rdD78zkOtuJ&zemlZH`q4#ierO6o4Sd2P.I[y`+qjVB", - "transparentColor" : null, - "width" : 16 - }, - { - "appPayloadBase64" : "EwAADQGipQ==", - "bodyBase64" : "AAANAaKl", - "height" : 3, - "name" : "swift-profile-0-nonce-0", - "paletteProfile" : "mono", - "pixels" : [ - 0, - 1, - 0, - 1, - 1, - 0, - 1, - 0, - 0, - 1, - 0, - 1 - ], - "text" : "im3:TAY4hA`0C", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8ADQGipQ==", - "bodyBase64" : "\/wANAaKl", - "height" : 3, - "name" : "swift-profile-0-nonce-255", - "paletteProfile" : "mono", - "pixels" : [ - 0, - 1, - 0, - 1, - 1, - 0, - 1, - 0, - 0, - 1, - 0, - 1 - ], - "text" : "im3:m|1W(A=PF", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwABDQHCFmsM", - "bodyBase64" : "AAENAcIWaww=", - "height" : 3, - "name" : "swift-profile-1-nonce-0", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 2, - 1, - 1, - 0, - 3, - 2, - 2, - 1, - 0, - 3 - ], - "text" : "im3:TAc4hABg%xB", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8BDQHCFmsM", - "bodyBase64" : "\/wENAcIWaww=", - "height" : 3, - "name" : "swift-profile-1-nonce-255", - "paletteProfile" : "master4", - "pixels" : [ - 0, - 3, - 2, - 1, - 1, - 0, - 3, - 2, - 2, - 1, - 0, - 3 - ], - "text" : "im3:m|9W(AC$lJD", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwACDQGCu+Wk4A==", - "bodyBase64" : "AAINAYK75aTg", - "height" : 3, - "name" : "swift-profile-2-nonce-0", - "paletteProfile" : "master8", - "pixels" : [ - 0, - 7, - 6, - 5, - 5, - 4, - 3, - 2, - 2, - 1, - 0, - 7 - ], - "text" : "im3:TAg4hA$^J3\">", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8CDQGCu+Wk4A==", - "bodyBase64" : "\/wINAYK75aTg", - "height" : 3, - "name" : "swift-profile-2-nonce-255", - "paletteProfile" : "master8", - "pixels" : [ - 0, - 7, - 6, - 5, - 5, - 4, - 3, - 2, - 2, - 1, - 0, - 7 - ], - "text" : "im3:m|*W(Aj=RU}(B", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwADDQEC59W0ooEP", - "bodyBase64" : "AAMNAQLn1bSigQ8=", - "height" : 3, - "name" : "swift-profile-3-nonce-0", - "paletteProfile" : "master16", - "pixels" : [ - 0, - 7, - 14, - 5, - 13, - 4, - 11, - 2, - 10, - 1, - 8, - 15 - ], - "text" : "im3:TAk4hA?2l2T54rA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8DDQEC59W0ooEP", - "bodyBase64" : "\/wMNAQLn1bSigQ8=", - "height" : 3, - "name" : "swift-profile-3-nonce-255", - "paletteProfile" : "master16", - "pixels" : [ - 0, - 7, - 14, - 5, - 13, - 4, - 11, - 2, - 10, - 1, - 8, - 15 - ], - "text" : "im3:m|=W(A%T\/SlYW|A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAEDQECjqudLKkDeg==", - "bodyBase64" : "AAQNAQKOq50sqQN6", - "height" : 3, - "name" : "swift-profile-4-nonce-0", - "paletteProfile" : "master32", - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 4, - 11, - 18, - 26, - 1, - 8, - 15 - ], - "text" : "im3:TAo4hA$T\/#!PbK&K", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8EDQECjqudLKkDeg==", - "bodyBase64" : "\/wQNAQKOq50sqQN6", - "height" : 3, - "name" : "swift-profile-4-nonce-255", - "paletteProfile" : "master32", - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 4, - 11, - 18, - 26, - 1, - 8, - 15 - ], - "text" : "im3:m|`W(Aln1lif2UpV", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAFDQECHE7VkausB8gD", - "bodyBase64" : "AAUNAQIcTtWRq6wHyAM=", - "height" : 3, - "name" : "swift-profile-5-nonce-0", - "paletteProfile" : "master64", - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 36, - 43, - 50, - 58, - 1, - 8, - 15 - ], - "text" : "im3:TAs4hAkn#7Zz6j9AeB", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8FDQECHE7VkausB8gD", - "bodyBase64" : "\/wUNAQIcTtWRq6wHyAM=", - "height" : 3, - "name" : "swift-profile-5-nonce-255", - "paletteProfile" : "master64", - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 36, - 43, - 50, - 58, - 1, - 8, - 15 - ], - "text" : "im3:m|CX(A.>hdxMa,fBdFA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAGDQEC59W0ooEP", - "bodyBase64" : "AAYNAQLn1bSigQ8=", - "height" : 3, - "name" : "swift-profile-6-nonce-0", - "paletteProfile" : "grayscale16", - "pixels" : [ - 0, - 7, - 14, - 5, - 13, - 4, - 11, - 2, - 10, - 1, - 8, - 15 - ], - "text" : "im3:TAw4hA?2l2T54rA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8GDQEC59W0ooEP", - "bodyBase64" : "\/wYNAQLn1bSigQ8=", - "height" : 3, - "name" : "swift-profile-6-nonce-255", - "paletteProfile" : "grayscale16", - "pixels" : [ - 0, - 7, - 14, - 5, - 13, - 4, - 11, - 2, - 10, - 1, - 8, - 15 - ], - "text" : "im3:m|KX(A%T\/SlYW|A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAHDQECjqudLKkDeg==", - "bodyBase64" : "AAcNAQKOq50sqQN6", - "height" : 3, - "name" : "swift-profile-7-nonce-0", - "paletteProfile" : "grayscale32", - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 4, - 11, - 18, - 26, - 1, - 8, - 15 - ], - "text" : "im3:TA04hA$T\/#!PbK&K", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8HDQECjqudLKkDeg==", - "bodyBase64" : "\/wcNAQKOq50sqQN6", - "height" : 3, - "name" : "swift-profile-7-nonce-255", - "paletteProfile" : "grayscale32", - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 4, - 11, - 18, - 26, - 1, - 8, - 15 - ], - "text" : "im3:m|SX(Aln1lif2UpV", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAIDQGCu+Wk4A==", - "bodyBase64" : "AAgNAYK75aTg", - "height" : 3, - "name" : "swift-profile-8-nonce-0", - "paletteProfile" : "grayscale8", - "pixels" : [ - 0, - 7, - 6, - 5, - 5, - 4, - 3, - 2, - 2, - 1, - 0, - 7 - ], - "text" : "im3:TA44hA$^J3\">", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8IDQGCu+Wk4A==", - "bodyBase64" : "\/wgNAYK75aTg", - "height" : 3, - "name" : "swift-profile-8-nonce-255", - "paletteProfile" : "grayscale8", - "pixels" : [ - 0, - 7, - 6, - 5, - 5, - 4, - 3, - 2, - 2, - 1, - 0, - 7 - ], - "text" : "im3:m|aX(Aj=RU}(B", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAJDQGCu+Wk4A==", - "bodyBase64" : "AAkNAYK75aTg", - "height" : 3, - "name" : "swift-profile-9-nonce-0", - "paletteProfile" : "dynamicGlobal8", - "pixels" : [ - 0, - 484, - 401, - 283, - 283, - 210, - 91, - 63, - 63, - 83, - 0, - 484 - ], - "text" : "im3:TA84hA$^J3\">", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8JDQGCu+Wk4A==", - "bodyBase64" : "\/wkNAYK75aTg", - "height" : 3, - "name" : "swift-profile-9-nonce-255", - "paletteProfile" : "dynamicGlobal8", - "pixels" : [ - 0, - 484, - 401, - 283, - 283, - 210, - 91, - 63, - 63, - 83, - 0, - 484 - ], - "text" : "im3:m|iX(Aj=RU}(B", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAKDQEC59W0ooEP", - "bodyBase64" : "AAoNAQLn1bSigQ8=", - "height" : 3, - "name" : "swift-profile-10-nonce-0", - "paletteProfile" : "dynamicGlobal16", - "pixels" : [ - 0, - 210, - 492, - 155, - 447, - 118, - 338, - 63, - 310, - 84, - 246, - 511 - ], - "text" : "im3:TA$4hA?2l2T54rA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8KDQEC59W0ooEP", - "bodyBase64" : "\/woNAQLn1bSigQ8=", - "height" : 3, - "name" : "swift-profile-10-nonce-255", - "paletteProfile" : "dynamicGlobal16", - "pixels" : [ - 0, - 210, - 492, - 155, - 447, - 118, - 338, - 63, - 310, - 84, - 246, - 511 - ], - "text" : "im3:m|qX(A%T\/SlYW|A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwALDQECjqudLKkDeg==", - "bodyBase64" : "AAsNAQKOq50sqQN6", - "height" : 3, - "name" : "swift-profile-11-nonce-0", - "paletteProfile" : "dynamicGlobal32", - "pixels" : [ - 0, - 118, - 237, - 347, - 457, - 64, - 182, - 310, - 429, - 18, - 128, - 255 - ], - "text" : "im3:TA)4hA$T\/#!PbK&K", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8LDQECjqudLKkDeg==", - "bodyBase64" : "\/wsNAQKOq50sqQN6", - "height" : 3, - "name" : "swift-profile-11-nonce-255", - "paletteProfile" : "dynamicGlobal32", - "pixels" : [ - 0, - 118, - 237, - 347, - 457, - 64, - 182, - 310, - 429, - 18, - 128, - 255 - ], - "text" : "im3:m|yX(Aln1lif2UpV", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAMDQECHE7VkausB8gD", - "bodyBase64" : "AAwNAQIcTtWRq6wHyAM=", - "height" : 3, - "name" : "swift-profile-12-nonce-0", - "paletteProfile" : "dynamicGlobal64", - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 9, - 64, - 127 - ], - "text" : "im3:TA.4hAkn#7Zz6j9AeB", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8MDQECHE7VkausB8gD", - "bodyBase64" : "\/wwNAQIcTtWRq6wHyAM=", - "height" : 3, - "name" : "swift-profile-12-nonce-255", - "paletteProfile" : "dynamicGlobal64", - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 9, - 64, - 127 - ], - "text" : "im3:m|6X(A.>hdxMa,fBdFA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwANDQECODgqHdJKpgsinw==", - "bodyBase64" : "AA0NAQI4OCod0kqmCyKf", - "height" : 3, - "name" : "swift-profile-13-nonce-0", - "paletteProfile" : "dynamicGlobal128", - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 2, - 10, - 17 - ], - "text" : "im3:TA<4hA,>}YXKoeM]`XtD", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8NDQECODgqHdJKpgsinw==", - "bodyBase64" : "\/w0NAQI4OCod0kqmCyKf", - "height" : 3, - "name" : "swift-profile-13-nonce-255", - "paletteProfile" : "dynamicGlobal128", - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 2, - 10, - 17 - ], - "text" : "im3:m|&X(Ax({xuU@8W:@v\"G", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAODQECcOBQ0UGyIqMThPQE", - "bodyBase64" : "AA4NAQJw4FDRQbIioxOE9AQ=", - "height" : 3, - "name" : "swift-profile-14-nonce-0", - "paletteProfile" : "dynamicGlobal256", - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 2, - 10, - 17 - ], - "text" : "im3:TA@4hAw(>J3\/gzz+\/NlZ?A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8ODQECcOBQ0UGyIqMThPQE", - "bodyBase64" : "\/w4NAQJw4FDRQbIioxOE9AQ=", - "height" : 3, - "name" : "swift-profile-14-nonce-255", - "paletteProfile" : "dynamicGlobal256", - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 2, - 10, - 17 - ], - "text" : "im3:m|:X(ADt&TR5#MKz4b:y(B", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "EwAPDQEC4ICDCh1IrJChIwiSJw==", - "bodyBase64" : "AA8NAQLggIMKHUiskKEjCJIn", - "height" : 3, - "name" : "swift-profile-15-nonce-0", - "paletteProfile" : "dynamicGlobal512", - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 36, - 43, - 50, - 58, - 65, - 72, - 79 - ], - "text" : "im3:TA_4hACtmn#D;WNP3X.t!+T", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "E\/8PDQEC4ICDCh1IrJChIwiSJw==", - "bodyBase64" : "\/w8NAQLggIMKHUiskKEjCJIn", - "height" : 3, - "name" : "swift-profile-15-nonce-255", - "paletteProfile" : "dynamicGlobal512", - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 36, - 43, - 50, - 58, - 65, - 72, - 79 - ], - "text" : "im3:m|]X(AE\"mn#D;WNP3X.t!+T", - "transparentColor" : null, - "width" : 4 - } - ], - "generator" : "scripts\/mcoimg\/verify-v3.swift", - "schema" : 1 -} \ No newline at end of file diff --git a/scripts/mcoimg/fixtures/v4-swift-raster.json b/scripts/mcoimg/fixtures/v4-swift-raster.json deleted file mode 100644 index 3e6c2b39fd..0000000000 --- a/scripts/mcoimg/fixtures/v4-swift-raster.json +++ /dev/null @@ -1,13197 +0,0 @@ -{ - "fixtures" : [ - { - "appPayloadBase64" : "FHpFI3hPUDQCCPkGAA==", - "bodyBase64" : "ekUjeE9QNAII+QYA", - "height" : 2, - "name" : "swift-rawGlobal", - "nonce" : 122, - "pixels" : [ - 0, - 1, - 2, - 3, - 3, - 2, - 1, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNAEK+AQ==", - "text" : "im4:lPJD[3YYjAL`NAA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEjRCgVgD", - "bodyBase64" : "ekUjeE8SNEKBWAM=", - "height" : 2, - "name" : "swift-rawLocal", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 3, - 3, - 0, - 3, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "eiGNUCDW", - "text" : "im4:lPJD[3]W74qiNA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEjRCgRgD", - "bodyBase64" : "ekUjeE8SNEKBGAM=", - "height" : 2, - "name" : "swift-compactRle", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 3, - 3, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "eiGNUCDG", - "text" : "im4:lPJD[3]W74qiMA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPUDQCCA8DAA==", - "bodyBase64" : "ekUjeE9QNAIIDwMA", - "height" : 2, - "name" : "swift-compactSparse", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 3, - 0, - 0, - 3, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNAMLDAA==", - "text" : "im4:lPJD[3YYjA0KGAA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEjRCgVgD", - "bodyBase64" : "ekUjeE8SNEKBWAM=", - "height" : 2, - "name" : "swift-biColorMask", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 3, - 3, - 0, - 3, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "eiGNUCDW", - "text" : "im4:lPJD[3]W74qiNA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEDRCgVgD", - "bodyBase64" : "ekUjeE8QNEKBWAM=", - "height" : 2, - "name" : "swift-rowRepeat", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 3, - 0, - 3, - 0, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNUCDW", - "text" : "im4:lPJD[3>W74qiNA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEDRCgVgD", - "bodyBase64" : "ekUjeE8QNEKBWAM=", - "height" : 2, - "name" : "swift-lzPixels", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 3, - 0, - 3, - 0, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNUCDW", - "text" : "im4:lPJD[3>W74qiNA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHoFgfcCE4DwAA==", - "bodyBase64" : "egWB9wITgPAA", - "height" : 2, - "name" : "swift-quadtree", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 3, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egEEIDw=", - "text" : "im4:lP>>HCmANVA", - "transparentColor" : null, - "width" : 2 - }, - { - "appPayloadBase64" : "FHpFI3hPUDQCCJE7AA==", - "bodyBase64" : "ekUjeE9QNAIIkTsA", - "height" : 2, - "name" : "swift-bitplanesRawAndRle", - "nonce" : 122, - "pixels" : [ - 0, - 1, - 0, - 1, - 2, - 3, - 2, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNAELkDg==", - "text" : "im4:lPJD[3YYjA~LcBA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEjRCgVgD", - "bodyBase64" : "ekUjeE8SNEKBWAM=", - "height" : 2, - "name" : "swift-adaptiveBitplanesRaw", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 3, - 3, - 0, - 3, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "eiGNUCDW", - "text" : "im4:lPJD[3]W74qiNA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHphI3hPkDQCCKKxPgA=", - "bodyBase64" : "emEjeE+QNAIIorE+AA==", - "height" : 2, - "name" : "swift-directBitplanes", - "nonce" : 122, - "pixels" : [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7 - ], - "profile" : 8, - "sourceV3BodyBase64" : "egiNAIJorA8=", - "text" : "im4:OEKD[39ZjA`X9]DA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEDRCgVgD", - "bodyBase64" : "ekUjeE8QNEKBWAM=", - "height" : 2, - "name" : "swift-compactRowDelta", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 3, - 0, - 3, - 0, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNUCDW", - "text" : "im4:lPJD[3>W74qiNA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHphI3hPkDQCCKIhGgA=", - "bodyBase64" : "emEjeE+QNAIIoiEaAA==", - "height" : 2, - "name" : "swift-directRowDelta", - "nonce" : 122, - "pixels" : [ - 0, - 1, - 2, - 3, - 0, - 1, - 2, - 3 - ], - "profile" : 8, - "sourceV3BodyBase64" : "egiNAIJoiAY=", - "text" : "im4:OEKD[39ZjA`XA5BA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEDRCgVgD", - "bodyBase64" : "ekUjeE8QNEKBWAM=", - "height" : 2, - "name" : "swift-rowDelta", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 3, - 0, - 3, - 0, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNUCDW", - "text" : "im4:lPJD[3>W74qiNA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPEjRCgRgD", - "bodyBase64" : "ekUjeE8SNEKBGAM=", - "height" : 2, - "name" : "swift-varUintRle", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 3, - 3, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "eiGNUCDG", - "text" : "im4:lPJD[3]W74qiMA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPUDQCCA8DAA==", - "bodyBase64" : "ekUjeE9QNAIIDwMA", - "height" : 2, - "name" : "swift-varUintSparse", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 3, - 0, - 0, - 3, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNAMLDAA==", - "text" : "im4:lPJD[3YYjA0KGAA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFB3iPKOiAMI4B", - "bodyBase64" : "ekUHeI8o6IAwjgE=", - "height" : 1, - "name" : "swift-adaptiveLegacyRle", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 0, - 3, - 3, - 3, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "ekEdEMYx", - "text" : "im4:lP6Apy{WeL~JDA", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "FHpFB3iPKOgAMOkH", - "bodyBase64" : "ekUHeI8o6AAw6Qc=", - "height" : 1, - "name" : "swift-adaptiveShortRle", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 3, - 3, - 3, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "ekEdACb9", - "text" : "im4:lP6Apy{WHAA]HA", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "FHpFB3iPyB0ADAA=", - "bodyBase64" : "ekUHeI\/IHQAMAA==", - "height" : 1, - "name" : "swift-adaptiveConstantZero", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "ekEdAAw=", - "text" : "im4:lP6Apy,^C\"BA", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "FHpFB3iPwB0wDAA=", - "bodyBase64" : "ekUHeI\/AHTAMAA==", - "height" : 1, - "name" : "swift-adaptiveConstantOne", - "nonce" : 122, - "pixels" : [ - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egEdMAw=", - "text" : "im4:lP6Apy#^UEDA", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "FHpFB3iPoOgAEAYYAA==", - "bodyBase64" : "ekUHeI+g6AAQBhgA", - "height" : 1, - "name" : "swift-adaptiveSparseOne", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 0, - 0, - 0, - 3, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egEdAMIAAw==", - "text" : "im4:lP6ApyYYHAMCYAA", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "FHpFB3iPoOgAkPlnAA==", - "bodyBase64" : "ekUHeI+g6ACQ+WcA", - "height" : 1, - "name" : "swift-adaptiveSparseZero", - "nonce" : 122, - "pixels" : [ - 3, - 0, - 3, - 3, - 3, - 3, - 0, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egEdADL\/DA==", - "text" : "im4:lP6ApyYYHA*|MBA", - "transparentColor" : null, - "width" : 8 - }, - { - "appPayloadBase64" : "FHoFg\/eEAgawqn8A", - "bodyBase64" : "egWD94QCBrCqfwA=", - "height" : 4, - "name" : "swift-boundsBlock", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 3, - 3, - 0, - 0, - 3, - 3, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "ekEMYFX\/", - "text" : "im4:lPD?sD:h{ey~BA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHoFg\/eEAgawqjwA", - "bodyBase64" : "egWD94QCBrCqPAA=", - "height" : 4, - "name" : "swift-compactBoundsBlock", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 1, - 2, - 0, - 0, - 3, - 1, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "ekEMYFV5", - "text" : "im4:lPD?sD:h{ee`AA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHoFg\/eEAgawqj4A", - "bodyBase64" : "egWD94QCBrCqPgA=", - "height" : 4, - "name" : "swift-regions", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 1, - 3, - 0, - 0, - 3, - 1, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "ekEMYFV9", - "text" : "im4:lPD?sD:h{eN}AA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpFI3hPUDQCSN81AA==", - "bodyBase64" : "ekUjeE9QNAJI3zUA", - "height" : 2, - "name" : "swift-compactRegionsSharedDelta", - "nonce" : 122, - "pixels" : [ - 1, - 3, - 3, - 1, - 3, - 1, - 1, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGNANJ3DQ==", - "text" : "im4:lPJD[3YYjAB(QBA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHoFgPcCAggD", - "bodyBase64" : "egWA9wICCAM=", - "height" : 1, - "name" : "swift-solidBackground", - "nonce" : 122, - "pixels" : [ - 2 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egEAwg==", - "text" : "im4:lP+>HCFtwA", - "transparentColor" : null, - "width" : 1 - }, - { - "appPayloadBase64" : "FHoFg\/eEAgawqn8A", - "bodyBase64" : "egWD94QCBrCqfwA=", - "height" : 4, - "name" : "swift-solidRects", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 3, - 3, - 0, - 0, - 3, - 3, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "ekEMYFX\/", - "text" : "im4:lPD?sD:h{ey~BA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHoFgfciEgAD", - "bodyBase64" : "egWB9yISAAM=", - "height" : 2, - "name" : "swift-implicitWhiteSolid", - "nonce" : 122, - "pixels" : [ - 0, - 0, - 0, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "ekEEwA==", - "text" : "im4:lP>>1YkAYA", - "transparentColor" : null, - "width" : 2 - }, - { - "appPayloadBase64" : "FHoFQe+FJhAeAA==", - "bodyBase64" : "egVB74UmEB4A", - "height" : 2, - "name" : "swift-transparentSolid", - "nonce" : 122, - "pixels" : [ - 2, - 2, - 2, - 2 - ], - "profile" : 1, - "sourceV3BodyBase64" : "eoEEwgM=", - "text" : "im4:lPV\/PE?\"6CA", - "transparentColor" : 3, - "width" : 2 - }, - { - "appPayloadBase64" : "FHpFInhPECQCCNIB", - "bodyBase64" : "ekUieE8QJAII0gE=", - "height" : 2, - "name" : "swift-scanV", - "nonce" : 122, - "pixels" : [ - 0, - 2, - 0, - 1, - 3, - 1 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGJAIJ0", - "text" : "im4:lPBD[3>WiA#5DA", - "transparentColor" : null, - "width" : 3 - }, - { - "appPayloadBase64" : "FHpFInhPECQCCBkD", - "bodyBase64" : "ekUieE8QJAIIGQM=", - "height" : 2, - "name" : "swift-scanS", - "nonce" : 122, - "pixels" : [ - 0, - 1, - 2, - 1, - 0, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGJAELG", - "text" : "im4:lPBD[3>WiA3RGA", - "transparentColor" : null, - "width" : 3 - }, - { - "appPayloadBase64" : "FHpFInhPECQCCJMB", - "bodyBase64" : "ekUieE8QJAIIkwE=", - "height" : 2, - "name" : "swift-scanSV", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 0, - 1, - 2, - 1 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egGJAMJk", - "text" : "im4:lPBD[3>WiAjNDA", - "transparentColor" : null, - "width" : 3 - }, - { - "appPayloadBase64" : "FHpFA3hPEDQACA8A", - "bodyBase64" : "ekUDeE8QNAAIDwA=", - "height" : 1, - "name" : "swift-paletteBitmap", - "nonce" : 122, - "pixels" : [ - 0, - 3, - 3, - 0 - ], - "profile" : 1, - "sourceV3BodyBase64" : "egENAMID", - "text" : "im4:lPaA{bo4BAaFAA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpJA3hPEDQACEQB", - "bodyBase64" : "ekkDeE8QNAAIRAE=", - "height" : 1, - "name" : "swift-paletteSortedDelta", - "nonce" : 122, - "pixels" : [ - 0, - 2, - 4, - 2 - ], - "profile" : 2, - "sourceV3BodyBase64" : "egINAAJR", - "text" : "im4:8aaA{bo4BA_XBA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHpJA3hPEDQACFID", - "bodyBase64" : "ekkDeE8QNAAIUgM=", - "height" : 1, - "name" : "swift-paletteRangeRuns", - "nonce" : 122, - "pixels" : [ - 0, - 1, - 5, - 6 - ], - "profile" : 2, - "sourceV3BodyBase64" : "egINAILU", - "text" : "im4:8aaA{bo4BA=cDA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHp9A3hP0DQASABBAQQB", - "bodyBase64" : "en0DeE\/QNABIAEEBBAE=", - "height" : 1, - "name" : "swift-paletteBankBitmaps", - "nonce" : 122, - "pixels" : [ - 1, - 130, - 1, - 130 - ], - "profile" : 15, - "sourceV3BodyBase64" : "eg8NABJAUABB", - "text" : "im4:_]bA{by6BAL\"*BnLA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHp9A3hP0DQASLBk0ZIB", - "bodyBase64" : "en0DeE\/QNABIsGTRkgE=", - "height" : 1, - "name" : "swift-paletteOrderedSingleBank", - "nonce" : 122, - "pixels" : [ - 193, - 201, - 209, - 201 - ], - "profile" : 15, - "sourceV3BodyBase64" : "eg8NABIsWbRk", - "text" : "im4:_]bA{by6BA\"9_wljA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FHp9A3hP0DQASABBAwgB", - "bodyBase64" : "en0DeE\/QNABIAEEDCAE=", - "height" : 1, - "name" : "swift-paletteOrderedMultiBank", - "nonce" : 122, - "pixels" : [ - 1, - 130, - 3, - 132 - ], - "profile" : 15, - "sourceV3BodyBase64" : "eg8NABJA0ABC", - "text" : "im4:_]bA{by6BAL\"0E3LA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FAAJj3chaAA8ZTOZhFlVVQkAYEIVeAIAmKqqAgA=", - "bodyBase64" : "AAmPdyFoADxlM5mEWVVVCQBgQhV4AgCYqqoCAA==", - "height" : 16, - "name" : "swift-painted16", - "nonce" : 0, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 3, - 3, - 3, - 3, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 3, - 3, - 3, - 3, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 3, - 3, - 3, - 3, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 3, - 3, - 3, - 3, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 2, - "sourceV3BodyBase64" : "AEI8ZTOZhFlVVQkAYEIVeAIAmKqqAg==", - "text" : "im4:dZI@wXaCz3a.(zrfB8:A*h\/7z3AA\/dB8AA", - "transparentColor" : null, - "width" : 16 - }, - { - "appPayloadBase64" : "FP8Vj3chYK48IEAkzkRl3kim7kzn\/t0bTOWdbO0fjfWRrXoDzkbG\/lKJL15MXNf6T+f+jPfyzcf2DnTizUgnH1xsbHChvdHZT+lfrcHVDtlbbG7BzUqIP2ZPrUIGH8u4T+uwzcu4T+uwzWigzUzpX3Ai7lRrfMWXT+0R7tWbjP0VL2KPzU5KfHoFL2bA3f92T+9yDt9+zc96jFxuzVCrnETob3glP\/lVT\/HTLulRDuHf7VZNzVIMvU7LrEqKnPM0T\/M0T\/M0T\/M0TwA=", - "bodyBase64" : "\/xWPdyFgrjwgQCTORGXeSKbuTOf+3RtM5Z1s7R+N9ZGtegPORsb+UokvXkxc1\/pP5\/6M9\/LNx\/YOdOLNSCcfXGxscKG90dlP6V+twdUO2VtsbsHNSog\/Zk+tQgYfy7hP67DNy7hP67DNaKDNTOlfcCLuVGt8xZdP7RHu1ZuM\/RUvYo\/NTkp8egUvZsDd\/3ZP73IO337Nz3qMXG7NUKucROhveCU\/+VVP8dMu6VEO4d\/tVk3NUgy9TsusSoqc8zRP8zRP8zRP8zRPAA==", - "height" : 16, - "name" : "swift-dense16", - "nonce" : 255, - "pixels" : [ - 0, - 17, - 34, - 51, - 4, - 21, - 38, - 55, - 8, - 25, - 42, - 59, - 12, - 29, - 46, - 63, - 29, - 47, - 1, - 19, - 37, - 55, - 9, - 27, - 45, - 63, - 17, - 35, - 53, - 7, - 25, - 43, - 58, - 13, - 32, - 51, - 6, - 25, - 44, - 63, - 18, - 37, - 56, - 11, - 30, - 49, - 4, - 23, - 23, - 43, - 63, - 19, - 39, - 59, - 15, - 35, - 55, - 11, - 31, - 51, - 7, - 27, - 47, - 3, - 52, - 9, - 30, - 51, - 8, - 29, - 50, - 7, - 28, - 49, - 6, - 27, - 48, - 5, - 26, - 47, - 17, - 39, - 61, - 19, - 41, - 63, - 21, - 43, - 1, - 23, - 45, - 3, - 25, - 47, - 5, - 27, - 46, - 5, - 28, - 51, - 10, - 33, - 56, - 15, - 38, - 61, - 20, - 43, - 2, - 25, - 48, - 7, - 11, - 35, - 59, - 19, - 43, - 3, - 27, - 51, - 11, - 35, - 59, - 19, - 43, - 3, - 27, - 51, - 40, - 1, - 26, - 51, - 12, - 37, - 62, - 23, - 48, - 9, - 34, - 59, - 20, - 45, - 6, - 31, - 5, - 31, - 57, - 19, - 45, - 7, - 33, - 59, - 21, - 47, - 9, - 35, - 61, - 23, - 49, - 11, - 34, - 61, - 24, - 51, - 14, - 41, - 4, - 31, - 58, - 21, - 48, - 11, - 38, - 1, - 28, - 55, - 63, - 27, - 55, - 19, - 47, - 11, - 39, - 3, - 31, - 59, - 23, - 51, - 15, - 43, - 7, - 35, - 28, - 57, - 22, - 51, - 16, - 45, - 10, - 39, - 4, - 33, - 62, - 27, - 56, - 21, - 50, - 15, - 57, - 23, - 53, - 19, - 49, - 15, - 45, - 11, - 41, - 7, - 37, - 3, - 33, - 63, - 29, - 59, - 22, - 53, - 20, - 51, - 18, - 49, - 16, - 47, - 14, - 45, - 12, - 43, - 10, - 41, - 8, - 39, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19, - 51, - 19 - ], - "profile" : 5, - "sourceV3BodyBase64" : "\/wU8IEAkzkRl3kim7kzn\/t0bTOWdbO0fjfWRrXoDzkbG\/lKJL15MXNf6T+f+jPfyzcf2DnTizUgnH1xsbHChvdHZT+lfrcHVDtlbbG7BzUqIP2ZPrUIGH8u4T+uwzcu4T+uwzWigzUzpX3Ai7lRrfMWXT+0R7tWbjP0VL2KPzU5KfHoFL2bA3f92T+9yDt9+zc96jFxuzVCrnETob3glP\/lVT\/HTLulRDuHf7VZNzVIMvU7LrEqKnPM0T\/M0T\/M0T\/M0Tw==", - "text" : "im4:@9I@wX@@8KS\"z?J5)q%+^^wU^s2T\/d*b[#85f{Pmb>>2cj.sKN3*=a%%z~7.K\/vr4Tb|lZ#+I\/@Kk_8[z9[()\/+Y`Z{n|>%tVDF!~^%j2*PQv&U{1Xaa@lV$3=b`6r:Vl4S?AA", - "transparentColor" : null, - "width" : 16 - }, - { - "appPayloadBase64" : "FABBQ3hPIGgIEC0F", - "bodyBase64" : "AEFDeE8gaAgQLQU=", - "height" : 3, - "name" : "swift-profile-0-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 1, - 0, - 1, - 1, - 0, - 1, - 0, - 0, - 1, - 0, - 1 - ], - "profile" : 0, - "sourceV3BodyBase64" : "AAANAaKl", - "text" : "im4::C^F[3%trBj#UA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9BQ3hPIGgIEC0F", - "bodyBase64" : "\/0FDeE8gaAgQLQU=", - "height" : 3, - "name" : "swift-profile-0-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 1, - 0, - 1, - 1, - 0, - 1, - 0, - 0, - 1, - 0, - 1 - ], - "profile" : 0, - "sourceV3BodyBase64" : "\/wANAaKl", - "text" : "im4:4F^F[3%trBj#UA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABFQ3hPIGkIELZYYwA=", - "bodyBase64" : "AEVDeE8gaQgQtlhjAA==", - "height" : 3, - "name" : "swift-profile-1-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 3, - 2, - 1, - 1, - 0, - 3, - 2, - 2, - 1, - 0, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "AAENAcIWaww=", - "text" : "im4:GO^F[3fzrBE<7lMA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9FQ3hPIGkIELZYYwA=", - "bodyBase64" : "\/0VDeE8gaQgQtlhjAA==", - "height" : 3, - "name" : "swift-profile-1-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 3, - 2, - 1, - 1, - 0, - 3, - 2, - 2, - 1, - 0, - 3 - ], - "profile" : 1, - "sourceV3BodyBase64" : "\/wENAcIWaww=", - "text" : "im4:?Q^F[3fzrBE<7lMA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABJQ3hPoGkIENwtJwUH", - "bodyBase64" : "AElDeE+gaQgQ3C0nBQc=", - "height" : 3, - "name" : "swift-profile-2-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 7, - 6, - 5, - 5, - 4, - 3, - 2, - 2, - 1, - 0, - 7 - ], - "profile" : 2, - "sourceV3BodyBase64" : "AAINAYK75aTg", - "text" : "im4:dZ^F[3O2rBrn,@\/BHA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9JQ3hPoGkIENwtJwUH", - "bodyBase64" : "\/0lDeE+gaQgQ3C0nBQc=", - "height" : 3, - "name" : "swift-profile-2-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 7, - 6, - 5, - 5, - 4, - 3, - 2, - 2, - 1, - 0, - 7 - ], - "profile" : 2, - "sourceV3BodyBase64" : "\/wINAYK75aTg", - "text" : "im4:Lc^F[3O2rBrn,@\/BHA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABNQ3hPoGoIEDivphUNfAA=", - "bodyBase64" : "AE1DeE+gaggQOK+mFQ18AA==", - "height" : 3, - "name" : "swift-profile-3-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 7, - 14, - 5, - 13, - 4, - 11, - 2, - 10, - 1, - 8, - 15 - ], - "profile" : 3, - "sourceV3BodyBase64" : "AAMNAQLn1bSigQ8=", - "text" : "im4:0k^F[3,7rB>>T;3H^>DA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9NQ3hPoGoIEDivphUNfAA=", - "bodyBase64" : "\/01DeE+gaggQOK+mFQ18AA==", - "height" : 3, - "name" : "swift-profile-3-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 7, - 14, - 5, - 13, - 4, - 11, - 2, - 10, - 1, - 8, - 15 - ], - "profile" : 3, - "sourceV3BodyBase64" : "\/wMNAQLn1bSigQ8=", - "text" : "im4:in^F[3,7rB>>T;3H^>DA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABRQ3hPIGsIEHBc7WRJHdAD", - "bodyBase64" : "AFFDeE8gawgQcFztZEkd0AM=", - "height" : 3, - "name" : "swift-profile-4-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 4, - 11, - 18, - 26, - 1, - 8, - 15 - ], - "profile" : 4, - "sourceV3BodyBase64" : "AAQNAQKOq50sqQN6", - "text" : "im4:;v^F[32!rB3(d8sjj]\/`A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9RQ3hPIGsIEHBc7WRJHdAD", - "bodyBase64" : "\/1FDeE8gawgQcFztZEkd0AM=", - "height" : 3, - "name" : "swift-profile-4-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 4, - 11, - 18, - 26, - 1, - 8, - 15 - ], - "profile" : 4, - "sourceV3BodyBase64" : "\/wQNAQKOq50sqQN6", - "text" : "im4:5y^F[32!rB3(d8sjj]\/`A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABVQ3hPIGwIEOBwqo5cZT1AHgA=", - "bodyBase64" : "AFVDeE8gbAgQ4HCqjlxlPUAeAA==", - "height" : 3, - "name" : "swift-profile-5-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 36, - 43, - 50, - 58, - 1, - 8, - 15 - ], - "profile" : 5, - "sourceV3BodyBase64" : "AAUNAQIcTtWRq6wHyAM=", - "text" : "im4:H7^F[3U)rBJtqbPyHPkFZVAA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9VQ3hPIGwIEOBwqo5cZT1AHgA=", - "bodyBase64" : "\/1VDeE8gbAgQ4HCqjlxlPUAeAA==", - "height" : 3, - "name" : "swift-profile-5-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 36, - 43, - 50, - 58, - 1, - 8, - 15 - ], - "profile" : 5, - "sourceV3BodyBase64" : "\/wUNAQIcTtWRq6wHyAM=", - "text" : "im4:@9^F[3U)rBJtqbPyHPkFZVAA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABZQ3hPoGoIEDivphUNfAA=", - "bodyBase64" : "AFlDeE+gaggQOK+mFQ18AA==", - "height" : 3, - "name" : "swift-profile-6-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 7, - 14, - 5, - 13, - 4, - 11, - 2, - 10, - 1, - 8, - 15 - ], - "profile" : 6, - "sourceV3BodyBase64" : "AAYNAQLn1bSigQ8=", - "text" : "im4:e+^F[3,7rB>>T;3H^>DA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9ZQ3hPoGoIEDivphUNfAA=", - "bodyBase64" : "\/1lDeE+gaggQOK+mFQ18AA==", - "height" : 3, - "name" : "swift-profile-6-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 7, - 14, - 5, - 13, - 4, - 11, - 2, - 10, - 1, - 8, - 15 - ], - "profile" : 6, - "sourceV3BodyBase64" : "\/wYNAQLn1bSigQ8=", - "text" : "im4:M\/^F[3,7rB>>T;3H^>DA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABdQ3hPIGsIEHBc7WRJHdAD", - "bodyBase64" : "AF1DeE8gawgQcFztZEkd0AM=", - "height" : 3, - "name" : "swift-profile-7-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 4, - 11, - 18, - 26, - 1, - 8, - 15 - ], - "profile" : 7, - "sourceV3BodyBase64" : "AAcNAQKOq50sqQN6", - "text" : "im4:1[^F[32!rB3(d8sjj]\/`A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9dQ3hPIGsIEHBc7WRJHdAD", - "bodyBase64" : "\/11DeE8gawgQcFztZEkd0AM=", - "height" : 3, - "name" : "swift-profile-7-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 7, - 14, - 21, - 29, - 4, - 11, - 18, - 26, - 1, - 8, - 15 - ], - "profile" : 7, - "sourceV3BodyBase64" : "\/wcNAQKOq50sqQN6", - "text" : "im4:j_^F[32!rB3(d8sjj]\/`A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABhQ3hPoGkIENwtJwUH", - "bodyBase64" : "AGFDeE+gaQgQ3C0nBQc=", - "height" : 3, - "name" : "swift-profile-8-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 7, - 6, - 5, - 5, - 4, - 3, - 2, - 2, - 1, - 0, - 7 - ], - "profile" : 8, - "sourceV3BodyBase64" : "AAgNAYK75aTg", - "text" : "im4::C_F[3O2rBrn,@\/BHA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9hQ3hPoGkIENwtJwUH", - "bodyBase64" : "\/2FDeE+gaQgQ3C0nBQc=", - "height" : 3, - "name" : "swift-profile-8-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 7, - 6, - 5, - 5, - 4, - 3, - 2, - 2, - 1, - 0, - 7 - ], - "profile" : 8, - "sourceV3BodyBase64" : "\/wgNAYK75aTg", - "text" : "im4:4F_F[3O2rBrn,@\/BHA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABlQ3hPoGkIENwtJwUH", - "bodyBase64" : "AGVDeE+gaQgQ3C0nBQc=", - "height" : 3, - "name" : "swift-profile-9-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 484, - 401, - 283, - 283, - 210, - 91, - 63, - 63, - 83, - 0, - 484 - ], - "profile" : 9, - "sourceV3BodyBase64" : "AAkNAYK75aTg", - "text" : "im4:GO_F[3O2rBrn,@\/BHA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9lQ3hPoGkIENwtJwUH", - "bodyBase64" : "\/2VDeE+gaQgQ3C0nBQc=", - "height" : 3, - "name" : "swift-profile-9-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 484, - 401, - 283, - 283, - 210, - 91, - 63, - 63, - 83, - 0, - 484 - ], - "profile" : 9, - "sourceV3BodyBase64" : "\/wkNAYK75aTg", - "text" : "im4:?Q_F[3O2rBrn,@\/BHA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABpQ3hPoGoIEDivphUNfAA=", - "bodyBase64" : "AGlDeE+gaggQOK+mFQ18AA==", - "height" : 3, - "name" : "swift-profile-10-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 210, - 492, - 155, - 447, - 118, - 338, - 63, - 310, - 84, - 246, - 511 - ], - "profile" : 10, - "sourceV3BodyBase64" : "AAoNAQLn1bSigQ8=", - "text" : "im4:dZ_F[3,7rB>>T;3H^>DA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9pQ3hPoGoIEDivphUNfAA=", - "bodyBase64" : "\/2lDeE+gaggQOK+mFQ18AA==", - "height" : 3, - "name" : "swift-profile-10-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 210, - 492, - 155, - 447, - 118, - 338, - 63, - 310, - 84, - 246, - 511 - ], - "profile" : 10, - "sourceV3BodyBase64" : "\/woNAQLn1bSigQ8=", - "text" : "im4:Lc_F[3,7rB>>T;3H^>DA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABtQ3hPIGsIEHBc7WRJHdAD", - "bodyBase64" : "AG1DeE8gawgQcFztZEkd0AM=", - "height" : 3, - "name" : "swift-profile-11-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 118, - 237, - 347, - 457, - 64, - 182, - 310, - 429, - 18, - 128, - 255 - ], - "profile" : 11, - "sourceV3BodyBase64" : "AAsNAQKOq50sqQN6", - "text" : "im4:0k_F[32!rB3(d8sjj]\/`A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9tQ3hPIGsIEHBc7WRJHdAD", - "bodyBase64" : "\/21DeE8gawgQcFztZEkd0AM=", - "height" : 3, - "name" : "swift-profile-11-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 118, - 237, - 347, - 457, - 64, - 182, - 310, - 429, - 18, - 128, - 255 - ], - "profile" : 11, - "sourceV3BodyBase64" : "\/wsNAQKOq50sqQN6", - "text" : "im4:in_F[32!rB3(d8sjj]\/`A", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FABxQ3hPIGwIEOBwqo5cZT1AHgA=", - "bodyBase64" : "AHFDeE8gbAgQ4HCqjlxlPUAeAA==", - "height" : 3, - "name" : "swift-profile-12-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 9, - 64, - 127 - ], - "profile" : 12, - "sourceV3BodyBase64" : "AAwNAQIcTtWRq6wHyAM=", - "text" : "im4:;v_F[3U)rBJtqbPyHPkFZVAA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP9xQ3hPIGwIEOBwqo5cZT1AHgA=", - "bodyBase64" : "\/3FDeE8gbAgQ4HCqjlxlPUAeAA==", - "height" : 3, - "name" : "swift-profile-12-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 9, - 64, - 127 - ], - "profile" : 12, - "sourceV3BodyBase64" : "\/wwNAQIcTtWRq6wHyAM=", - "text" : "im4:5y_F[3U)rBJtqbPyHPkFZVAA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FAB1Q3hPoGwIEMDBUemQVjJdEPkE", - "bodyBase64" : "AHVDeE+gbAgQwMFR6ZBWMl0Q+QQ=", - "height" : 3, - "name" : "swift-profile-13-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 2, - 10, - 17 - ], - "profile" : 13, - "sourceV3BodyBase64" : "AA0NAQI4OCod0kqmCyKf", - "text" : "im4:H7_F[3D,rBK\"@JCp(fr6)F\"NA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FP91Q3hPoGwIEMDBUemQVjJdEPkE", - "bodyBase64" : "\/3VDeE+gbAgQwMFR6ZBWMl0Q+QQ=", - "height" : 3, - "name" : "swift-profile-13-nonce-255", - "nonce" : 255, - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 2, - 10, - 17 - ], - "profile" : 13, - "sourceV3BodyBase64" : "\/w0NAQI4OCod0kqmCyKf", - "text" : "im4:@9_F[3D,rBK\"@JCp(fr6)F\"NA", - "transparentColor" : null, - "width" : 4 - }, - { - "appPayloadBase64" : "FAB5Q3hPoG0IEIADh4oOkhUZnSCkJwA=", - "bodyBase64" : "AHlDeE+gbQgQgAOHig6SFRmdIKQnAA==", - "height" : 3, - "name" : "swift-profile-14-nonce-0", - "nonce" : 0, - "pixels" : [ - 0, - 63, - 118, - 173, - 237, - 292, - 347, - 402, - 466, - 2, - 10, - 17 - ], - "profile" : 14, - "sourceV3BodyBase64" : "AA4NAQJw4FDRQbIioxOE9AQ=", - "text" : "im4:e+_F[381YEAYA", - "transparentColor" : null, - "width" : 1 - }, - { - "appPayloadBase64" : "FCpJ33snCHLfAwMA", - "bodyBase64" : "KknfeycIct8DAwA=", - "height" : 31, - "name" : "dimensions-32x31", - "nonce" : 42, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 2, - "sourceV3BodyBase64" : "KkJ9Dww=", - "text" : "im4:,ZN|*bnLb_VEAA", - "transparentColor" : null, - "width" : 32 - }, - { - "appPayloadBase64" : "FCqJ4Oe9IMiCHzAA", - "bodyBase64" : "Kong570gyIIfMAA=", - "height" : 32, - "name" : "dimensions-33x32", - "nonce" : 42, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 2, - "sourceV3BodyBase64" : "KkKCHzA=", - "text" : "im4:,ZX|wr&tA)!(AA", - "transparentColor" : null, - "width" : 33 - }, - { - "appPayloadBase64" : "FCoJv3cEgsgPDA==", - "bodyBase64" : "Kgm\/dwSCyA8M", - "height" : 64, - "name" : "dimensions-64x64", - "nonce" : 42, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 2, - "sourceV3BodyBase64" : "KkL8wA==", - "text" : "im4:,Zc_MD?v+CG", - "transparentColor" : null, - "width" : 64 - }, - { - "appPayloadBase64" : "FCrJgLwnEuQBAQMA", - "bodyBase64" : "KsmAvCcS5AEBAwA=", - "height" : 65, - "name" : "dimensions-65x65", - "nonce" : 42, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 2, - "sourceV3BodyBase64" : "KkIDAgY=", - "text" : "im4:,ZdL{b]WftUEAA", - "transparentColor" : null, - "width" : 65 - }, - { - "appPayloadBase64" : "FCrJ\/wG8Q4iC\/wMAAwA=", - "bodyBase64" : "Ksn\/AbxDiIL\/AwADAA==", - "height" : 1, - "name" : "dimensions-256x1", - "nonce" : 42, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 2, - "sourceV3BodyBase64" : "KkL\/BwAG", - "text" : "im4:,Z\"sSqtu|(4F*hAA", - "transparentColor" : null, - "width" : 256 - }, - { - "appPayloadBase64" : "FCrJAf69B4GCA\/wDAwA=", - "bodyBase64" : "KskB\/r0HgYID\/AMDAA==", - "height" : 256, - "name" : "dimensions-1x256", - "nonce" : 42, - "pixels" : [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "profile" : 2, - "sourceV3BodyBase64" : "KkIH+AcG", - "text" : "im4:,ZPt2r.F|(l__hAA", - "transparentColor" : null, - "width" : 1 - } - ] -} \ No newline at end of file From ad623867d64ac6cb1de0cbdd22336338f75ae5d2 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:47:00 -0800 Subject: [PATCH 04/13] style: format mcoimg for swiftformat --- .../Chats/ChatConversationInputBar.swift | 18 ++-- MC1/Views/Chats/MCOimg/MCOImageRenderer.swift | 16 ++-- MC1/Views/Chats/MCOimg/PixelPaintDraft.swift | 4 +- .../SyncCoordinator+MessageHandlers.swift | 7 +- .../SyncCoordinator+ReactionHandlers.swift | 2 +- .../Utilities/MCOImageTransport.swift | 2 +- .../Utilities/MCOimg/MCOImageBitReader.swift | 16 ++-- .../Utilities/MCOimg/MCOImageBitWriter.swift | 4 +- .../Utilities/MCOimg/MCOImageCodec.swift | 6 +- .../Utilities/MCOimg/MCOImageFigure.swift | 8 +- .../MCOimg/MCOImagePalette+Tables.swift | 86 +++++++++---------- .../Utilities/MCOimg/MCOImagePalette.swift | 8 +- .../MCOimg/MCOImageV3Codec+Bitplanes.swift | 12 ++- .../MCOimg/MCOImageV3Codec+Blocks.swift | 12 ++- .../MCOimg/MCOImageV3Codec+CompactRows.swift | 20 +++-- .../MCOimg/MCOImageV3Codec+Containers.swift | 8 +- .../MCOimg/MCOImageV3Codec+Encode.swift | 38 +++++--- .../MCOimg/MCOImageV3Codec+LocalPalette.swift | 16 ++-- .../MCOimg/MCOImageV3Codec+Rows.swift | 40 ++++++--- .../Utilities/MCOimg/MCOImageV3Codec.swift | 13 ++- .../MCOimg/MCOImageV4BitReader.swift | 16 ++-- .../MCOimg/MCOImageV4Codec+Raster.swift | 6 +- .../MCOimg/MCOImageV4Parser+Extended.swift | 12 +-- .../MCOimg/MCOImageV4Parser+Figures.swift | 2 +- .../MCOimg/MCOImageV4Parser+Paths.swift | 13 ++- .../Utilities/MCOimg/MCOImageV4Parser.swift | 30 ++++--- .../Utilities/MCOimg/MCOTextBitReader.swift | 8 +- .../Utilities/MCOimg/MCOTextDecoder.swift | 24 ++++-- .../Utilities/MCOimg/MCOTextModel.swift | 4 +- .../Utilities/MCOimg/MCOTextModels+BE.swift | 2 +- .../Utilities/MCOimg/MCOTextModels+DE.swift | 2 +- .../Utilities/MCOimg/MCOTextModels+EN.swift | 2 +- .../Utilities/MCOimg/MCOTextModels+FR.swift | 2 +- .../Utilities/MCOimg/MCOTextModels+IT.swift | 2 +- .../Utilities/MCOimg/MCOTextModels+RU.swift | 2 +- .../Utilities/MCOimg/MCOTextModels+UK.swift | 2 +- .../Utilities/MCOimg/MCOTextModels.swift | 8 +- .../MCOImageBinarySendTests.swift | 10 +-- .../MCOImageTransportTests.swift | 22 ++--- .../MCOImageV3CodecTests.swift | 12 +-- .../Utilities/MCOImageV4CodecTests.swift | 36 +++++--- .../Utilities/MCOTextCodecTests.swift | 14 +-- .../RoomMessageBubbleA11yLabelTests.swift | 2 +- .../Views/Chats/MCOImageGeometryTests.swift | 18 ++-- .../Views/Chats/MCOImageMessageTests.swift | 8 +- .../Views/Chats/PixelPaintDraftTests.swift | 20 ++--- .../Chats/PixelPaintPresentationTests.swift | 28 +++--- .../ChannelSendSerializationTests.swift | 20 ++--- 48 files changed, 397 insertions(+), 266 deletions(-) diff --git a/MC1/Views/Chats/ChatConversationInputBar.swift b/MC1/Views/Chats/ChatConversationInputBar.swift index c5e2eca883..e054ddd5d3 100644 --- a/MC1/Views/Chats/ChatConversationInputBar.swift +++ b/MC1/Views/Chats/ChatConversationInputBar.swift @@ -17,14 +17,14 @@ struct ChatConversationInputBar: View { var body: some View { inputBar - .fullScreenCover(isPresented: $isShowingPainter) { - PixelPaintEditor(draft: drawing, onSend: sendDrawing) - } - .onChange(of: conversationType.coordinatorID) { - drawing.remove() - isShowingPainter = false - } - .onDisappear { drawing.remove() } + .fullScreenCover(isPresented: $isShowingPainter) { + PixelPaintEditor(draft: drawing, onSend: sendDrawing) + } + .onChange(of: conversationType.coordinatorID) { + drawing.remove() + isShowingPainter = false + } + .onDisappear { drawing.remove() } } @ViewBuilder @@ -66,7 +66,7 @@ struct ChatConversationInputBar: View { } private func sendDrawing() { - let isChannel: Bool = if case .channel = conversationType { true } else { false } + let isChannel = if case .channel = conversationType { true } else { false } let radioID = conversationType.radioID let ready = { appState.connectionState == .ready && appState.connectedDevice?.radioID == radioID diff --git a/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift b/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift index bd5441f788..f328bd1570 100644 --- a/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift +++ b/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift @@ -37,9 +37,9 @@ struct MCOImageRenderer: View { static func color(_ reference: Int, profile: Int) -> Color { let rgb = MCOImagePalette.color(reference, profile: profile) let maximumComponent = 255.0 - return Color(.sRGB, red: Double((rgb >> 16) & 0xff) / maximumComponent, - green: Double((rgb >> 8) & 0xff) / maximumComponent, - blue: Double(rgb & 0xff) / maximumComponent, opacity: 1) + return Color(.sRGB, red: Double((rgb >> 16) & 0xFF) / maximumComponent, + green: Double((rgb >> 8) & 0xFF) / maximumComponent, + blue: Double(rgb & 0xFF) / maximumComponent, opacity: 1) } static func raster(_ image: MCOImageRaster, origin: CGPoint, context: inout GraphicsContext) { @@ -60,7 +60,7 @@ struct MCOImageRenderer: View { let center = MCOImageGeometry.point(point) let radius = CGFloat(style.strokeWidth) / 2 context.fill(Path(ellipseIn: CGRect(x: center.x - radius, y: center.y - radius, - width: radius * 2, height: radius * 2)), with: .color(color(stroke, profile: profile))) + width: radius * 2, height: radius * 2)), with: .color(color(stroke, profile: profile))) case let .line(start, end, style): var path = Path() path.move(to: MCOImageGeometry.point(start)) @@ -77,7 +77,9 @@ struct MCOImageRenderer: View { guard let first = points.first else { return } var path = Path() path.move(to: MCOImageGeometry.point(first)) - for point in points.dropFirst() { path.addLine(to: MCOImageGeometry.point(point)) } + for point in points.dropFirst() { + path.addLine(to: MCOImageGeometry.point(point)) + } paint(path, closed: closed, style: style, profile: profile, context: &context) case let .wave(start, end, depth, closed, style): guard let path = MCOImageGeometry.wave(start, end, depth: depth) else { return } @@ -86,7 +88,9 @@ struct MCOImageRenderer: View { drawText(text, origin: origin, width: width, alignment: alignment, fontSize: fontSize, style: style, profile: profile, canvasWidth: canvasWidth, context: &context) case let .group(figures, _): - for child in figures { self.figure(child, profile: profile, canvasWidth: canvasWidth, context: &context) } + for child in figures { + self.figure(child, profile: profile, canvasWidth: canvasWidth, context: &context) + } case let .raster(origin, image): raster(image, origin: CGPoint(x: origin.x, y: origin.y), context: &context) } diff --git a/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift b/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift index 9f6628a50b..aed1f3f49e 100644 --- a/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift +++ b/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift @@ -42,7 +42,9 @@ final class PixelPaintDraft { previousCell = (x, y) } - func endStroke() { previousCell = nil } + func endStroke() { + previousCell = nil + } func clear() { guard !isSubmitting else { return } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 56c67a130f..48a1aa1179 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -396,16 +396,15 @@ extension SyncCoordinator { messageDTO, scope: scope, conversationID: channel?.textRulesID ), scope.isCurrent else { return } - let savedDTO: MessageDTO - if datagramSenderName == nil { - savedDTO = try await harvestAndRefreshChannelMessage( + let savedDTO: MessageDTO = if datagramSenderName == nil { + try await harvestAndRefreshChannelMessage( messageDTO: messageDTO, radioID: radioID, dependencies: dependencies, scope: scope ) } else { - savedDTO = messageDTO + messageDTO } try await indexAndNotifyChannelMessage( messageDTO: savedDTO, diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift index 92c4ac94e1..5551b9a52f 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift @@ -252,7 +252,7 @@ extension SyncCoordinator { return true } - if (try? await dependencies.dataStore.channelImageMatchesReaction( + if await (try? dependencies.dataStore.channelImageMatchesReaction( radioID: radioID, channelIndex: channelIndex, parsedReaction: parsed, diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift index a6d15b5594..71fdfb0370 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift @@ -6,7 +6,7 @@ public enum MCOImageTransport { public static let applicationDataType: UInt16 = 0x0120 public static let imageSubtype: UInt8 = 0x01 private static let subtypeShift: UInt8 = 4 - private static let varintPayloadMask: UInt8 = 0x7f + private static let varintPayloadMask: UInt8 = 0x7F private static let varintContinuation: UInt8 = 0x80 private static let varintPayloadBits = 7 private static let maxVarintBytes = 5 diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift index a4ad02381e..698566ae72 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift @@ -10,7 +10,9 @@ struct MCOImageBitReader { position = byteOffset * 8 } - static func width(_ value: Int) -> Int { value <= 0 ? 0 : Int.bitWidth - value.leadingZeroBitCount } + static func width(_ value: Int) -> Int { + value <= 0 ? 0 : Int.bitWidth - value.leadingZeroBitCount + } mutating func read(_ bits: Int) throws -> Int { guard (0...32).contains(bits), position >= 0, position + bits <= bytes.count * 8 else { throw MCOImageCodecError.damaged } @@ -33,16 +35,18 @@ struct MCOImageBitReader { } mutating func prefix(limit: Int) throws -> Int { - for length in 0.. Int { switch try prefix(limit: 3) { - case 0: return try read(2) - case 1: return try read(4) + 4 - case 2: return try read(8) + 20 - default: return try varUint() + case 0: try read(2) + case 1: try read(4) + 4 + case 2: try read(8) + 20 + default: try varUint() } } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift index 32a6d5bc7e..926946bf25 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift @@ -40,5 +40,7 @@ struct MCOImageBitWriter { } } - var data: Data { Data(bytes) } + var data: Data { + Data(bytes) + } } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift index 3c189def1b..f8623598cd 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift @@ -9,7 +9,7 @@ public enum MCOImageCodec { private static let maximumVersionDigits = 2 private static let textPrefixLength = 2 private static let subtype: UInt8 = 1 - private static let versionMask: UInt8 = 0x0f + private static let versionMask: UInt8 = 0x0F private static let subtypeShift = 4 public static func isImageText(_ text: String) -> Bool { @@ -30,8 +30,8 @@ public enum MCOImageCodec { let payload = try appPayload(fromText: text) let body = Data(payload.dropFirst()) switch version { - case v3Version: return .raster(try MCOImageV3Codec.decodeBody(body)) - case v4Version: return .document(try MCOImageV4Codec.decodeBody(body)) + case v3Version: return try .raster(MCOImageV3Codec.decodeBody(body)) + case v4Version: return try .document(MCOImageV4Codec.decodeBody(body)) default: return .unsupported } } catch MCOImageCodecError.unsupported { diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageFigure.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageFigure.swift index c512fd6b0e..020f1bc151 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageFigure.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageFigure.swift @@ -19,7 +19,9 @@ public indirect enum MCOImageFigure: Sendable, Hashable { } func translated(x: Int, y: Int, style nextStyle: MCOImageV4Style) -> Self { - func moved(_ point: MCOImageV4Point) -> MCOImageV4Point { point.translated(x: x, y: y) } + func moved(_ point: MCOImageV4Point) -> MCOImageV4Point { + point.translated(x: x, y: y) + } switch self { case let .dot(point, _): return .dot(moved(point), nextStyle) case let .line(start, end, _): return .line(moved(start), moved(end), nextStyle) @@ -42,7 +44,9 @@ public indirect enum MCOImageFigure: Sendable, Hashable { guard limit > 0 else { throw MCOImageCodecError.unsupported } if case let .group(figures, _) = self { var total = 0 - for figure in figures { total += try figure.expandedCount(upTo: limit - total) } + for figure in figures { + total += try figure.expandedCount(upTo: limit - total) + } return total } return 1 diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette+Tables.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette+Tables.swift index ad6ccc1131..35c2f5c725 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette+Tables.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette+Tables.swift @@ -41,49 +41,49 @@ extension MCOImagePalette { ] static let global512: [UInt32] = [ - 0xFFFFFF, 0xF1D3B3, 0xD7AE83, 0xBB875D, 0x9B633E, 0x7C492D, 0x5E331F, 0x412116, 0x25110B, 0xD9D9D9, 0xFFEDE5, 0xFFE5D3, - 0xFFD8C6, 0xF8CCBF, 0xF4BFA5, 0xEBB88F, 0xE0A984, 0xD2977B, 0xB3B3B3, 0xFFD6E0, 0xFFDCC8, 0xFFF2B8, 0xCDECCF, 0xC9EEF0, - 0xCEDDFA, 0xE0D2F4, 0xEACFE3, 0x8A8B8A, 0xE4E0AE, 0xCAC783, 0xAAA95F, 0x898B43, 0x6D7134, 0x535629, 0x3A3C1E, 0x232416, - 0x6F6F6F, 0xFFF1B8, 0xFFE08A, 0xF4C95D, 0xDDAF37, 0xC49324, 0x9D7118, 0x74500F, 0x493008, 0x4F4F4F, 0xB9F3E8, 0x82DDCF, - 0x4EC3B5, 0x27A497, 0x168479, 0x0E635C, 0x08443F, 0x032622, 0x242424, 0xF4C0A8, 0xE79B7C, 0xD47657, 0xB9563E, 0x963D2D, - 0x722B22, 0x4F1C18, 0x2B0E0D, 0x000000, 0xFFB0A3, 0xFAF3E8, 0xEFE3D2, 0xE2D1B9, 0xD3BFA2, 0xC2A987, 0xAA906F, 0x8D765C, - 0x6F5C49, 0xFF9A89, 0xFFE0C2, 0xF4C29F, 0xDFA57E, 0xC88962, 0xAA6B49, 0x82503A, 0x5B352A, 0x35201B, 0xFF5541, 0x8D8D8D, - 0xA4A4A4, 0x666666, 0xFF3F24, 0xFE3A1D, 0xFE3416, 0xFE2F0E, 0xFE2907, 0xFE2400, 0xF92300, 0xF42300, 0xEF2200, 0xEA2100, - 0xE52101, 0xE02001, 0xDB1F01, 0xD61F01, 0xD11E01, 0xCA1D01, 0xC31C01, 0xBC1B01, 0xB51A01, 0xAD1900, 0xA61800, 0x9F1700, - 0x981600, 0x911500, 0x8C1400, 0x871300, 0x811300, 0x7C1200, 0x771101, 0x721001, 0x6C1001, 0x670F01, 0x620E01, 0x5F0E01, - 0x5C0D01, 0x580D01, 0x550C01, 0x520C00, 0x4F0B00, 0x4B0B00, 0x480A00, 0x450A00, 0xFFB363, 0xFFB261, 0xFFB160, 0xFFAF5E, - 0xFFAE5D, 0xFFAD5B, 0xFFAC5A, 0xFFAA58, 0xFFA957, 0xFFA855, 0xFFA651, 0xFFA34D, 0xFFA14A, 0xFF9F46, 0xFF9C42, 0xFF9A3E, - 0xFF983B, 0xFF9537, 0xFF9333, 0xFF912D, 0xFF9028, 0xFF8E22, 0xFF8C1C, 0xFF8B17, 0xFF8911, 0xFF870B, 0xFF8606, 0xFF8400, - 0xFC8200, 0xF98100, 0xF67F00, 0xF37E00, 0xF07C01, 0xED7B01, 0xEA7901, 0xE77801, 0xE47601, 0xE17401, 0xDD7201, 0xDA7101, - 0xD66F01, 0xD36D01, 0xCF6B01, 0xCC6A01, 0xC86801, 0xC56601, 0xBF6301, 0xB96001, 0xB35C01, 0xAD5901, 0xA65600, 0xA05300, - 0x9A4F00, 0x944C00, 0x8E4900, 0x8C4800, 0x8A4700, 0x884600, 0x864500, 0x834400, 0x814300, 0x7F4200, 0x7D4100, 0x7B4000, - 0xF7E572, 0xF7E46F, 0xF7E36D, 0xF6E36A, 0xF6E268, 0xF6E165, 0xF6E063, 0xF5E060, 0xF5DF5E, 0xF5DE5B, 0xF5DD51, 0xF4DB47, - 0xF4DA3D, 0xF3D833, 0xF3D728, 0xF2D51E, 0xF2D414, 0xF1D20A, 0xF1D100, 0xEFCF00, 0xEDCD00, 0xEBCC01, 0xE9CA01, 0xE7C801, - 0xE5C601, 0xE3C502, 0xE1C302, 0xDFC102, 0xDDBF02, 0xDBBD02, 0xD8BC02, 0xD6BA02, 0xD4B801, 0xD2B601, 0xCFB501, 0xCDB301, - 0xCBB101, 0xC9AF01, 0xC6AD01, 0xC4AA01, 0xC1A801, 0xBFA602, 0xBCA402, 0xBAA102, 0xB79F02, 0xB59D02, 0xB19902, 0xAD9602, - 0xA99202, 0xA58E02, 0xA08B02, 0x9C8702, 0x988302, 0x948002, 0x907C02, 0x8D7A02, 0x8B7802, 0x887602, 0x857402, 0x837102, - 0x806F02, 0x7D6D02, 0x7B6B02, 0x786902, 0xB7E69B, 0xB3E597, 0xAFE393, 0xACE28F, 0xA8E18B, 0xA4DF86, 0xA0DE82, 0x9DDD7E, - 0x99DB7A, 0x95DA76, 0x91D971, 0x8CD76C, 0x88D668, 0x83D463, 0x7FD35E, 0x7AD159, 0x76D055, 0x71CE50, 0x6DCD4B, 0x69CC43, - 0x65CA3A, 0x60C932, 0x5CC72A, 0x58C621, 0x54C419, 0x4FC311, 0x4BC108, 0x47C000, 0x46BE00, 0x46BC00, 0x45BB00, 0x44B900, - 0x44B700, 0x43B500, 0x42B400, 0x42B200, 0x41B000, 0x40AD00, 0x3FAA00, 0x3DA700, 0x3CA400, 0x3BA001, 0x3A9D01, 0x389A01, - 0x379701, 0x369401, 0x349001, 0x338C01, 0x318701, 0x308301, 0x2E7F00, 0x2D7B00, 0x2B7600, 0x2A7200, 0x286E00, 0x276B00, - 0x266700, 0x246400, 0x236000, 0x225D00, 0x215900, 0x1F5600, 0x1E5200, 0x1D4F00, 0xC4F1FF, 0xC1F0FF, 0xBEEFFF, 0xBCEEFF, - 0xB9EDFF, 0xB6EDFF, 0xB3ECFF, 0xB1EBFF, 0xAEEAFF, 0xABE9FF, 0xA6E8FF, 0xA1E6FF, 0x9CE5FF, 0x97E3FF, 0x93E2FF, 0x8EE0FF, - 0x89DFFF, 0x84DDFF, 0x7FDCFF, 0x71D9FF, 0x63D6FF, 0x55D4FF, 0x47D1FF, 0x39CEFF, 0x2BCBFF, 0x1DC9FF, 0x0FC6FF, 0x01C3FF, - 0x01C2FD, 0x01C0FB, 0x01BFF9, 0x01BDF7, 0x00BCF6, 0x00BAF4, 0x00B9F2, 0x00B7F0, 0x00B6EE, 0x00B5EC, 0x00B3EB, 0x00B2E9, - 0x00B1E7, 0x01AFE6, 0x01AEE4, 0x01ADE2, 0x01ABE1, 0x01AADF, 0x01A7DB, 0x01A4D6, 0x02A0D2, 0x029DCE, 0x029AC9, 0x0297C5, - 0x0393C1, 0x0390BC, 0x038DB8, 0x0389B3, 0x0386AF, 0x0282AA, 0x027FA6, 0x027BA1, 0x02789D, 0x017498, 0x017194, 0x016D8F, - 0x91AAFF, 0x8EA8FF, 0x8BA6FF, 0x88A3FF, 0x85A1FF, 0x819FFF, 0x7E9DFF, 0x7B9AFF, 0x7898FF, 0x7596FF, 0x6F90FF, 0x688BFF, - 0x6285FF, 0x5B80FF, 0x557AFF, 0x4E75FF, 0x486FFF, 0x3D69FF, 0x3B64FF, 0x345FFF, 0x2E5BFF, 0x2756FF, 0x2151FF, 0x1A4DFF, - 0x1448FF, 0x0D43FF, 0x073FFF, 0x003AFF, 0x0039FC, 0x0038F8, 0x0138F5, 0x0137F2, 0x0136EE, 0x0135EB, 0x0235E8, 0x0234E4, - 0x0233E1, 0x0232DE, 0x0232DC, 0x0231D9, 0x0231D7, 0x0230D4, 0x0230D2, 0x022FCF, 0x022FCD, 0x022ECA, 0x022DC7, 0x022DC4, - 0x022CC1, 0x022BBE, 0x012BBC, 0x012AB9, 0x0129B6, 0x0129B3, 0x0128B0, 0x0127AD, 0x0127AA, 0x0126A7, 0x0125A4, 0x0025A2, - 0x00249F, 0x00239C, 0x002399, 0x002296, 0xD7B2FF, 0xD3ADFF, 0xCFA8FF, 0xCBA4FF, 0xC79FFF, 0xC29AFF, 0xBE95FF, 0xBA91FF, - 0xB68CFF, 0xB287FF, 0xAF83FF, 0xAD7FFF, 0xAA7CFF, 0xA778FF, 0xA574FF, 0xA270FF, 0x9F6DFF, 0x9D69FF, 0x9A65FF, 0x9861FF, - 0x955CFF, 0x9358FF, 0x9153FF, 0x8E4FFF, 0x8C4AFF, 0x8A46FF, 0x8741FF, 0x853DFF, 0x8436FF, 0x822FFF, 0x8129FF, 0x8022FF, - 0x7E1BFF, 0x7D14FF, 0x7C0EFF, 0x7A07FF, 0x7900FF, 0x7700FB, 0x7500F7, 0x7401F4, 0x7201F0, 0x7001EC, 0x6E01E8, 0x6D02E5, - 0x6A00E3, 0x6902DD, 0x6702D8, 0x6402D3, 0x6202CE, 0x5F02C9, 0x5D01C3, 0x5A01BE, 0x5801B9, 0x5501B4, 0x5301AF, 0x4F01A7, - 0x4B019E, 0x470196, 0x43018E, 0x3F0085, 0x3B007D, 0x370075, 0x33006C, 0x2F0064, + 0xFFFFFF, 0xF1D3B3, 0xD7AE83, 0xBB875D, 0x9B633E, 0x7C492D, 0x5E331F, 0x412116, 0x25110B, 0xD9D9D9, 0xFFEDE5, 0xFFE5D3, + 0xFFD8C6, 0xF8CCBF, 0xF4BFA5, 0xEBB88F, 0xE0A984, 0xD2977B, 0xB3B3B3, 0xFFD6E0, 0xFFDCC8, 0xFFF2B8, 0xCDECCF, 0xC9EEF0, + 0xCEDDFA, 0xE0D2F4, 0xEACFE3, 0x8A8B8A, 0xE4E0AE, 0xCAC783, 0xAAA95F, 0x898B43, 0x6D7134, 0x535629, 0x3A3C1E, 0x232416, + 0x6F6F6F, 0xFFF1B8, 0xFFE08A, 0xF4C95D, 0xDDAF37, 0xC49324, 0x9D7118, 0x74500F, 0x493008, 0x4F4F4F, 0xB9F3E8, 0x82DDCF, + 0x4EC3B5, 0x27A497, 0x168479, 0x0E635C, 0x08443F, 0x032622, 0x242424, 0xF4C0A8, 0xE79B7C, 0xD47657, 0xB9563E, 0x963D2D, + 0x722B22, 0x4F1C18, 0x2B0E0D, 0x000000, 0xFFB0A3, 0xFAF3E8, 0xEFE3D2, 0xE2D1B9, 0xD3BFA2, 0xC2A987, 0xAA906F, 0x8D765C, + 0x6F5C49, 0xFF9A89, 0xFFE0C2, 0xF4C29F, 0xDFA57E, 0xC88962, 0xAA6B49, 0x82503A, 0x5B352A, 0x35201B, 0xFF5541, 0x8D8D8D, + 0xA4A4A4, 0x666666, 0xFF3F24, 0xFE3A1D, 0xFE3416, 0xFE2F0E, 0xFE2907, 0xFE2400, 0xF92300, 0xF42300, 0xEF2200, 0xEA2100, + 0xE52101, 0xE02001, 0xDB1F01, 0xD61F01, 0xD11E01, 0xCA1D01, 0xC31C01, 0xBC1B01, 0xB51A01, 0xAD1900, 0xA61800, 0x9F1700, + 0x981600, 0x911500, 0x8C1400, 0x871300, 0x811300, 0x7C1200, 0x771101, 0x721001, 0x6C1001, 0x670F01, 0x620E01, 0x5F0E01, + 0x5C0D01, 0x580D01, 0x550C01, 0x520C00, 0x4F0B00, 0x4B0B00, 0x480A00, 0x450A00, 0xFFB363, 0xFFB261, 0xFFB160, 0xFFAF5E, + 0xFFAE5D, 0xFFAD5B, 0xFFAC5A, 0xFFAA58, 0xFFA957, 0xFFA855, 0xFFA651, 0xFFA34D, 0xFFA14A, 0xFF9F46, 0xFF9C42, 0xFF9A3E, + 0xFF983B, 0xFF9537, 0xFF9333, 0xFF912D, 0xFF9028, 0xFF8E22, 0xFF8C1C, 0xFF8B17, 0xFF8911, 0xFF870B, 0xFF8606, 0xFF8400, + 0xFC8200, 0xF98100, 0xF67F00, 0xF37E00, 0xF07C01, 0xED7B01, 0xEA7901, 0xE77801, 0xE47601, 0xE17401, 0xDD7201, 0xDA7101, + 0xD66F01, 0xD36D01, 0xCF6B01, 0xCC6A01, 0xC86801, 0xC56601, 0xBF6301, 0xB96001, 0xB35C01, 0xAD5901, 0xA65600, 0xA05300, + 0x9A4F00, 0x944C00, 0x8E4900, 0x8C4800, 0x8A4700, 0x884600, 0x864500, 0x834400, 0x814300, 0x7F4200, 0x7D4100, 0x7B4000, + 0xF7E572, 0xF7E46F, 0xF7E36D, 0xF6E36A, 0xF6E268, 0xF6E165, 0xF6E063, 0xF5E060, 0xF5DF5E, 0xF5DE5B, 0xF5DD51, 0xF4DB47, + 0xF4DA3D, 0xF3D833, 0xF3D728, 0xF2D51E, 0xF2D414, 0xF1D20A, 0xF1D100, 0xEFCF00, 0xEDCD00, 0xEBCC01, 0xE9CA01, 0xE7C801, + 0xE5C601, 0xE3C502, 0xE1C302, 0xDFC102, 0xDDBF02, 0xDBBD02, 0xD8BC02, 0xD6BA02, 0xD4B801, 0xD2B601, 0xCFB501, 0xCDB301, + 0xCBB101, 0xC9AF01, 0xC6AD01, 0xC4AA01, 0xC1A801, 0xBFA602, 0xBCA402, 0xBAA102, 0xB79F02, 0xB59D02, 0xB19902, 0xAD9602, + 0xA99202, 0xA58E02, 0xA08B02, 0x9C8702, 0x988302, 0x948002, 0x907C02, 0x8D7A02, 0x8B7802, 0x887602, 0x857402, 0x837102, + 0x806F02, 0x7D6D02, 0x7B6B02, 0x786902, 0xB7E69B, 0xB3E597, 0xAFE393, 0xACE28F, 0xA8E18B, 0xA4DF86, 0xA0DE82, 0x9DDD7E, + 0x99DB7A, 0x95DA76, 0x91D971, 0x8CD76C, 0x88D668, 0x83D463, 0x7FD35E, 0x7AD159, 0x76D055, 0x71CE50, 0x6DCD4B, 0x69CC43, + 0x65CA3A, 0x60C932, 0x5CC72A, 0x58C621, 0x54C419, 0x4FC311, 0x4BC108, 0x47C000, 0x46BE00, 0x46BC00, 0x45BB00, 0x44B900, + 0x44B700, 0x43B500, 0x42B400, 0x42B200, 0x41B000, 0x40AD00, 0x3FAA00, 0x3DA700, 0x3CA400, 0x3BA001, 0x3A9D01, 0x389A01, + 0x379701, 0x369401, 0x349001, 0x338C01, 0x318701, 0x308301, 0x2E7F00, 0x2D7B00, 0x2B7600, 0x2A7200, 0x286E00, 0x276B00, + 0x266700, 0x246400, 0x236000, 0x225D00, 0x215900, 0x1F5600, 0x1E5200, 0x1D4F00, 0xC4F1FF, 0xC1F0FF, 0xBEEFFF, 0xBCEEFF, + 0xB9EDFF, 0xB6EDFF, 0xB3ECFF, 0xB1EBFF, 0xAEEAFF, 0xABE9FF, 0xA6E8FF, 0xA1E6FF, 0x9CE5FF, 0x97E3FF, 0x93E2FF, 0x8EE0FF, + 0x89DFFF, 0x84DDFF, 0x7FDCFF, 0x71D9FF, 0x63D6FF, 0x55D4FF, 0x47D1FF, 0x39CEFF, 0x2BCBFF, 0x1DC9FF, 0x0FC6FF, 0x01C3FF, + 0x01C2FD, 0x01C0FB, 0x01BFF9, 0x01BDF7, 0x00BCF6, 0x00BAF4, 0x00B9F2, 0x00B7F0, 0x00B6EE, 0x00B5EC, 0x00B3EB, 0x00B2E9, + 0x00B1E7, 0x01AFE6, 0x01AEE4, 0x01ADE2, 0x01ABE1, 0x01AADF, 0x01A7DB, 0x01A4D6, 0x02A0D2, 0x029DCE, 0x029AC9, 0x0297C5, + 0x0393C1, 0x0390BC, 0x038DB8, 0x0389B3, 0x0386AF, 0x0282AA, 0x027FA6, 0x027BA1, 0x02789D, 0x017498, 0x017194, 0x016D8F, + 0x91AAFF, 0x8EA8FF, 0x8BA6FF, 0x88A3FF, 0x85A1FF, 0x819FFF, 0x7E9DFF, 0x7B9AFF, 0x7898FF, 0x7596FF, 0x6F90FF, 0x688BFF, + 0x6285FF, 0x5B80FF, 0x557AFF, 0x4E75FF, 0x486FFF, 0x3D69FF, 0x3B64FF, 0x345FFF, 0x2E5BFF, 0x2756FF, 0x2151FF, 0x1A4DFF, + 0x1448FF, 0x0D43FF, 0x073FFF, 0x003AFF, 0x0039FC, 0x0038F8, 0x0138F5, 0x0137F2, 0x0136EE, 0x0135EB, 0x0235E8, 0x0234E4, + 0x0233E1, 0x0232DE, 0x0232DC, 0x0231D9, 0x0231D7, 0x0230D4, 0x0230D2, 0x022FCF, 0x022FCD, 0x022ECA, 0x022DC7, 0x022DC4, + 0x022CC1, 0x022BBE, 0x012BBC, 0x012AB9, 0x0129B6, 0x0129B3, 0x0128B0, 0x0127AD, 0x0127AA, 0x0126A7, 0x0125A4, 0x0025A2, + 0x00249F, 0x00239C, 0x002399, 0x002296, 0xD7B2FF, 0xD3ADFF, 0xCFA8FF, 0xCBA4FF, 0xC79FFF, 0xC29AFF, 0xBE95FF, 0xBA91FF, + 0xB68CFF, 0xB287FF, 0xAF83FF, 0xAD7FFF, 0xAA7CFF, 0xA778FF, 0xA574FF, 0xA270FF, 0x9F6DFF, 0x9D69FF, 0x9A65FF, 0x9861FF, + 0x955CFF, 0x9358FF, 0x9153FF, 0x8E4FFF, 0x8C4AFF, 0x8A46FF, 0x8741FF, 0x853DFF, 0x8436FF, 0x822FFF, 0x8129FF, 0x8022FF, + 0x7E1BFF, 0x7D14FF, 0x7C0EFF, 0x7A07FF, 0x7900FF, 0x7700FB, 0x7500F7, 0x7401F4, 0x7201F0, 0x7001EC, 0x6E01E8, 0x6D02E5, + 0x6A00E3, 0x6902DD, 0x6702D8, 0x6402D3, 0x6202CE, 0x5F02C9, 0x5D01C3, 0x5A01BE, 0x5801B9, 0x5501B4, 0x5301AF, 0x4F01A7, + 0x4B019E, 0x470196, 0x43018E, 0x3F0085, 0x3B007D, 0x370075, 0x33006C, 0x2F0064, ] static let dynamicReferences: [[Int]] = [ diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift index 3f2d796798..d8eaf075e0 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift @@ -20,7 +20,9 @@ public enum MCOImagePalette { return fixed[profile][reference] } - public static func white(profile: Int) -> Int { 0 } + public static func white(profile: Int) -> Int { + 0 + } public static func black(profile: Int) -> Int { guard (0..= firstDynamicProfile ? dynamicReferences[profile - firstDynamicProfile] : Array(fixed[profile].indices) } - static func bits(_ profile: Int) -> Int { MCOImageBitReader.width(count(profile: profile) - 1) } + static func bits(_ profile: Int) -> Int { + MCOImageBitReader.width(count(profile: profile) - 1) + } } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift index bf86400dd3..0cce5f046c 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift @@ -3,7 +3,9 @@ extension MCOImageV3Codec.Decoder { var pixels = Array(repeating: 0, count: count) for bit in 0.. 0, length <= count - position else { throw MCOImageCodecError.damaged } - for offset in 0..= minimumMatch else { throw MCOImageCodecError.damaged } let distance = try reader.range(result.count - 1) + 1 let length = try reader.range(remaining - minimumMatch) + minimumMatch - for _ in 0.. [Int] { let virtual = try reader.read(1) != 0 var pixels = Array(repeating: 0, count: count) - if !virtual { for x in 0.. Int { try implicitWhite ? MCOImagePalette.white(profile: profile) : color() } + mutating func background() throws -> Int { + try implicitWhite ? MCOImagePalette.white(profile: profile) : color() + } mutating func pixels(container: MCOImageV3Codec.Container, algorithm: MCOImageV3Codec.Algorithm, scan: Int, context: Int) throws -> [Int] { switch container { case .block, .compactBlock: - return MCOImageV3Codec.fromScan(try block(width: width, height: height, algorithm: algorithm, scan: scan), width: width, height: height, scan: scan) + return try MCOImageV3Codec.fromScan(block(width: width, height: height, algorithm: algorithm, scan: scan), width: width, height: height, scan: scan) case .boundsBlock, .compactBoundsBlock: let background = try background() let bounds = try geometry(compact: container == .compactBoundsBlock) @@ -29,7 +31,7 @@ extension MCOImageV3Codec.Decoder { let lowBits = min(bits, MCOImageV3Codec.containerShift) guard context < 1 << lowBits else { throw MCOImageCodecError.damaged } let ref = try context | reader.read(bits - lowBits) << lowBits - return Array(repeating: try MCOImagePalette.ref(fromStored: ref, profile: profile), count: width * height) + return try Array(repeating: MCOImagePalette.ref(fromStored: ref, profile: profile), count: width * height) case .solidRects: let background = try background() let palette = try localPalette() diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Encode.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Encode.swift index aa4df9098c..e71e7cc6a8 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Encode.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Encode.swift @@ -6,7 +6,9 @@ extension MCOImageV3Codec { (0.. 0 && indexes[start..<(start + rowLength)].elementsEqual(indexes[(start - rowLength).. 0 { writer.write(same ? 1 : 0, 1) } - if !same { for index in indexes[start..<(start + rowLength)] { writer.write(index, bits) } } + if !same { for index in indexes[start..<(start + rowLength)] { + writer.write(index, bits) + } } } - } else { for index in indexes { writer.write(index, bits) } } + } else { for index in indexes { + writer.write(index, bits) + } } } private static func writeSparse(_ pixels: [Int], background: Int, profile: Int, writer: inout MCOImageBitWriter) throws { @@ -144,7 +158,9 @@ extension MCOImageV3Codec { while position < pixels.count { if pixels[position] == background { position += 1; continue } var end = position + 1 - while end < pixels.count && pixels[end] == pixels[position] { end += 1 } + while end < pixels.count, pixels[end] == pixels[position] { + end += 1 + } runs.append((position, end - position, pixels[position])) position = end } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift index 82307cc86a..94ed3d87a0 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift @@ -43,11 +43,15 @@ extension MCOImageV3Codec.Decoder { var refs: [Int] = [] switch descriptor { case 0: - for ref in 0.. before else { throw MCOImageCodecError.damaged } } return refs @@ -94,7 +100,7 @@ extension MCOImageV3Codec.Decoder { let index = try reader.read(MCOImageBitReader.width(banks.count - 1)) guard banks.indices.contains(index) else { throw MCOImageCodecError.damaged } used.insert(index) - refs.append(try (banks[index] << 6) | reader.read(6)) + try refs.append((banks[index] << 6) | reader.read(6)) } guard used.count == banks.count else { throw MCOImageCodecError.damaged } return refs diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Rows.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Rows.swift index 3a87136dd0..d842692ce9 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Rows.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Rows.swift @@ -18,15 +18,21 @@ extension MCOImageV3Codec.Decoder { } func copyRow(_ pixels: inout [Int], row: Int, rowLength: Int, predictor: Int = 0, virtual: Bool) { - for x in 0.. [Int] { var pixels = Array(repeating: 0, count: count) - for x in 0.. [Int] { var positions: [Int] = [] - for x in 0.. previousEnd, x + length <= rowLength else { throw MCOImageCodecError.damaged } - for offset in x..<(x + length) { pixels[start + offset] = try rowValue(bits, maximum: maximum) } + for offset in x..<(x + length) { + pixels[start + offset] = try rowValue(bits, maximum: maximum) + } previousEnd = x + length - 1 } } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift index bbcf05634b..a4d41d5f8b 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift @@ -29,8 +29,13 @@ public enum MCOImageV3Codec { case bitplanes = 8, adaptiveBitplanes = 9, directBitplanes = 10, compactRowDelta = 11, directRowDelta = 12, rowDelta = 13 case varRle = 14, varSparse = 15 - var compact: Bool { self == .rawGlobal || self == .rawLocal || self == .biColor } - var usesBackground: Bool { self == .sparse || self == .varSparse || self == .biColor } + var compact: Bool { + self == .rawGlobal || self == .rawLocal || self == .biColor + } + + var usesBackground: Bool { + self == .sparse || self == .varSparse || self == .biColor + } } struct Decoder { @@ -129,7 +134,9 @@ public enum MCOImageV3Codec { static func fromScan(_ linear: [Int], width: Int, height: Int, scan: Int) -> [Int] { if scan == 0 { return linear } var result = Array(repeating: 0, count: linear.count) - for (position, index) in scanIndexes(width: width, height: height, scan: scan).enumerated() { result[index] = linear[position] } + for (position, index) in scanIndexes(width: width, height: height, scan: scan).enumerated() { + result[index] = linear[position] + } return result } } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift index 906fb7aee9..8fe8bf358d 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift @@ -6,12 +6,16 @@ struct MCOImageV4BitReader { private static let bitsPerByte = 8 private static let varUIntBytes = 5 private static let varUIntPayloadBits = 7 - private static let varUIntPayloadMask = 0x7f + private static let varUIntPayloadMask = 0x7F private static let varUIntContinuation = 0x80 - init(_ data: Data) { bytes = Array(data) } + init(_ data: Data) { + bytes = Array(data) + } - var remaining: Int { bytes.count * Self.bitsPerByte - offset } + var remaining: Int { + bytes.count * Self.bitsPerByte - offset + } mutating func read(_ bits: Int) throws -> Int { guard bits >= 0, bits <= Int.bitWidth - 1, bits <= remaining else { throw MCOImageCodecError.damaged } @@ -23,7 +27,9 @@ struct MCOImageV4BitReader { return value } - mutating func bit() throws -> Bool { try read(1) != 0 } + mutating func bit() throws -> Bool { + try read(1) != 0 + } mutating func signed(_ bits: Int) throws -> Int { let value = try read(bits) @@ -55,7 +61,7 @@ struct MCOImageV4BitReader { mutating func data(_ count: Int) throws -> Data { guard count >= 0, count <= remaining / Self.bitsPerByte else { throw MCOImageCodecError.damaged } - return Data(try (0..> headerBits, headerBits) writer.compact(bytes.count - 2) - for byte in bytes.dropFirst(2) { writer.write(Int(byte), field.byteBits) } + for byte in bytes.dropFirst(2) { + writer.write(Int(byte), field.byteBits) + } writer.write(MCOImageV4Parser.Opcode.end.rawValue, field.opcodeBits) return Data([bytes[0]]) + writer.data } @@ -31,7 +33,7 @@ extension MCOImageV4Codec { private static func writeRasterDimensions(_ width: Int, _ height: Int, writer: inout MCOImageBitWriter) { let field = MCOImageV4Parser.Field.self let squareMode = 0, smallMode = 1, mediumMode = 2, extendedMode = 3 - if width == height && width <= field.mediumDimensionMaximum { + if width == height, width <= field.mediumDimensionMaximum { writer.write(squareMode, field.modeBits) writer.write(width - 1, field.mediumDimensionBits) } else if max(width, height) <= field.smallDimensionMaximum { diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Extended.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Extended.swift index 003b4979ae..ad4e6d472e 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Extended.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Extended.swift @@ -11,7 +11,7 @@ extension MCOImageV4Parser { history: [MCOImageFigure], nested: Bool, style: inout MCOImageV4Style, alignment: inout Int, fontSize: inout Int ) throws -> [MCOImageFigure] { - let opcode = Extended(rawValue: try reader.read(Field.opcodeBits))! + let opcode = try Extended(rawValue: reader.read(Field.opcodeBits))! switch opcode { case .style, .repeatBack, .repeatColors, .dots, .group: break default: try consume(1) @@ -69,17 +69,17 @@ extension MCOImageV4Parser { return [previous.translated(x: delta.x, y: delta.y, style: style)] case .repeatColors: return try repeatedColors(history: history, style: &style) case .dots: return try dots(style: style) - case .pathOrthogonal: return [try orthogonalPath(style: style)] - case .pathBounds: return [try boundsPath(delta: false, style: style)] - case .pathBoundsDelta: return [try boundsPath(delta: true, style: style)] + case .pathOrthogonal: return try [orthogonalPath(style: style)] + case .pathBounds: return try [boundsPath(delta: false, style: style)] + case .pathBoundsDelta: return try [boundsPath(delta: true, style: style)] case .escape: let textCommand = 0 guard try reader.read(Field.opcodeBits) == textCommand else { throw MCOImageCodecError.unsupported } - return [try text(style: style, alignment: &alignment, fontSize: &fontSize)] + return try [text(style: style, alignment: &alignment, fontSize: &fontSize)] case .raster: let mixedMode = 1 guard mode == mixedMode, !nested else { throw MCOImageCodecError.damaged } - return [try raster()] + return try [raster()] case .group: let count = try reader.compact() + 1 guard groupDepth < Field.maximumGroupDepth else { throw MCOImageCodecError.unsupported } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Figures.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Figures.swift index 97944e437b..485bf3ba30 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Figures.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Figures.swift @@ -34,7 +34,7 @@ extension MCOImageV4Parser { mutating func pointSequence(count: Int) throws -> [MCOImageV4Point] { let bits = try Field.shortWidths[reader.read(Field.shortSelectorBits)] - var points = [try point()] + var points = try [point()] for _ in 1..= 0, next.x < boundsWidth, next.y >= 0, next.y < boundsHeight else { throw MCOImageCodecError.damaged } @@ -65,7 +64,7 @@ extension MCOImageV4Parser { let minimumStepBits = shortBits.map { 2 * $0 } ?? (xBits + yBits) guard count - 1 <= reader.remaining / minimumStepBits else { throw MCOImageCodecError.damaged } try consume(count) - var points = [try point()] + var points = try [point()] while points.count < count { let next: MCOImageV4Point if let shortBits { diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift index bb682814df..61bdc4f10a 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift @@ -43,7 +43,9 @@ struct MCOImageV4Parser { var remainingFigures = Field.maximumExpandedFigures var groupDepth = 0 - init(_ data: Data) { reader = MCOImageV4BitReader(data) } + init(_ data: Data) { + reader = MCOImageV4BitReader(data) + } mutating func decode() throws -> MCOImageV4Document { mode = try reader.read(Field.modeBits) @@ -72,16 +74,16 @@ struct MCOImageV4Parser { guard flags & ~Field.knownTailFlags == 0 else { throw MCOImageCodecError.damaged } if flags & Field.targetFlag != 0 { let count = try reader.varUInt() - guard count > 0, let name = String(data: try reader.data(count), encoding: .utf8) else { + guard count > 0, let name = try String(data: reader.data(count), encoding: .utf8) else { throw MCOImageCodecError.damaged } targetName = name } if flags & Field.replyFlag != 0 { - replyTimestamp = UInt32(try reader.read(Field.byteBits)) - | UInt32(try reader.read(Field.byteBits)) << Field.byteBits - | UInt32(try reader.read(Field.byteBits)) << (2 * Field.byteBits) - | UInt32(try reader.read(Field.byteBits)) << (3 * Field.byteBits) + replyTimestamp = try UInt32(reader.read(Field.byteBits)) + | UInt32(reader.read(Field.byteBits)) << Field.byteBits + | UInt32(reader.read(Field.byteBits)) << (2 * Field.byteBits) + | UInt32(reader.read(Field.byteBits)) << (3 * Field.byteBits) } guard reader.remaining == 0 else { throw MCOImageCodecError.damaged } } @@ -95,7 +97,7 @@ struct MCOImageV4Parser { var figures: [MCOImageFigure] = [] var history: [MCOImageFigure] = [] while count == nil || figures.count < count! { - let opcode = Opcode(rawValue: try reader.read(Field.opcodeBits))! + let opcode = try Opcode(rawValue: reader.read(Field.opcodeBits))! var next: [MCOImageFigure] = [] switch opcode { case .end: @@ -114,7 +116,7 @@ struct MCOImageV4Parser { next = try extended(history: history, nested: count != nil, style: &style, alignment: &alignment, fontSize: &fontSize) default: try consume(1) - next = [try figure(opcode, style: style)] + next = try [figure(opcode, style: style)] } if let count, next.count > count - figures.count { throw MCOImageCodecError.damaged } for figure in next { @@ -155,7 +157,9 @@ struct MCOImageV4Parser { } } - mutating func optionalColor() throws -> Int? { try reader.bit() ? color() : nil } + mutating func optionalColor() throws -> Int? { + try reader.bit() ? color() : nil + } mutating func color() throws -> Int { try MCOImagePalette.ref(fromStored: reader.read(colorBits), profile: profile) @@ -176,9 +180,13 @@ struct MCOImageV4Parser { return try MCOImageV4Point(x: reader.signed(shortBits ?? (xBits + 1)), y: reader.signed(shortBits ?? (yBits + 1))) } - func margin(_ size: Int) -> Int { min(Field.maximumOverscan, max(1, (size + Field.overscanDivisor - 1) / Field.overscanDivisor)) } + func margin(_ size: Int) -> Int { + min(Field.maximumOverscan, max(1, (size + Field.overscanDivisor - 1) / Field.overscanDivisor)) + } - static func bits(_ maximum: Int) -> Int { max(1, Int.bitWidth - maximum.leadingZeroBitCount) } + static func bits(_ maximum: Int) -> Int { + max(1, Int.bitWidth - maximum.leadingZeroBitCount) + } mutating func consume(_ count: Int) throws { guard count <= remainingFigures else { throw MCOImageCodecError.unsupported } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift index 48574a09d8..ef2da0a42f 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift @@ -12,7 +12,9 @@ struct MCOTextBitReader { limit = bitLength } - var remaining: Int { limit - offset } + var remaining: Int { + limit - offset + } mutating func read(_ count: Int) throws -> Int { guard count >= 0, count < Int.bitWidth, count <= remaining else { throw MCOImageCodecError.damaged } @@ -24,7 +26,9 @@ struct MCOTextBitReader { return value } - mutating func bit() throws -> Bool { try read(1) != 0 } + mutating func bit() throws -> Bool { + try read(1) != 0 + } mutating func headerField() throws -> Int { let shortBits = 3 diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift index e38b16bd71..584e20186a 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift @@ -12,7 +12,7 @@ struct MCOTextDecoder { static let rawPaddingBits = 4 static let predictionCount = 4 static let space: UInt32 = 0x20 - static let lineFeed: UInt32 = 0x0a + static let lineFeed: UInt32 = 0x0A } private enum Context { case start, punctuation, symbol } @@ -26,7 +26,9 @@ struct MCOTextDecoder { private var capitals = false private var output = String.UnicodeScalarView() - init(_ data: Data, bitLength: Int) throws { reader = try MCOTextBitReader(data, bitLength: bitLength) } + init(_ data: Data, bitLength: Int) throws { + reader = try MCOTextBitReader(data, bitLength: bitLength) + } mutating func decode() throws -> String { guard try reader.headerField() == Field.version else { throw MCOImageCodecError.unsupported } @@ -52,7 +54,9 @@ struct MCOTextDecoder { languageB == nil || MCOTextModels.all.indices.contains(languageB!) else { throw MCOImageCodecError.damaged } guard generation == MCOTextModels.generation else { throw MCOImageCodecError.unsupported } language = languageA - while reader.remaining > 0 { try token() } + while reader.remaining > 0 { + try token() + } guard !shift else { throw MCOImageCodecError.damaged } return String(output) } @@ -78,7 +82,7 @@ struct MCOTextDecoder { try emit(model.primary[index], model: model) case 2: try requireNoShift() - let rune = MCOTextModels.punctuation[try reader.read(Field.symbolBits)] + let rune = try MCOTextModels.punctuation[reader.read(Field.symbolBits)] try append(rune) if rune == Field.lineFeed { reset() } else if rune == Field.space { if context != .symbol { reset() } @@ -102,7 +106,9 @@ struct MCOTextDecoder { private mutating func tokenPrefix() throws -> Int { let maximumPrefixLength = 6 - for count in 0.. String { guard count <= reader.remaining / Field.byteBits else { throw MCOImageCodecError.damaged } - let bytes = try (0..> shift) & 1) } + for shift in 0..> shift) & 1) + } } mutating func compact(_ value: Int) { @@ -106,19 +108,23 @@ struct MCOImageV4CodecTests { put(7, 3) var remaining = value repeat { - let low = remaining & 0x7f + let low = remaining & 0x7F remaining >>= 7 put(low | (remaining == 0 ? 0 : 0x80), 8) } while remaining != 0 } } - mutating func dot() { put(4, 4); put(1, 2); put(1, 2) } + mutating func dot() { + put(4, 4); put(1, 2); put(1, 2) + } mutating func body() -> Data { put(0, 4) var bytes = [UInt8](repeating: 0, count: (bits.count + 7) / 8) - for (index, bit) in bits.enumerated() where bit != 0 { bytes[index / 8] |= 1 << (index % 8) } + for (index, bit) in bits.enumerated() where bit != 0 { + bytes[index / 8] |= 1 << (index % 8) + } return Data([0] + bytes) } } @@ -136,7 +142,9 @@ struct MCOImageV4CodecTests { "strokeWidth": style.strokeWidth] } - private func point(_ point: MCOImageV4Point) -> [Int] { [point.x, point.y] } + private func point(_ point: MCOImageV4Point) -> [Int] { + [point.x, point.y] + } private func dump(_ figure: MCOImageFigure, canvasWidth: Int) -> [String: Any] { var result: [String: Any] = ["style": dump(figure.style)] diff --git a/MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift index 5203745ef2..4f6c97161c 100644 --- a/MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift @@ -1,9 +1,9 @@ import Foundation -import Testing @testable import MC1Services +import Testing struct MCOTextCodecTests { - @Test func frozenGenerationZeroReferenceVectors() throws { + @Test func `frozen generation zero reference vectors`() throws { let url = try #require(Bundle.module.url(forResource: "MCOTextFixtures", withExtension: "json", subdirectory: "Fixtures")) let root = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) let fixtures = try #require(root["fixtures"] as? [[String: Any]]) @@ -17,26 +17,28 @@ struct MCOTextCodecTests { } } - @Test func rawUTF8DoesNotRequireKnownModelGeneration() throws { + @Test func `raw UTF 8 does not require known model generation`() throws { let bits = [0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0] let header = bytes(bits) #expect(try MCOTextCodec.decode(header + Data("Help".utf8), bitLength: 48) == "Help") } - @Test func rejectsPendingShiftAndInvalidUTF8() { + @Test func `rejects pending shift and invalid UTF 8`() { // Version 1, generation 0, English/no partner, then an unfinished SHIFT. let shift = [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0] #expect(throws: MCOImageCodecError.damaged) { try MCOTextCodec.decode(bytes(shift), bitLength: shift.count) } #expect(throws: MCOImageCodecError.damaged) { - try MCOTextCodec.decode(Data([0x23, 0x90, 0xff]), bitLength: 24) + try MCOTextCodec.decode(Data([0x23, 0x90, 0xFF]), bitLength: 24) } } private func bytes(_ bits: [Int]) -> Data { var bytes = [UInt8](repeating: 0, count: (bits.count + 7) / 8) - for (index, bit) in bits.enumerated() where bit != 0 { bytes[index / 8] |= 1 << (7 - index % 8) } + for (index, bit) in bits.enumerated() where bit != 0 { + bytes[index / 8] |= 1 << (7 - index % 8) + } return Data(bytes) } } diff --git a/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift b/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift index e540442ae8..108e1ea291 100644 --- a/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift +++ b/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift @@ -7,7 +7,7 @@ import Testing @Suite("RoomMessageBubble accessibility label") struct RoomMessageBubbleA11yLabelTests { @Test(arguments: ["im3:g/5WjAL`NA", "im4:AAAAA", "im5:unknown", "im3:"]) - func imageMessagesAnnounceTheirLocalizedContent(_ text: String) throws { + func `image messages announce their localized content`(_ text: String) throws { let message = RoomMessageDTO(sessionID: UUID(), authorKeyPrefix: Data([0xAA]), authorName: "Alice", text: text, timestamp: 100) let content = try #require(MCOImageCodec.content(from: text)) diff --git a/MC1Tests/Views/Chats/MCOImageGeometryTests.swift b/MC1Tests/Views/Chats/MCOImageGeometryTests.swift index 011ef1a480..611826b057 100644 --- a/MC1Tests/Views/Chats/MCOImageGeometryTests.swift +++ b/MC1Tests/Views/Chats/MCOImageGeometryTests.swift @@ -1,20 +1,22 @@ +@testable import MC1 import MC1Services import SwiftUI import Testing -@testable import MC1 @Suite("MCOimg rendering geometry") @MainActor struct MCOImageGeometryTests { - private func point(_ x: Int, _ y: Int) -> MCOImageV4Point { .init(x: x, y: y) } + private func point(_ x: Int, _ y: Int) -> MCOImageV4Point { + .init(x: x, y: y) + } - @Test func vectorAnchorsUseCellCentersWithoutClampingOverscan() { + @Test func `vector anchors use cell centers without clamping overscan`() { #expect(MCOImageGeometry.point(point(-1, 4)) == CGPoint(x: -0.5, y: 4.5)) let rect = MCOImageGeometry.rectangle(point(0, 0), point(4, 4), point(4, 0)) #expect(rect.boundingRect == CGRect(x: 0.5, y: 0.5, width: 4, height: 4)) } - @Test func ellipseUsesDiameterAndPerpendicularThirdPoint() throws { + @Test func `ellipse uses diameter and perpendicular third point`() throws { let ellipse = try #require(MCOImageGeometry.ellipse(point(0, 2), point(8, 2), point(4, 4))) #expect(ellipse.closed) #expect(ellipse.path.boundingRect == CGRect(x: 0.5, y: 0.5, width: 8, height: 4)) @@ -23,7 +25,7 @@ struct MCOImageGeometryTests { #expect(MCOImageGeometry.ellipse(point(0, 0), point(0, 0), point(1, 1))?.path == nil) } - @Test func waveDepthIsTheVisibleMidpointDisplacement() throws { + @Test func `wave depth is the visible midpoint displacement`() throws { let path = try #require(MCOImageGeometry.wave(point(0, 0), point(8, 0), depth: 2)) var control: CGPoint? path.forEach { if case let .quadCurve(_, value) = $0 { control = value } } @@ -31,7 +33,7 @@ struct MCOImageGeometryTests { #expect(path.boundingRect.maxY == 2.5) } - @Test func rasterPaintsExactProfileColorsAndTransparency() throws { + @Test func `raster paints exact profile colors and transparency`() throws { let image = MCOImageRaster(width: 2, height: 1, profile: 0, pixels: [0, 1], transparentColor: 0) let renderer = ImageRenderer(content: MCOImageRenderer(content: .raster(image)).frame(width: 2, height: 1)) renderer.scale = 1 @@ -39,8 +41,8 @@ struct MCOImageGeometryTests { var bytes = [UInt8](repeating: 0, count: 8) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmap = try #require(CGContext(data: &bytes, width: 2, height: 1, bitsPerComponent: 8, - bytesPerRow: 8, space: colorSpace, - bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) + bytesPerRow: 8, space: colorSpace, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) bitmap.draw(rendered, in: CGRect(x: 0, y: 0, width: 2, height: 1)) #expect(Array(bytes[0..<4]) == [0, 0, 0, 0]) #expect(Array(bytes[4..<8]) == [0, 0, 0, 255]) diff --git a/MC1Tests/Views/Chats/MCOImageMessageTests.swift b/MC1Tests/Views/Chats/MCOImageMessageTests.swift index bcf56299b2..5d00c2e48a 100644 --- a/MC1Tests/Views/Chats/MCOImageMessageTests.swift +++ b/MC1Tests/Views/Chats/MCOImageMessageTests.swift @@ -1,18 +1,18 @@ import Foundation +@testable import MC1 import MC1Services import Testing -@testable import MC1 @Suite("MCOimg message content") struct MCOImageMessageTests { - @Test func encodedPixelsBakeWithoutTextPreviewsOrTranslation() throws { + @Test func `encoded pixels bake without text previews or translation`() throws { let image = MCOImageRaster(width: 2, height: 2, profile: 0, pixels: [0, 1, 1, 0]) let body = try MCOImageV3Codec.encode(image, nonce: 42) let text = try MCOImageCodec.text(fromAppPayload: Data([MCOImageCodec.v3Subtype]) + body) let message = MessageFragmentBuilderFixtures.makeMessage(text: text) let inputs = MessageFragmentBuilderFixtures.makeMinimalInputs(messageID: message.id) let item = MessageFragmentBuilder.makeItem(for: message, inputs: inputs, - envInputs: MessageFragmentBuilderFixtures.makeEnvInputs()) + envInputs: MessageFragmentBuilderFixtures.makeEnvInputs()) #expect(item.content == [.mcoImage(.raster(image))]) #expect(!item.shouldRequestPreviewFetch) #expect(item.translation == nil) @@ -23,7 +23,7 @@ struct MCOImageMessageTests { #expect(layout.siblings.isEmpty) } - @Test func terminalPlaceholdersDifferAndParticipateInItemIdentity() { + @Test func `terminal placeholders differ and participate in item identity`() { let id = UUID() let unsupported = MessageFragmentBuilderFixtures.makeMessage(id: id, text: "im5:anything") let damaged = MessageFragmentBuilderFixtures.makeMessage(id: id, text: "im3:") diff --git a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift index 82aca9b383..77065595f3 100644 --- a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift @@ -1,11 +1,11 @@ +@testable import MC1 import MC1Services import Testing -@testable import MC1 @Suite("Pixel paint drafts") @MainActor struct PixelPaintDraftTests { - @Test func paintingInterpolatesAcrossTheCanvas() { + @Test func `painting interpolates across the canvas`() { let draft = PixelPaintDraft() draft.paint(x: 0, y: 0) draft.paint(x: PixelPaintDraft.side - 1, y: PixelPaintDraft.side - 1) @@ -18,7 +18,7 @@ struct PixelPaintDraftTests { #expect(draft.image == painted) } - @Test func blankCanvasIsAdmittedOnceAndClears() async throws { + @Test func `blank canvas is admitted once and clears`() async { let draft = PixelPaintDraft() let probe = AdmissionProbe() await probe.submit(draft)?.value @@ -27,7 +27,7 @@ struct PixelPaintDraftTests { #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) } - @Test func paintAndClearDuringSubmitDoNotChangeTheCapturedRaster() async throws { + @Test func `paint and clear during submit do not change the captured raster`() async { let draft = PixelPaintDraft() draft.paint(x: 1, y: 2) draft.endStroke() @@ -51,7 +51,7 @@ struct PixelPaintDraftTests { #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) } - @Test func cancelBeforeAdmissionSendsNothingAndLeavesABlankCanvas() async throws { + @Test func `cancel before admission sends nothing and leaves A blank canvas`() async { let draft = PixelPaintDraft() draft.paint(x: 4, y: 5) draft.endStroke() @@ -74,7 +74,7 @@ struct PixelPaintDraftTests { #expect(!draft.isSubmitting) } - @Test func rejectedAdmissionKeepsPixelsAndClearsTheConversationSendError() async throws { + @Test func `rejected admission keeps pixels and clears the conversation send error`() async { let draft = PixelPaintDraft() draft.paint(x: 2, y: 3) draft.endStroke() @@ -94,7 +94,7 @@ struct PixelPaintDraftTests { #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) } - @Test func disconnectAfterTheTapKeepsPixelsAndDoesNotAdmit() async throws { + @Test func `disconnect after the tap keeps pixels and does not admit`() async { let draft = PixelPaintDraft() draft.paint(x: 6, y: 1) draft.endStroke() @@ -116,7 +116,7 @@ struct PixelPaintDraftTests { #expect(!draft.isAdmitting) } - @Test func encodeFailureKeepsPixelsAndSetsTheEncodeTitle() async throws { + @Test func `encode failure keeps pixels and sets the encode title`() async { let draft = PixelPaintDraft() draft.paint(x: 1, y: 1) draft.endStroke() @@ -132,7 +132,7 @@ struct PixelPaintDraftTests { #expect(!draft.isSubmitting) } - @Test func oversizedPayloadKeepsPixelsAndSetsTheSizeTitle() async throws { + @Test func `oversized payload keeps pixels and sets the size title`() async { let draft = PixelPaintDraft() draft.paint(x: 2, y: 2) draft.endStroke() @@ -148,7 +148,7 @@ struct PixelPaintDraftTests { #expect(!draft.isSubmitting) } - @Test func canvasEdgesDoNotWrapIntoOtherRows() { + @Test func `canvas edges do not wrap into other rows`() { let draft = PixelPaintDraft() draft.paint(x: PixelPaintDraft.side, y: 0) draft.paint(x: -1, y: 0) diff --git a/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift index fa4a8c4fec..5a0bfc5ba5 100644 --- a/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift @@ -1,20 +1,22 @@ import Foundation +@testable import MC1 @testable import MC1Services import SwiftUI import Testing import UIKit -@testable import MC1 private struct AccessibilityDump: Error, CustomStringConvertible { var description: String - init(_ description: String) { self.description = description } + init(_ description: String) { + self.description = description + } } @Suite("Pixel paint presentation", .serialized) @MainActor struct PixelPaintPresentationTests { - @Test func fullScreenCoverBlocksDismissalAndCancelDiscardsPixels() async throws { - let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + @Test func `full screen cover blocks dismissal and cancel discards pixels`() async throws { + let appState = try AppState(modelContainer: PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) appState.connectionManager.setTestState(connectionState: .ready) let draft = PixelPaintDraft() let presentation = Presentation() @@ -61,8 +63,8 @@ struct PixelPaintPresentationTests { #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) } - @Test func sendAdmitsOnceWithoutChangingTheTextDraft() async throws { - let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + @Test func `send admits once without changing the text draft`() async throws { + let appState = try AppState(modelContainer: PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) appState.connectionManager.setTestState(connectionState: .ready) let draft = PixelPaintDraft() draft.paint(x: 2, y: 3) @@ -100,8 +102,8 @@ struct PixelPaintPresentationTests { #expect(draft.image != snapshot) } - @Test func rejectedAdmissionShowsOneCoverAlertAndKeepsPixels() async throws { - let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + @Test func `rejected admission shows one cover alert and keeps pixels`() async throws { + let appState = try AppState(modelContainer: PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) appState.connectionManager.setTestState(connectionState: .ready) let draft = PixelPaintDraft() draft.paint(x: 4, y: 1) @@ -132,8 +134,8 @@ struct PixelPaintPresentationTests { #expect(model.text == SendModel.originalText) } - @Test func disconnectAfterTheTapShowsOneCoverAlertAndKeepsPixels() async throws { - let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + @Test func `disconnect after the tap shows one cover alert and keeps pixels`() async throws { + let appState = try AppState(modelContainer: PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) appState.connectionManager.setTestState(connectionState: .ready) let draft = PixelPaintDraft() draft.paint(x: 5, y: 6) @@ -189,8 +191,8 @@ struct PixelPaintPresentationTests { #expect(presentedController(in: window) != nil) } - @Test func hardwareReturnSendsOnlyNonEmptyText() async throws { - let appState = AppState(modelContainer: try PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + @Test func `hardware return sends only non empty text`() async throws { + let appState = try AppState(modelContainer: PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) appState.connectionManager.setTestState(connectionState: .ready) let model = InputModel() model.text = String(repeating: "a", count: InputModel.maxBytes + 1) @@ -311,7 +313,7 @@ struct PixelPaintPresentationTests { } } - private func host(_ view: Content) throws -> UIWindow { + private func host(_ view: some View) throws -> UIWindow { let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) let window = UIWindow(windowScene: scene) let controller = UIHostingController(rootView: view) diff --git a/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift b/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift index 1460659203..161e3c2960 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift @@ -16,18 +16,16 @@ struct ChannelSendSerializationTests { let (session, transport) = try await startSession() let first = Task { try await send(session: session, binary: binary, - channel: Self.firstChannel, text: "first", timestamp: Self.timestamp, - floodScope: .scope(Self.firstScope) - ) + channel: Self.firstChannel, text: "first", timestamp: Self.timestamp, + floodScope: .scope(Self.firstScope)) } try await waitForFrameCount(2, transport: transport) #expect(await transport.sentData[1] == PacketBuilder.setFloodScope(Self.firstScope.scopeKey())) let second = Task { try await send(session: session, binary: binary, - channel: Self.secondChannel, text: "second", timestamp: Self.timestamp, - floodScope: .scope(Self.secondScope) - ) + channel: Self.secondChannel, text: "second", timestamp: Self.timestamp, + floodScope: .scope(Self.secondScope)) } let selection = Task { try await session.setFloodScope(Self.selectedScope) } try await waitForSerializerWaiters(2, session: session) @@ -35,9 +33,8 @@ struct ChannelSendSerializationTests { await transport.simulateOK() try await waitForFrameCount(3, transport: transport) - #expect(await transport.sentData[2] == (try command(binary: binary, - channel: Self.firstChannel, text: "first", timestamp: Self.timestamp - ))) + #expect(try await transport.sentData[2] == command(binary: binary, + channel: Self.firstChannel, text: "first", timestamp: Self.timestamp)) await transport.simulateOK() try await waitForFrameCount(4, transport: transport) #expect(await transport.sentData[3] == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) @@ -56,9 +53,8 @@ struct ChannelSendSerializationTests { let frames = await Array(transport.sentData.dropFirst()) let secondScopeFrame = PacketBuilder.setFloodScope(Self.secondScope.scopeKey()) let secondScopeIndex = try #require(frames.firstIndex(of: secondScopeFrame)) - #expect(frames[secondScopeIndex + 1] == (try command(binary: binary, - channel: Self.secondChannel, text: "second", timestamp: Self.timestamp - ))) + #expect(try frames[secondScopeIndex + 1] == command(binary: binary, + channel: Self.secondChannel, text: "second", timestamp: Self.timestamp)) #expect(frames[secondScopeIndex + 2] == PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey())) let commandCode = binary ? CommandCode.sendChannelData : CommandCode.sendChannelMessage #expect(frames.filter { $0.first == commandCode.rawValue }.count == 2) From 5f0a28cbcc2174890038aa40d7797830a8e041d8 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:44:38 -0800 Subject: [PATCH 05/13] update Reactions.md --- docs/Reactions.md | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/docs/Reactions.md b/docs/Reactions.md index 171e10548c..047ab57f3a 100644 --- a/docs/Reactions.md +++ b/docs/Reactions.md @@ -6,17 +6,29 @@ How to implement emoji reactions compatible with MeshCore One. Reactions target messages by a hash of their content. Every node that received the original message can compute the same hash independently. -1. Concatenate the message's UTF-8 text bytes with the sender's original timestamp as a little-endian `UInt32` +1. Concatenate the message's UTF-8 text bytes with the sender timestamp as a 4-byte little-endian unix time 2. SHA-256 the result 3. Take the first 5 bytes (40 bits) 4. Encode as 8 characters of [Crockford Base32](https://www.crockford.com/base32.html) ``` -SHA-256( UTF-8(text) + LE(UInt32(senderTimestamp)) ) +SHA-256( UTF-8(text) + LE32(timestamp) ) → first 5 bytes → Crockford Base32 → "b45pc4ek" ``` -Use the **sender's original timestamp**, not your local receive time in order for all nodes to agree on the hash. +Use the **sender timestamp from the packet**, not the local receive time, so all nodes agree on the hash. Group text messages and plain text messages (direct messages) use this. + +Room posts and group datagrams have no sender timestamp. Use a `0x01` byte instead: + +``` +SHA-256( 0x01 + bytes ) + → first 5 bytes → Crockford Base32 +``` + +- **Room post.** `bytes` are the post text after the 4-byte sender pubkey prefix (`txt_type` `0x02`). +- **Group datagram.** `bytes` are the `data` field. + +Two copies with the same hash and sender: attach to the newest copy stored at or before the reaction. ### Why Crockford Base32? @@ -26,28 +38,38 @@ Crockford Base32 maps 5 bytes to exactly 8 characters using only alphanumerics Reactions are sent as regular mesh messages with a specific text format. -**Channel** (includes target sender to disambiguate identical messages from different users): +**Group text** (includes the sender name to disambiguate identical messages from different users): ``` -@[{targetSenderName}]{emoji}\n{hash} +@[{sender name}]{emoji}\n{hash} ``` Example: `@[AlphaNode]👍\nb45pc4ek` -The `{emoji}` field is a single extended grapheme cluster. A remainder that merely starts with an emoji is ordinary chat, not a reaction. Queue unmatched bodies that do match this format; do not persist them as chat. +`{sender name}` is the name from the group text body, `: `. The `{emoji}` field is a single extended grapheme cluster. A remainder that merely starts with an emoji is ordinary chat, not a reaction. Queue unmatched bodies that do match this format; do not persist them as chat. -Until 1.4.1, channel reactions put the emoji first: `{emoji}@[{targetSenderName}]\n{hash}`. Accept both orders for now so older clients still match. We'll drop the old one once enough apps have been updated. +Until MC1 v1.4.1, group text reactions put the emoji first: `{emoji}@[{sender name}]\n{hash}`. Accept both orders for now so older clients still match. We'll drop the old one once enough apps have been updated. -**DM** (two-party, sender is unambiguous): +**Plain text message** (direct message, two-party, sender is unambiguous): ``` {emoji}\n{hash} ``` Example: `👍\nb45pc4ek` +**Room post** (sender field is the sender pubkey prefix): +``` +@[{sender pubkey prefix}]{emoji}\n{hash} +``` +Example: `@[A1B2C3D4]👍\nb45pc4ek` + +Sent as a room post. The post text is the line above. `{hash}` is the no-timestamp hash of the target post. Match posts in that room, including the local node's own posts. Ignore the post timestamp the room server wrote onto the reaction. No emoji-first form. + ## Receiving Reactions -When you receive a message, check if it matches the reaction format before treating it as a regular message. +On receive, check whether the message matches the reaction format before treating it as a regular message. + +**If it's a reaction:** look up the target message by hash. If the target hasn't arrived yet (out-of-order delivery is common on mesh), queue the reaction and match it when the target appears. Use the no-timestamp hash for a room post or a group datagram, and the normal hash for everything else. -**If it's a reaction:** look up the target message by hash. If the target hasn't arrived yet (out-of-order delivery is common on mesh), queue the reaction and match it when the target appears. +**If it's a regular message:** compute its hash and index it so future reactions can find it. Also check the pending queue for reactions already waiting on this hash. Index room posts and group datagrams with the no-timestamp hash, or a reaction that got there first sits in the queue until it falls off. -**If it's a regular message:** compute its hash and index it so future reactions can find it. Also check your pending queue for reactions already waiting on this hash. +Group text lookup can scan about five minutes around the reaction. Room posts and group datagrams match the saved messages for that room or channel. -Deduplicate by `(targetHash, senderName, emoji)` — a node may relay the same reaction more than once. +Deduplicate by `(target hash, sender, emoji)`. A node may relay the same reaction more than once. For a room reaction, `sender` is the reacting author's pubkey prefix. From 314c6ab2d5451aef832fe69470078156c16f0207 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:58:42 -0800 Subject: [PATCH 06/13] feat: react to a channel MCOimg without a time - A channel MCOimg with no packet sender time matches a reaction by a hash of the datagram bytes, with no five-minute window. The row keeps the sender name from send time. - An incoming channel MCOimg joins the same receive path as channel text. It carries the decoded name and no wire time. - A channel send is classified once. The pool, the radio command, and the queue share that result instead of reading the text again. - A send that is not admitted leaves the draft or the pixels in place. A user resend changes the nonce before the queue stores the text. --- .../Chats/ChatConversationInputBar.swift | 4 +- MC1/Views/Chats/ChatConversationView.swift | 4 +- .../Chats/Components/ChatShareMenu.swift | 12 +- MC1/Views/Chats/MCOimg/PixelPaintDraft.swift | 5 +- .../Reactions/MessageActionAvailability.swift | 2 +- .../ChatMessageBakeState+ItemBuild.swift | 4 +- .../ViewModel/ChatTimelinePopulator.swift | 20 +- .../ViewModel/ChatViewModel+Channels.swift | 11 +- .../ChatViewModel+MessageActions.swift | 26 +- .../ViewModel/ChatViewModel+Messages.swift | 2 - .../RemoteNodes/Rooms/RoomMessageBubble.swift | 19 +- .../Persistence/MessagePersisting.swift | 26 +- .../ChatSendQueueService+ChannelDrain.swift | 24 +- .../Services/ChatSendQueueService.swift | 14 +- .../Services/MessageDTO+MCOImage.swift | 31 ++ .../Services/MessageFragmentBuilder.swift | 5 +- .../Services/MessageLRUCache.swift | 13 +- .../Services/MessageLanguageDetector.swift | 2 +- .../MessageService+ChannelScope.swift | 28 +- .../Services/MessageService+MCOImage.swift | 49 ++- .../Services/MessageService+SendChannel.swift | 57 ++- .../Services/PersistenceStore+Messages.swift | 53 ++- .../PersistenceStore+OutgoingReactions.swift | 11 +- .../MC1Services/Services/ReactionParser.swift | 14 +- .../Services/ReactionService.swift | 19 +- .../SyncCoordinator+MessageHandlers.swift | 335 +++++++++++------- .../SyncCoordinator+ReactionHandlers.swift | 154 +++++--- .../Utilities/MCOImageTransport.swift | 13 +- .../Utilities/MCOimg/MCOImageCodec.swift | 6 +- .../MCOImageBinarySendTests.swift | 27 +- .../MCOImageReceiveIntegrationTests.swift | 73 ++++ .../MCOImageSendIntegrationTests.swift | 8 +- .../MCOImageTransportTests.swift | 28 +- .../MCOImageV3CodecTests.swift | 2 +- .../Mocks/MockPersistenceStore.swift | 20 ++ .../PersistenceStoreTests.swift | 269 ++++++++++---- .../Services/ChatSendQueueReactionTests.swift | 4 +- .../Services/ChatSendQueueServiceTests.swift | 51 ++- .../Services/ReactionParserTests.swift | 35 ++ .../Services/ReactionServiceTests.swift | 26 +- ...dinatorChannelMCOImageReactionTests.swift} | 91 +++-- .../Views/Chats/ChatSendAdmissionTests.swift | 78 +++- .../ChatKeyboardTransitionTests.swift | 2 +- .../ChatNativeSplitLayoutTests.swift | 2 +- .../RoomMessageBubbleA11yLabelTests.swift | 2 +- .../MessageActionAvailabilityTests.swift | 22 +- .../Models/MessageFragmentBuilderTests.swift | 6 +- .../Views/Chats/PixelPaintDraftTests.swift | 14 +- .../Chats/PixelPaintPresentationTests.swift | 5 - 49 files changed, 1180 insertions(+), 548 deletions(-) create mode 100644 MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift rename MC1Services/Tests/MC1ServicesTests/{SyncCoordinatorChannelImageReactionTests.swift => SyncCoordinatorChannelMCOImageReactionTests.swift} (70%) diff --git a/MC1/Views/Chats/ChatConversationInputBar.swift b/MC1/Views/Chats/ChatConversationInputBar.swift index e054ddd5d3..cccd889d18 100644 --- a/MC1/Views/Chats/ChatConversationInputBar.swift +++ b/MC1/Views/Chats/ChatConversationInputBar.swift @@ -9,7 +9,7 @@ struct ChatConversationInputBar: View { let nodeNameByteCount: Int let onSend: (String) async -> Bool let onWillSend: () -> Void - let onDrawingRejected: () -> Void + let onNotAdmitted: () -> Void @Environment(\.appState) private var appState @State private var drawing = PixelPaintDraft() @@ -80,7 +80,6 @@ struct ChatConversationInputBar: View { isReady: ready, onSend: onSend, onWillSend: onWillSend, - onRejected: onDrawingRejected, onAdmitted: { isShowingPainter = false } ) } @@ -94,6 +93,7 @@ struct ChatConversationInputBar: View { guard await !onSend(text) else { return } let newerText = draft.wrappedValue draft.wrappedValue = newerText.isEmpty ? text : text + "\n" + newerText + onNotAdmitted() } } diff --git a/MC1/Views/Chats/ChatConversationView.swift b/MC1/Views/Chats/ChatConversationView.swift index 141fe4b38f..d4e7e9ccb9 100644 --- a/MC1/Views/Chats/ChatConversationView.swift +++ b/MC1/Views/Chats/ChatConversationView.swift @@ -201,7 +201,9 @@ struct ChatConversationView: View { } }, onWillSend: { scrollToBottomRequest += 1 }, - onDrawingRejected: { chatViewModel.sendErrorMessage = nil } + onNotAdmitted: { + chatViewModel.sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + } ) } .navigationHeader( diff --git a/MC1/Views/Chats/Components/ChatShareMenu.swift b/MC1/Views/Chats/Components/ChatShareMenu.swift index e0eb9b6858..504da578cd 100644 --- a/MC1/Views/Chats/Components/ChatShareMenu.swift +++ b/MC1/Views/Chats/Components/ChatShareMenu.swift @@ -6,7 +6,7 @@ import SwiftUI /// Pixel painting opens the conversation-owned editor; contacts load in `ShareContactPickerSheet`. struct ChatShareMenu: View { let onInsert: (String) -> Void - var onPaint: (() -> Void)? + let onPaint: () -> Void @Environment(\.appState) private var appState @@ -81,12 +81,10 @@ struct ChatShareMenu: View { } .disabled(!canShareLocation) - if let onPaint { - Button(action: onPaint) { - Label(L10n.Chats.Chats.Mcoimg.title, systemImage: "paintpalette") - } - .accessibilityIdentifier("pixelPaintAction") + Button(action: onPaint) { + Label(L10n.Chats.Chats.Mcoimg.title, systemImage: "paintpalette") } + .accessibilityIdentifier("pixelPaintAction") Button { isShowingContactPicker = true @@ -159,6 +157,6 @@ private extension View { } #Preview { - ChatShareMenu(onInsert: { _ in }) + ChatShareMenu(onInsert: { _ in }, onPaint: {}) .padding() } diff --git a/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift b/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift index aed1f3f49e..3a2dd9cf78 100644 --- a/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift +++ b/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift @@ -93,7 +93,6 @@ final class PixelPaintDraft { isReady: @escaping () -> Bool, onSend: @escaping (String) async -> Bool, onWillSend: @escaping () -> Void, - onRejected: @escaping () -> Void, onAdmitted: @escaping () -> Void, encode: @escaping @Sendable (MCOImageRaster, Bool) async throws -> String = encodePixelDrawing ) async { @@ -108,7 +107,7 @@ final class PixelPaintDraft { onWillSend: onWillSend, encode: encode ) - settle(result, generation: attempt.generation, onRejected: onRejected, onAdmitted: onAdmitted) + settle(result, generation: attempt.generation, onAdmitted: onAdmitted) } private func resetPixels() { @@ -166,7 +165,6 @@ final class PixelPaintDraft { private func settle( _ result: SubmissionResult, generation: UInt, - onRejected: () -> Void, onAdmitted: () -> Void ) { guard isCurrent(generation) else { return } @@ -175,7 +173,6 @@ final class PixelPaintDraft { remove() onAdmitted() case .rejected: - onRejected() errorTitle = L10n.Chats.Chats.Alert.UnableToSend.title errorMessage = L10n.Chats.Chats.Alert.UnableToSend.message isSubmitting = false diff --git a/MC1/Views/Chats/Reactions/MessageActionAvailability.swift b/MC1/Views/Chats/Reactions/MessageActionAvailability.swift index 35ec669dac..bf1687091f 100644 --- a/MC1/Views/Chats/Reactions/MessageActionAvailability.swift +++ b/MC1/Views/Chats/Reactions/MessageActionAvailability.swift @@ -26,7 +26,7 @@ struct MessageActionAvailability { && message.isFloodRouted && !(message.pathNodes?.isEmpty ?? true) canDelete = true - canReact = !MCOImageCodec.isChannelImage(channelIndex: message.channelIndex, text: message.text) + canReact = message.mcoImageReactionTarget() != nil || !message.isChannelMCOImage showsPathDetail = canViewPath || canShowRepeatDetails || (!message.isOutgoing && message.heardRepeats > 0) } } diff --git a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift index 2ae3143422..ffcaa7a582 100644 --- a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift +++ b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift @@ -112,10 +112,10 @@ extension ChatMessageBakeState { envInputs: EnvInputs, senderTables: ChatSenderTables ) -> MessageBuildInputs { - if !MCOImageCodec.isImageText(message.text) { + if message.mcoImage == nil { seedPreviewStateIfNeeded(for: message, envInputs: envInputs) } - if envInputs.translationOffersEnabled, !MCOImageCodec.isImageText(message.text) { + if envInputs.translationOffersEnabled, message.mcoImage == nil { seedDetectedLanguageIfNeeded(for: message) } let flags = Self.computeDisplayFlags(for: message, previous: previous, next: next) diff --git a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift index a53b71379f..02d2f93353 100644 --- a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift +++ b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift @@ -151,14 +151,19 @@ enum ChatTimelinePopulator { // disconnect would otherwise mint a fresh UUID into persisted rows. let radioID = channel.radioID for message in fetchedMessages { - let senderName: String? = if message.isOutgoing { - localNodeName + let indexed = message.mcoImageReactionTarget() + let reactionSender: String? + let messageHash: String? + if message.isChannelMCOImage { + reactionSender = indexed?.senderName + messageHash = indexed?.messageHash + } else if message.isOutgoing { + reactionSender = localNodeName + messageHash = nil } else { - message.senderNodeName + reactionSender = message.senderNodeName + messageHash = nil } - let reactionSender = senderName ?? ( - MCOImageCodec.isChannelImage(channelIndex: message.channelIndex, text: message.text) ? "Unknown" : nil - ) guard let reactionSender else { continue } let pendingMatches = await reactionService.indexMessage( @@ -166,7 +171,8 @@ enum ChatTimelinePopulator { channelIndex: channel.index, senderName: reactionSender, text: message.text, - timestamp: message.reactionTimestamp + timestamp: message.reactionTimestamp, + messageHash: messageHash ) for pending in pendingMatches { diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift index 29a3d57ca6..d9fed9be14 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift @@ -104,7 +104,6 @@ extension ChatViewModel { guard !text.isEmpty else { return true } guard let channel = currentChannel, let queue = chatSendQueueServiceProvider() else { - sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message return false } @@ -123,7 +122,6 @@ extension ChatViewModel { await presentLocalEnqueueFailure(messageID: message.id, error: error) } } catch ChatSendQueueServiceError.notConnected { - sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message return false } catch { errorMessage = error.userFacingMessage @@ -154,14 +152,7 @@ extension ChatViewModel { errorMessage = nil errorBannerMessage = nil - let originalMessage = message - let message: MessageDTO - do { - message = try await messageService?.prepareImageForResend(originalMessage) ?? originalMessage - } catch { - errorMessage = error.userFacingMessage - return - } + guard let message = await messagePreparedForResend(message) else { return } // Capture once so the three status-update writes below all target the // same container even if a reconnect fires between the awaits. diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift index 078bdc36fc..b081f7cb9e 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift @@ -6,6 +6,16 @@ extension ChatViewModel { // MARK: - Message Actions + func messagePreparedForResend(_ message: MessageDTO) async -> MessageDTO? { + guard let messageService else { return message } + do { + return try await messageService.prepareMCOImageForResend(message) + } catch { + errorMessage = error.userFacingMessage + return nil + } + } + /// Retry sending a failed direct message through the persistent send /// queue. Replaces the prior multi-await sequence (delete + /// status flip + direct service call) with a single @@ -30,12 +40,7 @@ extension ChatViewModel { errorMessage = nil errorBannerMessage = nil - do { - _ = try await messageService?.prepareImageForResend(message) - } catch { - errorMessage = error.userFacingMessage - return - } + guard await messagePreparedForResend(message) != nil else { return } let envelope = DirectMessageEnvelope( messageID: message.id, contactID: contact.id, @@ -68,14 +73,7 @@ extension ChatViewModel { /// Resend a channel message in place, or copy text for direct messages. /// Used for "Send Again" context menu action. func sendAgain(_ message: MessageDTO) async { - let originalMessage = message - let message: MessageDTO - do { - message = try await messageService?.prepareImageForResend(originalMessage) ?? originalMessage - } catch { - errorMessage = error.userFacingMessage - return - } + guard let message = await messagePreparedForResend(message) else { return } if let channelIndex = message.channelIndex { // Text resends need a fresh wire timestamp; image nonces were prepared // before enqueue so automatic queue retries can preserve their payload. diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+Messages.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+Messages.swift index de6d6981c5..7e2b3e8630 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+Messages.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+Messages.swift @@ -156,7 +156,6 @@ extension ChatViewModel { guard !text.isEmpty else { return true } guard let contact = currentContact, let queue = chatSendQueueServiceProvider() else { - sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message return false } @@ -172,7 +171,6 @@ extension ChatViewModel { await presentLocalEnqueueFailure(messageID: message.id, error: error) } } catch ChatSendQueueServiceError.notConnected { - sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message return false } catch { errorMessage = error.userFacingMessage diff --git a/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift b/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift index 0e2bad4ea7..81708eb386 100644 --- a/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift +++ b/MC1/Views/RemoteNodes/Rooms/RoomMessageBubble.swift @@ -28,6 +28,7 @@ struct RoomMessageBubble: View { } var body: some View { + let mcoImage = MCOImageCodec.content(from: message.text) VStack(spacing: 4) { if showTimestamp { makeTimestampView() @@ -39,11 +40,11 @@ struct RoomMessageBubble: View { } VStack(alignment: isFromSelf ? .trailing : .leading, spacing: 2) { - makeBubbleContent() + makeBubbleContent(mcoImage: mcoImage) makeStatusIndicator() } .accessibilityElement(children: .combine) - .accessibilityLabel(accessibilityMessageLabel) + .accessibilityLabel(spokenLabel(mcoImage: mcoImage)) .accessibilityIdentifier(ChatScrollConstants.messageAccessibilityIdentifier(message.id)) .accessibilityAction { onLongPress?(message) @@ -91,7 +92,11 @@ struct RoomMessageBubble: View { } var accessibilityMessageLabel: String { - let body = MCOImageCodec.content(from: message.text)?.accessibilityLabel ?? visibleBody.spokenText + spokenLabel(mcoImage: MCOImageCodec.content(from: message.text)) + } + + private func spokenLabel(mcoImage: MCOImageContent?) -> String { + let body = mcoImage?.accessibilityLabel ?? visibleBody.spokenText if isFromSelf { return "\(body), \(message.accessibilityStatusLabel)" } @@ -126,9 +131,10 @@ struct RoomMessageBubble: View { ).text } - private func makeBubbleContent() -> some View { + private func makeBubbleContent(mcoImage: MCOImageContent?) -> some View { BubbleContent( message: message, + mcoImage: mcoImage, isFromSelf: isFromSelf, showSenderName: showSenderName, showAvatar: showAvatar, @@ -173,6 +179,7 @@ private struct TimestampView: View { private struct BubbleContent: View { let message: RoomMessageDTO + let mcoImage: MCOImageContent? let isFromSelf: Bool let showSenderName: Bool let showAvatar: Bool @@ -242,8 +249,8 @@ private struct BubbleContent: View { @ViewBuilder private var messageBody: some View { - if let image = MCOImageCodec.content(from: message.text) { - MCOImageView(content: image) + if let mcoImage { + MCOImageView(content: mcoImage) } else if let plainText = visibleBody.plainText { Text(plainText) .font(.body) diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index 17d4b8b807..4a0f226b04 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -97,16 +97,13 @@ public protocol MessagePersisting: Actor { limit: Int ) async throws -> MessageDTO? - /// True when a stored channel image matches this reaction hash. - /// The text lookup returns nil for that row, which is also how a missing text message looks. - func channelImageMatchesReaction( + /// Newest saved channel MCOimg with no packet sender timestamp that matches this reaction. + /// No timestamp window and no row cap. + func findChannelDatagramForReaction( radioID: UUID, channelIndex: UInt8, - parsedReaction: ParsedReaction, - localNodeName: String?, - timestampWindow: ClosedRange, - limit: Int - ) async throws -> Bool + parsedReaction: ParsedReaction + ) async throws -> MessageDTO? /// Fetches channel message candidates for meshcore-open reaction matching func fetchChannelMessageCandidates( @@ -169,7 +166,7 @@ public protocol MessagePersisting: Actor { /// Update message retry status func updateMessageRetryStatus(id: UUID, status: MessageStatus, retryAttempt: Int, maxRetryAttempts: Int) async throws - /// Update the exact wire text before a user-initiated image resend. + /// Update the exact wire text before a user-initiated MCOimg resend. func updateMessageText(id: UUID, text: String) async throws /// Update message timestamp (for resending) @@ -295,15 +292,12 @@ extension MessagePersisting { } public extension MessagePersisting { - func channelImageMatchesReaction( + func findChannelDatagramForReaction( radioID _: UUID, channelIndex _: UInt8, - parsedReaction _: ParsedReaction, - localNodeName _: String?, - timestampWindow _: ClosedRange, - limit _: Int - ) async throws -> Bool { - false + parsedReaction _: ParsedReaction + ) async throws -> MessageDTO? { + nil } func admitOutgoingReaction(_ message: MessageDTO) async throws -> MessageDTO? { diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift index 2926c7cfc3..a99068686b 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift @@ -43,6 +43,8 @@ extension ChatSendQueueService { ) else { return } try cancelSendIfRetired(dependencies.sendsRetired) + let capturedText = envelope.messageText + let sentDatagram = MCOImageCodec.isMCOImageText(capturedText) switch try await transmitQueuedChannel(envelope: envelope, dependencies: dependencies) { case .dropped: return @@ -60,12 +62,24 @@ extension ChatSendQueueService { timeout: dependencies.config.transportWaitTimeout ) case let .sent(indexTimestamp): - if let nodeName = envelope.localNodeName, !MCOImageCodec.isImageText(envelope.messageText) { + if sentDatagram { + if let saved = try? await dependencies.dataStore.fetchMessage(id: envelope.messageID), + let target = saved.mcoImageReactionTarget() { + _ = await dependencies.reactionService.indexMessage( + id: saved.id, + channelIndex: envelope.channelIndex, + senderName: target.senderName, + text: saved.text, + timestamp: saved.reactionTimestamp, + messageHash: target.messageHash + ) + } + } else if let nodeName = envelope.localNodeName { _ = await dependencies.reactionService.indexMessage( id: envelope.messageID, channelIndex: envelope.channelIndex, senderName: nodeName, - text: envelope.messageText, + text: capturedText, timestamp: indexTimestamp ) } @@ -78,6 +92,7 @@ extension ChatSendQueueService { error, postBumpCount: postBumpCount, envelope: envelope, + sentDatagram: sentDatagram, dependencies: dependencies ) } @@ -132,11 +147,10 @@ extension ChatSendQueueService { _ error: Error, postBumpCount: Int, envelope: ChannelMessageEnvelope, + sentDatagram: Bool, dependencies: ChannelDrainDependencies ) async throws { - guard isTransientChannelMessageError( - error, isImage: MCOImageCodec.isImageText(envelope.messageText) - ) else { + guard isTransientChannelMessageError(error, sentDatagram: sentDatagram) else { dependencies.logger.info( "channel drain terminal messageID=\(envelope.messageID) error=\(String(describing: error))" ) diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index 366619d6c8..8e73aa5e9c 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -284,12 +284,12 @@ public final class ChatSendQueueService { guard target.radioID == radioID else { throw ChatSendQueueServiceError.notConnected } guard beginAdmission() else { throw CancellationError() } defer { finishAdmission() } - if MCOImageCodec.isChannelImage(channelIndex: target.channelIndex, text: target.text) { - return nil - } - let text: String - if target.channelIndex != nil { + if let indexed = target.mcoImageReactionTarget() { + text = "@[\(indexed.senderName)]\(emoji)\n\(indexed.messageHash)" + } else if target.isChannelMCOImage { + return nil + } else if target.channelIndex != nil { guard let targetSender = target.isOutgoing ? senderName : target.senderNodeName else { return nil } text = reactionService.buildReactionText( emoji: emoji, targetSender: targetSender, targetText: target.text, targetTimestamp: target.reactionTimestamp @@ -570,9 +570,9 @@ public final class ChatSendQueueService { isTransientError(error, deviceCode: FirmwareDeviceErrorCode.directMessageTableFull) } - nonisolated static func isTransientChannelMessageError(_ error: Error, isImage: Bool = false) -> Bool { + nonisolated static func isTransientChannelMessageError(_ error: Error, sentDatagram: Bool) -> Bool { isTransientError(error, deviceCode: FirmwareDeviceErrorCode.channelMessageNotFound) - || (isImage && isTransientError(error, deviceCode: FirmwareDeviceErrorCode.channelDataTableFull)) + || (sentDatagram && isTransientError(error, deviceCode: FirmwareDeviceErrorCode.channelDataTableFull)) } /// Returns true if `error` is `MeshCoreError.deviceError(channelMessageNotFound)` diff --git a/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift new file mode 100644 index 0000000000..1cc56f8cac --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift @@ -0,0 +1,31 @@ +import Foundation + +public extension MessageDTO { + var mcoImage: MCOImageContent? { + MCOImageCodec.content(from: text) + } + + var isChannelMCOImage: Bool { + channelIndex != nil && MCOImageCodec.isMCOImageText(text) + } + + /// A channel MCOimg with no packet sender timestamp. + /// Incoming `senderTimestamp` nil is an accepted packet time. Zero is the datagram tuple. + /// Every outgoing channel MCOimg has no packet sender timestamp. + var isDatagramMCOImage: Bool { + guard isChannelMCOImage else { return false } + if isOutgoing { return true } + return senderTimestamp == 0 + } + + /// Nil when the name is missing or the datagram bytes cannot be rebuilt. + func mcoImageReactionTarget() -> (senderName: String, messageHash: String)? { + guard isChannelMCOImage else { return nil } + guard let senderNodeName, !senderNodeName.isEmpty else { return nil } + if isDatagramMCOImage { + guard let data = try? MCOImageTransport.dataField(text: text, senderName: senderNodeName) else { return nil } + return (senderNodeName, ReactionParser.generateUntimedHash(data)) + } + return (senderNodeName, ReactionParser.generateMessageHash(text: text, timestamp: reactionTimestamp)) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift index b4c8c2f403..2cc203270d 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift @@ -37,8 +37,7 @@ public enum MessageFragmentBuilder { if let image = MCOImageCodec.content(from: message.text) { fragments.append(.mcoImage(image)) - if !MCOImageCodec.isChannelImage(channelIndex: message.channelIndex, text: message.text), - let summary = message.reactionSummary, !summary.isEmpty { + if let summary = message.reactionSummary, !summary.isEmpty { fragments.append(.reactionSummary(summary)) } return fragments @@ -283,7 +282,7 @@ public enum MessageFragmentBuilder { inputs: MessageBuildInputs, message: MessageDTO ) -> Bool { - !MCOImageCodec.isImageText(message.text) + message.mcoImage == nil && inputs.previewState == .idle && inputs.cachedURL != nil && message.linkPreviewURL == nil diff --git a/MC1Services/Sources/MC1Services/Services/MessageLRUCache.swift b/MC1Services/Sources/MC1Services/Services/MessageLRUCache.swift index e1fb7bf672..b617e86a9f 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageLRUCache.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageLRUCache.swift @@ -44,9 +44,16 @@ actor MessageLRUCache { self.maxCandidatesPerKey = maxCandidatesPerKey } - /// Indexes a message for later lookup - func index(messageID: UUID, channelIndex: UInt8, senderName: String, text: String, timestamp: UInt32) { - let hash = ReactionParser.generateMessageHash(text: text, timestamp: timestamp) + /// A supplied hash replaces the timed hash. + func index( + messageID: UUID, + channelIndex: UInt8, + senderName: String, + text: String, + timestamp: UInt32, + messageHash: String? = nil + ) { + let hash = messageHash ?? ReactionParser.generateMessageHash(text: text, timestamp: timestamp) let key = MessageCacheKey(channelIndex: channelIndex, senderName: senderName, messageHash: hash) let candidate = MessageCandidate(messageID: messageID, text: text, timestamp: timestamp) diff --git a/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift b/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift index a7c6842b13..589ad5e137 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift @@ -15,7 +15,7 @@ public enum MessageLanguageDetector: Sendable { /// Dominant language of the mention-stripped body, or `.undetermined`. public static func dominantLanguage(for text: String) -> DetectedLanguage { - guard !MCOImageCodec.isImageText(text) else { return .undetermined } + guard !MCOImageCodec.isMCOImageText(text) else { return .undetermined } let sample = detectionSample(from: text) guard !sample.isEmpty else { return .undetermined } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift index 7438960900..8874eb65fb 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+ChannelScope.swift @@ -5,7 +5,7 @@ extension MessageService { private static let floodScopeMinimumFirmwareVersion: UInt8 = 8 func sendChannelMessageWithScope( - text: String, + _ transmission: ChannelTransmission, channelIndex: UInt8, radioID: UUID, timestamp: Date @@ -24,8 +24,8 @@ extension MessageService { } else { scope } - if MCOImageCodec.isImageText(text) { - let payload = try await channelImagePayload(text, radioID: radioID) + switch transmission { + case let .mcoImage(payload): if let appliedScope { try await session.sendChannelData( channelIndex: channelIndex, @@ -42,17 +42,17 @@ extension MessageService { pathBytes: Data() ) } - return - } - if let appliedScope { - try await session.sendChannelMessage( - channel: channelIndex, - text: text, - timestamp: timestamp, - floodScope: appliedScope - ) - } else { - try await session.sendChannelMessage(channel: channelIndex, text: text, timestamp: timestamp) + case let .text(text): + if let appliedScope { + try await session.sendChannelMessage( + channel: channelIndex, + text: text, + timestamp: timestamp, + floodScope: appliedScope + ) + } else { + try await session.sendChannelMessage(channel: channelIndex, text: text, timestamp: timestamp) + } } } } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift b/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift index 43e4f4aeca..0459ae5ac6 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift @@ -1,16 +1,36 @@ import Foundation +extension MessageService { + enum ChannelTransmission { + case text(String) + case mcoImage(Data) + } + + /// MCOimg bytes use the stored sender name, so a later rename does not change the payload. + func channelTransmission( + text: String, + senderNodeName: String?, + radioID: UUID + ) async throws -> ChannelTransmission { + if MCOImageCodec.isMCOImageText(text) { + return try .mcoImage(channelMCOImagePayload(text, senderName: senderNodeName ?? "")) + } + try await rejectIfChannelTextTooLong(text, radioID: radioID) + return .text(text) + } +} + public extension MessageService { - /// Refreshes a user-initiated image resend before its queue envelope captures the wire text. - func prepareImageForResend(_ message: MessageDTO) async throws -> MessageDTO { - guard MCOImageCodec.isImageText(message.text) else { return message } + /// Refreshes a user-initiated MCOimg resend before its queue envelope captures the wire text. + func prepareMCOImageForResend(_ message: MessageDTO) async throws -> MessageDTO { + guard message.mcoImage != nil else { return message } var refreshed = message let text = message.channelIndex != nil ? try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: message.text)) : message.text refreshed.text = try MCOImageCodec.refreshNonce(in: text) if message.channelIndex != nil { - _ = try await channelImagePayload(refreshed.text, radioID: message.radioID) + _ = try channelMCOImagePayload(refreshed.text, senderName: message.senderNodeName ?? "") } else { guard refreshed.text.utf8.count <= ProtocolLimits.maxDirectMessageLength else { throw MessageServiceError.messageTooLong @@ -20,21 +40,24 @@ public extension MessageService { return refreshed } - internal func prepareChannelMessage(_ text: String, radioID: UUID) async throws -> String { - guard MCOImageCodec.isImageText(text) else { + internal func prepareChannelMessage( + _ text: String, + radioID: UUID + ) async throws -> (text: String, mcoImageSenderName: String?) { + guard MCOImageCodec.isMCOImageText(text) else { try await rejectIfChannelTextTooLong(text, radioID: radioID) - return text + return (text, nil) } let canonicalText = try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: text)) - _ = try await channelImagePayload(canonicalText, radioID: radioID) - return canonicalText - } - - internal func channelImagePayload(_ text: String, radioID: UUID) async throws -> Data { guard let device = try await dataStore.fetchDevice(radioID: radioID) else { throw MessageServiceError.notConnected } - let payload = try MCOImageTransport.encode(text: text, senderName: device.nodeName) + _ = try channelMCOImagePayload(canonicalText, senderName: device.nodeName) + return (canonicalText, device.nodeName) + } + + internal func channelMCOImagePayload(_ text: String, senderName: String) throws -> Data { + let payload = try MCOImageTransport.encode(text: text, senderName: senderName) guard payload.count <= MCOImageWireBudget.maximumChannelDataBytes else { throw MessageServiceError.messageTooLong } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index 0ca6aaf503..63e54e3963 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -42,7 +42,7 @@ public extension MessageService { // Keep this send in the retirement barrier through the Sent write if scope cleanup triggers recovery. try beginInlineSend() defer { endInlineSend() } - let text = try await prepareChannelMessage(text, radioID: radioID) + let prepared = try await prepareChannelMessage(text, radioID: radioID) let messageID = UUID() let timestamp = UInt32(Date().timeIntervalSince1970) @@ -52,16 +52,22 @@ public extension MessageService { id: messageID, radioID: radioID, channelIndex: channelIndex, - text: text, + text: prepared.text, timestamp: timestamp, - textType: textType + textType: textType, + mcoImageSenderName: prepared.mcoImageSenderName ) try await dataStore.saveMessage(messageDTO) do { - try await withPoolBackoff(transientCode: channelPoolErrorCode(text), config: config.poolBackoff, logger: logger) { + let transmission = try await channelTransmission( + text: prepared.text, + senderNodeName: prepared.mcoImageSenderName, + radioID: radioID + ) + try await withPoolBackoff(transientCode: channelPoolErrorCode(transmission), config: config.poolBackoff, logger: logger) { try await sendChannelMessageWithScope( - text: text, + transmission, channelIndex: channelIndex, radioID: radioID, timestamp: Date(timeIntervalSince1970: TimeInterval(timestamp)) @@ -97,7 +103,7 @@ public extension MessageService { radioID: UUID, textType: TextType = .plain ) async throws -> MessageDTO { - let text = try await prepareChannelMessage(text, radioID: radioID) + let prepared = try await prepareChannelMessage(text, radioID: radioID) let messageID = UUID() let timestamp = UInt32(Date().timeIntervalSince1970) @@ -106,9 +112,10 @@ public extension MessageService { id: messageID, radioID: radioID, channelIndex: channelIndex, - text: text, + text: prepared.text, timestamp: timestamp, - textType: textType + textType: textType, + mcoImageSenderName: prepared.mcoImageSenderName ) try await dataStore.saveMessage(messageDTO) @@ -144,9 +151,14 @@ public extension MessageService { let isReaction = message.reactionTargetMessageID != nil let alreadyAccepted = isReaction && (acceptedChannelReactions.contains(messageID) || message.status == .sent) if !alreadyAccepted { - try await withPoolBackoff(transientCode: channelPoolErrorCode(message.text), config: config.poolBackoff, logger: logger) { + let transmission = try await channelTransmission( + text: message.text, + senderNodeName: message.senderNodeName, + radioID: radioID + ) + try await withPoolBackoff(transientCode: channelPoolErrorCode(transmission), config: config.poolBackoff, logger: logger) { try await sendChannelMessageWithScope( - text: message.text, + transmission, channelIndex: channelIndex, radioID: radioID, timestamp: Date(timeIntervalSince1970: TimeInterval(message.timestamp)) @@ -221,9 +233,14 @@ public extension MessageService { acceptedChannelReactions.contains(messageID) || (preserveTimestamp && message.status == .sent) ) if !alreadyAccepted { - try await withPoolBackoff(transientCode: channelPoolErrorCode(message.text), config: config.poolBackoff, logger: logger) { + let transmission = try await channelTransmission( + text: message.text, + senderNodeName: message.senderNodeName, + radioID: message.radioID + ) + try await withPoolBackoff(transientCode: channelPoolErrorCode(transmission), config: config.poolBackoff, logger: logger) { try await sendChannelMessageWithScope( - text: message.text, + transmission, channelIndex: channelIndex, radioID: message.radioID, timestamp: wireDate @@ -261,8 +278,13 @@ public extension MessageService { return wireTimestamp } - private func channelPoolErrorCode(_ text: String) -> UInt8 { - MCOImageCodec.isImageText(text) ? FirmwareDeviceErrorCode.channelDataTableFull : FirmwareDeviceErrorCode.channelMessageNotFound + private func channelPoolErrorCode(_ transmission: ChannelTransmission) -> UInt8 { + switch transmission { + case .text: + FirmwareDeviceErrorCode.channelMessageNotFound + case .mcoImage: + FirmwareDeviceErrorCode.channelDataTableFull + } } private func createOutgoingChannelMessage( @@ -271,7 +293,8 @@ public extension MessageService { channelIndex: UInt8, text: String, timestamp: UInt32, - textType: TextType + textType: TextType, + mcoImageSenderName: String? ) -> MessageDTO { let message = Message( id: id, @@ -283,6 +306,10 @@ public extension MessageService { statusRawValue: MessageStatus.pending.rawValue, textTypeRawValue: textType.rawValue ) + if let mcoImageSenderName { + // The datagram sender. A later node rename must not change this field. + message.senderNodeName = mcoImageSenderName + } return MessageDTO(from: message) } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index bc111eab1b..7de6d44c6f 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -241,8 +241,8 @@ public extension PersistenceStore { continue } - guard !MCOImageCodec.isChannelImage(channelIndex: candidate.channelIndex, text: candidate.text) else { - logger.debug("[REACTION-MATCH] Skip channel image") + guard !candidate.isDatagramMCOImage else { + logger.debug("[REACTION-MATCH] Skip datagram image") continue } @@ -254,37 +254,29 @@ public extension PersistenceStore { return nil } - /// True when a channel image in the window hashes to this reaction. - /// A text lookup miss looks the same as this, so the caller must not queue it. - func channelImageMatchesReaction( + func findChannelDatagramForReaction( radioID: UUID, channelIndex: UInt8, - parsedReaction: ParsedReaction, - localNodeName: String?, - timestampWindow: ClosedRange, - limit: Int - ) async throws -> Bool { - let candidates = try fetchChannelMessageCandidates( - radioID: radioID, - channelIndex: channelIndex, - timestampWindow: timestampWindow, - limit: limit + parsedReaction: ParsedReaction + ) async throws -> MessageDTO? { + let targetRadioID = radioID + let targetChannelIndex: UInt8? = channelIndex + let predicate = #Predicate { message in + message.radioID == targetRadioID && message.channelIndex == targetChannelIndex + } + let descriptor = FetchDescriptor( + predicate: predicate, + sortBy: [SortDescriptor(\Message.createdAt, order: .reverse)] ) - for candidate in candidates { - guard MCOImageCodec.isChannelImage(channelIndex: candidate.channelIndex, text: candidate.text) else { - continue - } - if candidate.direction == .outgoing { - guard let localNodeName, parsedReaction.targetSender == localNodeName else { continue } - } else { - guard candidate.senderNodeName == parsedReaction.targetSender else { continue } - } - let candidateHash = ReactionParser.generateMessageHash( - text: candidate.text, timestamp: candidate.reactionTimestamp - ) - if candidateHash == parsedReaction.messageHash { return true } + for message in try modelContext.fetch(descriptor) { + let candidate = MessageDTO(from: message) + guard let target = candidate.mcoImageReactionTarget(), + candidate.isDatagramMCOImage, + target.senderName == parsedReaction.targetSender, + target.messageHash == parsedReaction.messageHash else { continue } + return candidate } - return false + return nil } /// Fetches channel message candidates within a timestamp window for meshcore-open reaction matching. @@ -1090,7 +1082,8 @@ public extension PersistenceStore { var messageDescriptor = FetchDescriptor(predicate: messagePredicate) messageDescriptor.fetchLimit = 1 guard let message = try modelContext.fetch(messageDescriptor).first else { return nil } - if MCOImageCodec.isChannelImage(channelIndex: message.channelIndex, text: message.text) { + let messageDTO = MessageDTO(from: message) + if messageDTO.isChannelMCOImage, messageDTO.mcoImageReactionTarget() == nil { return nil } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift index 36cec2c74f..377786abcb 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift @@ -6,10 +6,13 @@ public extension PersistenceStore { guard message.direction == .outgoing, message.status == .pending, let senderName = message.reactionSenderName, let details = outgoingReactionDetails(message), - let target = try outgoingReactionTarget(message), - details.messageHash == ReactionParser.generateMessageHash( - text: target.text, timestamp: target.senderTimestamp ?? target.timestamp - ) else { return nil } + let target = try outgoingReactionTarget(message) else { return nil } + let targetDTO = MessageDTO(from: target) + let expectedHash = targetDTO.mcoImageReactionTarget()?.messageHash + ?? ReactionParser.generateMessageHash( + text: target.text, timestamp: target.senderTimestamp ?? target.timestamp + ) + guard details.messageHash == expectedHash else { return nil } guard try !reactionExists(messageID: target.id, senderName: senderName, emoji: details.emoji) else { return nil } diff --git a/MC1Services/Sources/MC1Services/Services/ReactionParser.swift b/MC1Services/Sources/MC1Services/Services/ReactionParser.swift index 05c839064e..cbaf1889e3 100644 --- a/MC1Services/Sources/MC1Services/Services/ReactionParser.swift +++ b/MC1Services/Sources/MC1Services/Services/ReactionParser.swift @@ -192,9 +192,19 @@ public enum ReactionParser { public static func generateMessageHash(text: String, timestamp: UInt32) -> String { var data = Data(text.utf8) withUnsafeBytes(of: timestamp.littleEndian) { data.append(contentsOf: $0) } + return crockfordHash(of: data) + } + + /// Hash for a packet that has no sender timestamp. Input is the byte `0x01` plus the named bytes. + public static func generateUntimedHash(_ data: Data) -> String { + var framed = Data([0x01]) + framed.append(data) + return crockfordHash(of: framed) + } + + private static func crockfordHash(of data: Data) -> String { let digest = SHA256.hash(data: data) - let bytes = Array(digest.prefix(5)) - return encodeCrockfordBase32(bytes) + return encodeCrockfordBase32(Array(digest.prefix(5))) } /// Rows included in a message's reaction summary, most recent first. diff --git a/MC1Services/Sources/MC1Services/Services/ReactionService.swift b/MC1Services/Sources/MC1Services/Services/ReactionService.swift index 9de65eba93..534b19a947 100644 --- a/MC1Services/Sources/MC1Services/Services/ReactionService.swift +++ b/MC1Services/Sources/MC1Services/Services/ReactionService.swift @@ -73,27 +73,23 @@ public actor ReactionService { channelIndex: UInt8, senderName: String, text: String, - timestamp: UInt32 + timestamp: UInt32, + messageHash: String? = nil ) async -> [PendingReaction] { - let hash = ReactionParser.generateMessageHash(text: text, timestamp: timestamp) + let hash = messageHash ?? ReactionParser.generateMessageHash(text: text, timestamp: timestamp) let key = PendingReactionKey( channelIndex: channelIndex, targetSender: senderName, messageHash: hash ) - // A channel image is not a reaction target. Drop a reaction that arrived - // first, and do not leave the image in the cache for a later lookup. - if MCOImageCodec.isChannelImage(channelIndex: channelIndex, text: text) { - discardPendingReaction(for: key) - return [] - } await messageCache.index( messageID: id, channelIndex: channelIndex, senderName: senderName, text: text, - timestamp: timestamp + timestamp: timestamp, + messageHash: hash ) guard let matched = pendingReactions.removeValue(forKey: key) else { @@ -292,11 +288,6 @@ public actor ReactionService { logger.debug("Queued pending DM reaction \(parsed.emoji)") } - private func discardPendingReaction(for key: PendingReactionKey) { - guard pendingReactions.removeValue(forKey: key) != nil else { return } - pendingOrder.removeAll { $0 == key } - } - private func evictIfNeeded() { var totalCount = pendingReactions.values.reduce(0) { $0 + $1.count } diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 48a1aa1179..9a243c35d6 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -61,41 +61,45 @@ extension SyncCoordinator { private func wireChannelDatagramHandler(dependencies: SyncDependencies, radioID: UUID, selfNodeName: String) async { await dependencies.messagePollingService.setChannelDatagramHandler { [weak self] datagram, channel, context, scope, preference, arrivedAt in - guard let self, scope.radioID == radioID, scope.isCurrent, let image = MCOImageTransport.decode(datagram) else { return } - let message = ChannelMessage( - channelIndex: datagram.channelIndex, - pathLength: datagram.pathLength, - textType: MeshTextType.plain.rawValue, - senderTimestamp: Date(timeIntervalSince1970: 0), - text: image.text, - snr: datagram.snr - ) + guard let self, scope.radioID == radioID, scope.isCurrent, let decoded = MCOImageTransport.decode(datagram) else { return } await handleIncomingMessage( - kind: .channel(message, channel: channel), + kind: .mcoImage( + channelIndex: datagram.channelIndex, + text: decoded.text, + senderName: decoded.senderName, + pathLength: datagram.pathLength, + snr: datagram.snr, + channel: channel + ), receivedAt: arrivedAt, context: context, dependencies: dependencies, selfNodeName: selfNodeName, scope: scope, - preference: preference, - datagramSenderName: image.senderName + preference: preference ) } } // MARK: - Incoming Message Pipeline - /// Discriminates the two text-message ingestion paths, carrying the wire - /// message and the resolved conversation for each. private enum IncomingMessageKind { case direct(ContactMessage, contact: ContactDTO?) case channel(ChannelMessage, channel: ChannelDTO?) + case mcoImage( + channelIndex: UInt8, + text: String, + senderName: String, + pathLength: UInt8, + snr: Double, + channel: ChannelDTO? + ) - /// Log noun distinguishing the two paths in shared diagnostics. + /// Channel text and an MCOimg share one log noun. var logLabel: String { switch self { case .direct: "direct" - case .channel: "channel" + case .channel, .mcoImage: "channel" } } } @@ -200,8 +204,7 @@ extension SyncCoordinator { dependencies: SyncDependencies, selfNodeName: String, scope: ReceiveScope, - preference: TextRulesPreference?, - datagramSenderName: String? = nil + preference: TextRulesPreference? ) async { guard scope.isCurrent else { return } let radioID = scope.radioID @@ -212,17 +215,20 @@ extension SyncCoordinator { kind, dependencies: dependencies, scope: scope ) - // Per-kind wire fields. Channel messages embed the sender as a - // "NodeName: text" prefix; direct messages carry the sender key prefix. + // Channel text embeds the sender as a "NodeName: text" prefix. + // An MCOimg already has its name. A direct message carries the key prefix. let text: String let senderNodeName: String? - let senderTimestampDate: Date let textTypeRaw: UInt8 let snr: Double? let reportedPathLength: UInt8 let contactID: UUID? let channelIndex: UInt8? let senderKeyPrefix: Data? + let conversation: ChannelDTO? + let wireTimestamp: UInt32? + let harvestIncomingPaths: Bool + let suppressionFrame: ChannelMessage? switch resolvedKind { case let .direct(message, contact): // The firmware cannot surface a self-DM here: decrypt runs against a @@ -230,37 +236,75 @@ extension SyncCoordinator { // contacts[], so an echo of the user's own DM never reaches this arm. text = message.text senderNodeName = nil - senderTimestampDate = message.senderTimestamp textTypeRaw = message.textType snr = message.snr reportedPathLength = message.pathLength contactID = contact?.id channelIndex = nil senderKeyPrefix = message.senderPublicKeyPrefix - case let .channel(message, _): - // Parse "NodeName: text" format for sender name - if let datagramSenderName { - senderNodeName = datagramSenderName - text = message.text - } else { - (senderNodeName, text) = Self.parseChannelMessage(message.text) - } - senderTimestampDate = message.senderTimestamp + conversation = nil + wireTimestamp = UInt32(message.senderTimestamp.timeIntervalSince1970) + harvestIncomingPaths = false + suppressionFrame = nil + case let .channel(message, channel): + (senderNodeName, text) = Self.parseChannelMessage(message.text) textTypeRaw = message.textType snr = message.snr reportedPathLength = message.pathLength contactID = nil channelIndex = message.channelIndex senderKeyPrefix = nil + conversation = channel + wireTimestamp = UInt32(message.senderTimestamp.timeIntervalSince1970) + harvestIncomingPaths = true + suppressionFrame = message + case let .mcoImage(index, mcoImageText, senderName, pathLength, mcoImageSNR, channel): + text = mcoImageText + senderNodeName = senderName + textTypeRaw = MeshTextType.plain.rawValue + snr = mcoImageSNR + reportedPathLength = pathLength + contactID = nil + channelIndex = index + senderKeyPrefix = nil + conversation = channel + wireTimestamp = nil + harvestIncomingPaths = false + // Text Rules identify an MCOimg by its stored text, plain type, and sender time 0. + suppressionFrame = ChannelMessage( + channelIndex: index, + pathLength: pathLength, + textType: MeshTextType.plain.rawValue, + senderTimestamp: Date(timeIntervalSince1970: 0), + text: mcoImageText, + snr: mcoImageSNR + ) } - let timestamp = UInt32(senderTimestampDate.timeIntervalSince1970) - - // Correct invalid timestamps (sender clock wrong) let receiveTime = receivedAt - let (finalTimestamp, timestampCorrected) = Self.correctTimestampIfNeeded(timestamp, receiveTime: receiveTime) - if timestampCorrected { - logger.debug("Corrected invalid \(resolvedKind.logLabel) message timestamp from \(Date(timeIntervalSince1970: TimeInterval(timestamp))) to \(receiveTime)") + let finalTimestamp: UInt32 + let timestampCorrected: Bool + let storedSenderTimestamp: UInt32? + let dedupTimestamp: UInt32 + let rxSenderTimestamp: UInt32? + if let wireTimestamp { + let corrected = Self.correctTimestampIfNeeded(wireTimestamp, receiveTime: receiveTime) + finalTimestamp = corrected.correctedTimestamp + timestampCorrected = corrected.wasCorrected + storedSenderTimestamp = timestampCorrected ? wireTimestamp : nil + dedupTimestamp = wireTimestamp + rxSenderTimestamp = wireTimestamp + if timestampCorrected { + logger.debug("Corrected invalid \(resolvedKind.logLabel) message timestamp from \(Date(timeIntervalSince1970: TimeInterval(wireTimestamp))) to \(receiveTime)") + } + } else { + // An MCOimg has no wire time. The receive second sorts and dedups the row. + // senderTimestamp 0 is that absence, and it is not a packet clock. + finalTimestamp = UInt32(receiveTime.timeIntervalSince1970) + timestampCorrected = true + storedSenderTimestamp = 0 + dedupTimestamp = finalTimestamp + rxSenderTimestamp = nil } let sortDate = Self.sortDate(for: context, receiveTime: receiveTime) @@ -271,17 +315,17 @@ extension SyncCoordinator { let deduplicationKey = Self.fallbackDeduplicationKey( contactID: contactID, channelIndex: channelIndex, senderNodeName: senderNodeName, - timestamp: datagramSenderName == nil ? timestamp : finalTimestamp, + timestamp: dedupTimestamp, content: text ) // Channel lookup joins decrypted 0x88 rows by DeduplicationKey; DMs still - // match timestamp then sender-prefix. + // match timestamp then sender-prefix. An MCOimg has no sender timestamp. let rxResult = await lookupRxLogEntry( dependencies: dependencies, radioID: radioID, channelIndex: channelIndex, - senderTimestamp: datagramSenderName == nil ? timestamp : nil, + senderTimestamp: rxSenderTimestamp, senderPublicKeyPrefix: senderKeyPrefix, defaultPathLength: reportedPathLength, channelDeduplicationKey: channelIndex != nil ? deduplicationKey : nil @@ -293,7 +337,7 @@ extension SyncCoordinator { case .direct: !selfNodeName.isEmpty && MentionUtilities.containsSelfMention(in: text, selfName: selfNodeName) - case .channel: + case .channel, .mcoImage: !selfNodeName.isEmpty && senderNodeName != selfNodeName && MentionUtilities.containsSelfMention(in: text, selfName: selfNodeName) @@ -341,7 +385,7 @@ extension SyncCoordinator { containsSelfMention: hasSelfMention, mentionSeen: false, timestampCorrected: timestampCorrected, - senderTimestamp: timestampCorrected ? timestamp : nil, + senderTimestamp: storedSenderTimestamp, routeType: rxResult.routeType, regionScope: rxResult.regionScope, regionScopeMatches: rxResult.regionScopeMatches @@ -354,69 +398,95 @@ extension SyncCoordinator { scope: scope, preference: preference, dependencies: dependencies ) - case let .channel(message, channel): - if await recordChannelArrivalAndSkipDuplicate( + case .channel, .mcoImage: + guard let suppressionFrame else { return } + await receiveChannelMessage( + messageDTO, + frame: suppressionFrame, deduplicationKey: deduplicationKey, - radioID: radioID, rxResult: rxResult, - snr: snr, - receiveTime: receiveTime, - dependencies: dependencies, - scope: scope - ) { - return - } - guard scope.isCurrent else { return } - if isBlockedSender(senderNodeName) { - return - } - do { - if let channel, try await dependencies.dataStore.shouldSuppressChannelMessage( - messageDTO, frame: message, channel: channel, scope: scope, preference: preference - ) { return } - } catch { - logger.error("Failed to evaluate channel Text Rules: \(error)") - return - } - guard scope.isCurrent else { return } - if await handleChannelReaction( - text: text, - channelIndex: message.channelIndex, - senderNodeName: senderNodeName, + conversation: conversation, + harvestIncomingPaths: harvestIncomingPaths, selfNodeName: selfNodeName, - receiveTime: receiveTime, - radioID: radioID, + scope: scope, + preference: preference, dependencies: dependencies - ) { - return - } - do { - await runTestBeforeMessageSave(messageDTO) - guard try await dependencies.dataStore.saveReceivedChannelMessage( - messageDTO, scope: scope, conversationID: channel?.textRulesID - ), - scope.isCurrent else { return } - let savedDTO: MessageDTO = if datagramSenderName == nil { - try await harvestAndRefreshChannelMessage( - messageDTO: messageDTO, - radioID: radioID, - dependencies: dependencies, - scope: scope - ) - } else { - messageDTO - } - try await indexAndNotifyChannelMessage( - messageDTO: savedDTO, - channel: channel, - indexesReactions: datagramSenderName == nil, + ) + } + } + + private func receiveChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + deduplicationKey: String, + rxResult: RxLogLookupResult, + conversation: ChannelDTO?, + harvestIncomingPaths: Bool, + selfNodeName: String, + scope: ReceiveScope, + preference: TextRulesPreference?, + dependencies: SyncDependencies + ) async { + if await recordChannelArrivalAndSkipDuplicate( + deduplicationKey: deduplicationKey, + radioID: message.radioID, + rxResult: rxResult, + snr: message.snr, + receiveTime: message.createdAt, + dependencies: dependencies, + scope: scope + ) { + return + } + guard scope.isCurrent else { return } + if isBlockedSender(message.senderNodeName) { + return + } + do { + if let conversation, try await dependencies.dataStore.shouldSuppressChannelMessage( + message, frame: frame, channel: conversation, scope: scope, preference: preference + ) { return } + } catch { + logger.error("Failed to evaluate channel Text Rules: \(error)") + return + } + guard scope.isCurrent else { return } + if await handleChannelReaction( + text: message.text, + channelIndex: frame.channelIndex, + senderNodeName: message.senderNodeName, + selfNodeName: selfNodeName, + receiveTime: message.createdAt, + radioID: message.radioID, + dependencies: dependencies + ) { + return + } + do { + await runTestBeforeMessageSave(message) + guard try await dependencies.dataStore.saveReceivedChannelMessage( + message, scope: scope, conversationID: conversation?.textRulesID + ), + scope.isCurrent else { return } + let savedDTO: MessageDTO = if harvestIncomingPaths { + try await harvestAndRefreshChannelMessage( + messageDTO: message, + radioID: message.radioID, dependencies: dependencies, scope: scope ) - await notifyConversationsChanged(scope: scope) - } catch { - logger.error("Failed to save channel message: \(error)") + } else { + message } + try await indexAndNotifyChannelMessage( + messageDTO: savedDTO, + channel: conversation, + dependencies: dependencies, + scope: scope + ) + await notifyConversationsChanged(scope: scope) + } catch { + logger.error("Failed to save channel message: \(error)") } } @@ -525,37 +595,27 @@ extension SyncCoordinator { private func indexAndNotifyChannelMessage( messageDTO: MessageDTO, channel: ChannelDTO?, - indexesReactions: Bool = true, dependencies: SyncDependencies, scope: ReceiveScope ) async throws { guard scope.isCurrent, let channelIndex = messageDTO.channelIndex else { return } - // A channel image is not a reaction target. Indexing it still runs so a - // reaction queued before the image arrived drops that pending key. - let isChannelImage = MCOImageCodec.isChannelImage(channelIndex: channelIndex, text: messageDTO.text) - let senderName = messageDTO.senderNodeName ?? (isChannelImage ? "Unknown" : nil) - if indexesReactions || isChannelImage, let senderName { - let pendingMatches = await dependencies.reactionService.indexMessage( - id: messageDTO.id, - channelIndex: channelIndex, - senderName: senderName, - text: messageDTO.text, - timestamp: messageDTO.reactionTimestamp + let pendingMatches = await pendingChannelReactions( + for: messageDTO, + channelIndex: channelIndex, + dependencies: dependencies + ) + for pending in pendingMatches { + guard scope.isCurrent else { return } + let reactionDTO = ReactionDTO( + messageID: messageDTO.id, + emoji: pending.parsed.emoji, + senderName: pending.senderNodeName, + messageHash: pending.parsed.messageHash, + rawText: pending.rawText, + channelIndex: pending.channelIndex, + radioID: pending.radioID ) - - for pending in pendingMatches { - guard scope.isCurrent else { return } - let reactionDTO = ReactionDTO( - messageID: messageDTO.id, - emoji: pending.parsed.emoji, - senderName: pending.senderNodeName, - messageHash: pending.parsed.messageHash, - rawText: pending.rawText, - channelIndex: pending.channelIndex, - radioID: pending.radioID - ) - await persistReactionIfNew(reactionDTO, dependencies: dependencies) - } + await persistReactionIfNew(reactionDTO, dependencies: dependencies) } guard scope.isCurrent else { return } @@ -573,6 +633,35 @@ extension SyncCoordinator { } } + /// A channel MCOimg with no reaction target is not indexed. + private func pendingChannelReactions( + for messageDTO: MessageDTO, + channelIndex: UInt8, + dependencies: SyncDependencies + ) async -> [PendingReaction] { + if let target = messageDTO.mcoImageReactionTarget() { + return await dependencies.reactionService.indexMessage( + id: messageDTO.id, + channelIndex: channelIndex, + senderName: target.senderName, + text: messageDTO.text, + timestamp: messageDTO.reactionTimestamp, + messageHash: target.messageHash + ) + } + if MCOImageCodec.isChannelMCOImage(channelIndex: channelIndex, text: messageDTO.text) { + return [] + } + guard let senderName = messageDTO.senderNodeName else { return [] } + return await dependencies.reactionService.indexMessage( + id: messageDTO.id, + channelIndex: channelIndex, + senderName: senderName, + text: messageDTO.text, + timestamp: messageDTO.reactionTimestamp + ) + } + // MARK: - Signed Message Handler private func wireSignedMessageHandler(dependencies: SyncDependencies) async { diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift index 5551b9a52f..8eea1bdb22 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift @@ -209,69 +209,119 @@ extension SyncCoordinator { logger.debug("DB lookup: selfNodeName='\(selfNodeName)', targetSender=\(parsed.targetSender), hash=\(parsed.messageHash)") - if let targetMessage = try? await dependencies.dataStore.findChannelMessageForReaction( - radioID: radioID, - channelIndex: channelIndex, - parsedReaction: parsed, - localNodeName: selfNodeName.isEmpty ? nil : selfNodeName, - timestampWindow: timestampWindow, - limit: 200 - ) { - let targetMessageID = targetMessage.id - let reactionDTO = ReactionDTO( - messageID: targetMessageID, - emoji: parsed.emoji, - senderName: senderName, - messageHash: parsed.messageHash, - rawText: text, + func queuePending() async { + await dependencies.reactionService.queuePendingReaction( + parsed: parsed, channelIndex: channelIndex, + senderNodeName: senderName, + rawText: text, radioID: radioID ) - if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { - let targetSenderName: String? = if targetMessage.direction == .outgoing { - selfNodeName.isEmpty ? nil : selfNodeName - } else { - targetMessage.senderNodeName - } - - if let targetSenderName { - // Index for future reactions (pending matches not needed here since - // message exists in DB, so pending reactions would also match via DB fallback) - _ = await dependencies.reactionService.indexMessage( - id: targetMessageID, - channelIndex: channelIndex, - senderName: targetSenderName, - text: targetMessage.text, - timestamp: targetMessage.reactionTimestamp - ) - } - - logger.debug("Saved reaction \(parsed.emoji) to message \(targetMessageID) via DB lookup") - } + } + let windowedMatch: MessageDTO? + do { + windowedMatch = try await dependencies.dataStore.findChannelMessageForReaction( + radioID: radioID, + channelIndex: channelIndex, + parsedReaction: parsed, + localNodeName: selfNodeName.isEmpty ? nil : selfNodeName, + timestampWindow: timestampWindow, + limit: 200 + ) + } catch { + await queuePending() + return true + } + if let windowedMatch { + await attachChannelReaction( + to: windowedMatch, + parsed: parsed, + text: text, + channelIndex: channelIndex, + senderName: senderName, + selfNodeName: selfNodeName, + radioID: radioID, + dependencies: dependencies + ) return true } - if await (try? dependencies.dataStore.channelImageMatchesReaction( - radioID: radioID, - channelIndex: channelIndex, - parsedReaction: parsed, - localNodeName: selfNodeName.isEmpty ? nil : selfNodeName, - timestampWindow: timestampWindow, - limit: 200 - )) == true { + let datagramMatch: MessageDTO? + do { + datagramMatch = try await dependencies.dataStore.findChannelDatagramForReaction( + radioID: radioID, + channelIndex: channelIndex, + parsedReaction: parsed + ) + } catch { + await queuePending() + return true + } + if let datagramMatch { + await attachChannelReaction( + to: datagramMatch, + parsed: parsed, + text: text, + channelIndex: channelIndex, + senderName: senderName, + selfNodeName: selfNodeName, + radioID: radioID, + dependencies: dependencies + ) return true } - // Queue reaction for later matching when target message arrives - await dependencies.reactionService.queuePendingReaction( - parsed: parsed, - channelIndex: channelIndex, - senderNodeName: senderName, + await queuePending() + return true + } + + private func attachChannelReaction( + to targetMessage: MessageDTO, + parsed: ParsedReaction, + text: String, + channelIndex: UInt8, + senderName: String, + selfNodeName: String, + radioID: UUID, + dependencies: SyncDependencies + ) async { + let reactionDTO = ReactionDTO( + messageID: targetMessage.id, + emoji: parsed.emoji, + senderName: senderName, + messageHash: parsed.messageHash, rawText: text, + channelIndex: channelIndex, radioID: radioID ) - return true + guard await persistReactionIfNew(reactionDTO, dependencies: dependencies) else { return } + if let target = targetMessage.mcoImageReactionTarget() { + _ = await dependencies.reactionService.indexMessage( + id: targetMessage.id, + channelIndex: channelIndex, + senderName: target.senderName, + text: targetMessage.text, + timestamp: targetMessage.reactionTimestamp, + messageHash: target.messageHash + ) + } else { + let targetSenderName: String? = if targetMessage.direction == .outgoing { + selfNodeName.isEmpty ? nil : selfNodeName + } else { + targetMessage.senderNodeName + } + if let targetSenderName { + _ = await dependencies.reactionService.indexMessage( + id: targetMessage.id, + channelIndex: channelIndex, + senderName: targetSenderName, + text: targetMessage.text, + timestamp: targetMessage.reactionTimestamp + ) + } + } + logger.debug("Saved reaction \(parsed.emoji) to message \(targetMessage.id) via DB lookup") } /// Computes a bounded timestamp window around the given time for reaction matching. @@ -371,7 +421,7 @@ extension SyncCoordinator { for candidate in candidates { // Skip messages that are themselves reactions if ReactionParser.isReactionText(candidate.text, isDM: false) { continue } - if MCOImageCodec.isChannelImage(channelIndex: candidate.channelIndex, text: candidate.text) { continue } + if candidate.isChannelMCOImage { continue } // For channel messages, the Dart hash includes the sender name let candidateSenderName: String? = if candidate.direction == .outgoing { @@ -484,7 +534,7 @@ extension SyncCoordinator { for candidate in candidates { if ReactionParser.isReactionText(candidate.text, isDM: false) { continue } - if MCOImageCodec.isChannelImage(channelIndex: candidate.channelIndex, text: candidate.text) { continue } + if candidate.isChannelMCOImage { continue } // Verify sender name hash let candidateSenderName: String? = if candidate.direction == .outgoing { diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift index 71fdfb0370..224877da8a 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift @@ -1,7 +1,7 @@ import Foundation import MeshCore -/// Reads the sender name and stored MCOimg text without decoding the image. +/// Reads the sender name and stored MCOimg text without decoding the pixels. public enum MCOImageTransport { public static let applicationDataType: UInt16 = 0x0120 public static let imageSubtype: UInt8 = 0x01 @@ -12,7 +12,16 @@ public enum MCOImageTransport { private static let maxVarintBytes = 5 public static func encode(text: String, senderName: String) throws -> Data { - let payload = try MCOImageCodec.channelAppPayload(fromText: text) + try framed(MCOImageCodec.channelAppPayload(fromText: text), senderName: senderName) + } + + /// The group-datagram `data` field for a stored row: varint name framing plus the stored app payload. + /// Transmit still uses `encode`, which upgrades a v3 payload before it goes on the air. + public static func dataField(text: String, senderName: String) throws -> Data { + try framed(MCOImageCodec.appPayload(fromText: text), senderName: senderName) + } + + private static func framed(_ payload: Data, senderName: String) -> Data { let name = Data(senderName.utf8) var writer = MCOImageBitWriter() writer.varUint(name.count) diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift index f8623598cd..67d9ec429c 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift @@ -12,14 +12,14 @@ public enum MCOImageCodec { private static let versionMask: UInt8 = 0x0F private static let subtypeShift = 4 - public static func isImageText(_ text: String) -> Bool { + public static func isMCOImageText(_ text: String) -> Bool { version(in: text.trimmingCharacters(in: .whitespacesAndNewlines)) != nil } /// A channel row whose text is MCOimg. Group data and a channel text packet /// with an `im3:` or `im4:` body are the same stored shape. - public static func isChannelImage(channelIndex: UInt8?, text: String) -> Bool { - channelIndex != nil && isImageText(text) + public static func isChannelMCOImage(channelIndex: UInt8?, text: String) -> Bool { + channelIndex != nil && isMCOImageText(text) } public static func content(from text: String) -> MCOImageContent? { diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift index 5879408040..d4d66bd9b7 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift @@ -18,7 +18,9 @@ struct MCOImageBinarySendTests { try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "救援隊", firmwareVersion: 12)) let channel = ChannelDTO.testChannel(radioID: radioID, floodScope: .region("Alpha")) try await store.saveChannel(channel) - let legacy = MessageDTO.testChannelMessage(radioID: radioID, channelIndex: channel.index, text: fixture) + let legacy = MessageDTO.testChannelMessage( + radioID: radioID, channelIndex: channel.index, text: fixture, senderNodeName: "救援隊" + ) try await store.saveMessage(legacy) switch path { case .inline: @@ -58,7 +60,7 @@ struct MCOImageBinarySendTests { try await service.sendPendingChannelMessage(messageID: message.id) let firstCalls = await session.sendChannelDataInvocations #expect(firstCalls[0].payload == firstCalls[1].payload) - let prepared = try await service.prepareImageForResend(message) + let prepared = try await service.prepareMCOImageForResend(message) #expect(prepared.text.hasPrefix("im4:")) #expect(try await store.fetchMessage(id: message.id)?.text == prepared.text) let expected = try MCOImageTransport.encode(text: prepared.text, senderName: "Radio") @@ -72,7 +74,7 @@ struct MCOImageBinarySendTests { } @Test - func `complete UTF8 binary budget accepts 165 and rejects 166 before admission or drain`() async throws { + func `complete UTF8 binary budget accepts 165 and rejects 166 at admission`() async throws { let radioID = UUID() let store = MockPersistenceStore() let session = MockMeshCoreSession() @@ -90,16 +92,17 @@ struct MCOImageBinarySendTests { } #expect(try await store.fetchMessages(radioID: radioID, channelIndex: 0, limit: 10, offset: 0).count == 1) try await store.saveDevice(.testDevice(radioID: radioID, nodeName: name + "A")) - await #expect(throws: MessageServiceError.self) { - try await service.sendPendingChannelMessage(messageID: message.id) - } - #expect(await session.sendChannelDataInvocations.count == 1) + try await service.sendPendingChannelMessage(messageID: message.id) + let calls = await session.sendChannelDataInvocations + #expect(calls.count == 2) + #expect(calls[0].payload == calls[1].payload) + #expect(calls[0].payload.count == 165) #expect(await session.sendChannelMessageInvocations.isEmpty) - #expect(try await store.fetchMessage(id: message.id)?.status == .failed) + #expect(try await store.fetchMessage(id: message.id)?.status == .sent) } @Test(arguments: ["im3:!", "im4:!", "im5:AA"]) - func `damaged and unsupported image text never falls through to channel text`(text: String) async throws { + func `damaged and unsupported MCOimg text never falls through to channel text`(text: String) async throws { let radioID = UUID() let store = MockPersistenceStore() let session = MockMeshCoreSession() @@ -140,7 +143,7 @@ struct MCOImageBinarySendTests { @Test(arguments: [MeshCoreError.notConnected, .deviceError(code: 3)]) @MainActor - func `persisted legacy image replays as identical binary after disconnect`(failure: MeshCoreError) async throws { + func `persisted legacy MCOimg replays as identical binary after disconnect`(failure: MeshCoreError) async throws { let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) let radioID = UUID() try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio")) @@ -200,8 +203,8 @@ struct MCOImageBinarySendTests { #expect(calls.count == 2) #expect(calls[0].payload == calls[1].payload) #expect(await session.sendChannelMessageInvocations.isEmpty) - #expect(ChatSendQueueService.isTransientChannelMessageError(MeshCoreError.deviceError(code: 3), isImage: true)) - #expect(!ChatSendQueueService.isTransientChannelMessageError(MeshCoreError.deviceError(code: 3), isImage: false)) + #expect(ChatSendQueueService.isTransientChannelMessageError(MeshCoreError.deviceError(code: 3), sentDatagram: true)) + #expect(!ChatSendQueueService.isTransientChannelMessageError(MeshCoreError.deviceError(code: 3), sentDatagram: false)) } @Test diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift index 1fb1b929f0..93fbfbb0d4 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift @@ -80,4 +80,77 @@ struct MCOImageReceiveIntegrationTests { } } } + + @Test + func `a recently blocked MCOimg is suppressed and an unblocked MCOimg is saved`() async throws { + let radioID = UUID() + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + try await store.saveDevice(.testDevice(id: radioID)) + let channel = ChannelDTO.testChannel(radioID: radioID, index: 2) + try await store.saveChannel(channel) + let savedChannel = try #require(try await store.fetchChannel(radioID: radioID, index: channel.index)) + let conversationID = try #require(savedChannel.textRulesID) + let services = ServiceContainer( + session: MeshCoreSession(transport: SimulatorMockTransport()), + dataStore: store, + radioID: radioID + ) + services.notificationService.isSuppressingNotifications = true + defer { Task { await services.tearDown() } } + let poller = MockMessagePollingService() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: poller), + radioID: radioID + ) + + let sender = "Peer" + let blockedPayload = Data([0x14, 0, 0, 0, 0]) + let allowedPayload = try #require(Data(base64Encoded: "E3oBjQBCvgE=")) + let blockedText = try MCOImageCodec.text(fromAppPayload: blockedPayload) + let allowedText = try MCOImageCodec.text(fromAppPayload: allowedPayload) + var preference = TextRulesPreference() + preference.append(.init(phrase: "blocked", lookIn: .message, match: .contains)) + try await store.recordRecentlyBlockedMessage(RecentlyBlockedMessageDTO( + identity: .init( + radioID: radioID, + conversationID: conversationID, + senderPrefix: nil, + senderTimestamp: 0, + textType: MeshTextType.plain.rawValue, + wireText: Data(blockedText.utf8) + ), + arrivedAt: Date(), + body: "blocked", + sender: nil, + conversationName: savedChannel.name, + radioName: nil, + match: #require(preference.firstMatch(body: "blocked", sender: nil)) + )) + + let handler = try #require(await poller.capturedChannelDatagramHandler) + let scope = try #require(try await store.captureReceiveScope(radioID: radioID, link: ReceiveScope.Lifetime())) + await handler( + datagram(channel: savedChannel, sender: sender, payload: blockedPayload), + savedChannel, .live, scope, nil, Date() + ) + await handler( + datagram(channel: savedChannel, sender: sender, payload: allowedPayload), + savedChannel, .live, scope, nil, Date() + ) + + let messages = try await store.fetchMessages(radioID: radioID, channelIndex: savedChannel.index) + #expect(messages.map(\.text) == [allowedText]) + #expect(messages.first?.senderNodeName == sender) + } + + private func datagram(channel: ChannelDTO, sender: String, payload: Data) -> ChannelDatagram { + ChannelDatagram( + channelIndex: channel.index, + pathLength: 2, + dataType: MCOImageTransport.applicationDataType, + data: Data([UInt8(sender.utf8.count)]) + Data(sender.utf8) + payload, + snr: 6.25 + ) + } } diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift index d33be4f8ba..34fb35dd2b 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift @@ -39,12 +39,12 @@ struct MCOImageSendIntegrationTests { } @Test - func `image resend persists exactly the text that queue envelopes and ACK prediction use`() async throws { + func `MCOimg resend persists exactly the text that queue envelopes and ACK prediction use`() async throws { let store = MockPersistenceStore() let service = MessageService(session: MockMeshCoreSession(), dataStore: store, contactService: nil) let contact = ContactDTO.testContact(radioID: UUID()) let original = try await service.createPendingMessage(text: fixture, to: contact) - let refreshed = try await service.prepareImageForResend(original) + let refreshed = try await service.prepareMCOImageForResend(original) let originalPayload = try MCOImageCodec.appPayload(fromText: original.text) let refreshedPayload = try MCOImageCodec.appPayload(fromText: refreshed.text) #expect(originalPayload.dropFirst(2) == refreshedPayload.dropFirst(2)) @@ -54,11 +54,11 @@ struct MCOImageSendIntegrationTests { } @Test - func `nonimage resend preparation preserves the original wire text`() async throws { + func `text resend preparation preserves the original wire text`() async throws { let store = MockPersistenceStore() let service = MessageService(session: MockMeshCoreSession(), dataStore: store, contactService: nil) let contact = ContactDTO.testContact(radioID: UUID()) let original = try await service.createPendingMessage(text: "hello", to: contact) - #expect(try await service.prepareImageForResend(original) == original) + #expect(try await service.prepareMCOImageForResend(original) == original) } } diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift index d6d99743a3..4d3163b598 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift @@ -32,7 +32,7 @@ struct MCOImageTransportTests { } @Test - func `v4 text omits subtype byte and unknown image versions survive for placeholders`() throws { + func `v4 text omits subtype byte and unknown MCOimg versions survive for placeholders`() throws { for version: UInt8 in [0x14, 0x15] { let payload = Data([0, version, 0, 0]) let image = try #require(MCOImageTransport.decode(datagram(payload: payload))) @@ -72,14 +72,20 @@ struct MCOImageTransportTests { let time = Date(timeIntervalSince1970: 100) var duplicates = MCOImageDatagramDuplicates() let packet = datagram() - #expect(duplicates.admit(packet, radioID: radioID, receivedAt: time)) - #expect(!duplicates.admit(packet, radioID: radioID, receivedAt: time.addingTimeInterval(1))) - #expect(duplicates.admit(packet, radioID: UUID(), receivedAt: time.addingTimeInterval(2))) - #expect(duplicates.admit(datagram(channelIndex: 3), radioID: radioID, receivedAt: time.addingTimeInterval(3))) + let sameRadio = duplicates.admit(packet, radioID: radioID, receivedAt: time) + let repeatPacket = duplicates.admit(packet, radioID: radioID, receivedAt: time.addingTimeInterval(1)) + let otherRadio = duplicates.admit(packet, radioID: UUID(), receivedAt: time.addingTimeInterval(2)) + let otherChannel = duplicates.admit(datagram(channelIndex: 3), radioID: radioID, receivedAt: time.addingTimeInterval(3)) var newNonce = packet.data newNonce[newNonce.startIndex + 1 + "Peer:名".utf8.count + 1] ^= 1 - #expect(duplicates.admit(datagram(payload: newNonce), radioID: radioID, receivedAt: time.addingTimeInterval(4))) - #expect(duplicates.admit(packet, radioID: radioID, receivedAt: time.addingTimeInterval(MCOImageDatagramDuplicates.lifetime))) + let changedNonce = duplicates.admit(datagram(payload: newNonce), radioID: radioID, receivedAt: time.addingTimeInterval(4)) + let expired = duplicates.admit(packet, radioID: radioID, receivedAt: time.addingTimeInterval(MCOImageDatagramDuplicates.lifetime)) + #expect(sameRadio) + #expect(!repeatPacket) + #expect(otherRadio) + #expect(otherChannel) + #expect(changedNonce) + #expect(expired) } @Test @@ -89,9 +95,11 @@ struct MCOImageTransportTests { var duplicates = MCOImageDatagramDuplicates() for nonce in 0...MCOImageDatagramDuplicates.capacity { let packet = datagram(payload: Data([0, 0x13, UInt8(nonce)])) - #expect(duplicates.admit(packet, radioID: radioID, receivedAt: time)) + let admitted = duplicates.admit(packet, radioID: radioID, receivedAt: time) + #expect(admitted) } - #expect(duplicates.admit(datagram(payload: Data([0, 0x13, 0])), radioID: radioID, receivedAt: time)) + let evicted = duplicates.admit(datagram(payload: Data([0, 0x13, 0])), radioID: radioID, receivedAt: time) + #expect(evicted) } private actor Receipt { @@ -103,7 +111,7 @@ struct MCOImageTransportTests { } @Test - func `initial sync admits image datagrams while continuing to drain unknown application data`() async throws { + func `initial sync admits MCOimg datagrams while continuing to drain unknown application data`() async throws { let radioID = UUID() let store = try await PersistenceStore.createTestDataStore(radioID: radioID) let session = MockMeshCoreSession() diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageV3CodecTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageV3CodecTests.swift index 7240eb6b52..30a79ad4f7 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageV3CodecTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageV3CodecTests.swift @@ -59,7 +59,7 @@ struct MCOImageV3CodecTests { } } - @Test func `truncation and trailing bytes do not render partial images`() throws { + @Test func `truncation and trailing bytes do not render a partial MCOimg`() throws { for fixture in try fixtures() { let body = try #require(Data(base64Encoded: fixture.bodyBase64)) for count in 0.. MessageDTO? { + if let error = stubbedFetchMessageError { + throw error + } + return messages.values + .filter { $0.radioID == radioID && $0.channelIndex == channelIndex } + .sorted { $0.createdAt > $1.createdAt } + .first { candidate in + guard candidate.isDatagramMCOImage, + let target = candidate.mcoImageReactionTarget() else { return false } + return target.senderName == parsedReaction.targetSender + && target.messageHash == parsedReaction.messageHash + } + } + public func fetchChannelMessageCandidates( radioID: UUID, channelIndex: UInt8, diff --git a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift index d952efdd34..06461c967c 100644 --- a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift @@ -1091,101 +1091,232 @@ struct PersistenceStoreTests { } @Test - func `Channel image is not a reaction match`() async throws { + func `Datagram channel MCOimg matches outside the window and the newer copy wins`() async throws { let store = try await createTestStore() let device = createTestDevice() try await store.saveDevice(device) + let text = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) + let sender = "Ada" + let hash = try ReactionParser.generateUntimedHash(MCOImageTransport.dataField(text: text, senderName: sender)) + let parsed = try #require(ReactionParser.parse("@[\(sender)]👍\n\(hash)")) + let older = datagramImage( + radioID: device.id, channelIndex: 0, text: text, sender: sender, + createdAt: Date(timeIntervalSince1970: 1000) + ) + let newer = datagramImage( + radioID: device.id, channelIndex: 0, text: text, sender: sender, + createdAt: Date(timeIntervalSince1970: 2000) + ) + try await store.saveMessage(older) + try await store.saveMessage(newer) + + let found = try await store.findChannelDatagramForReaction( + radioID: device.id, channelIndex: 0, parsedReaction: parsed + ) + #expect(found?.id == newer.id) + let now = UInt32(Date().timeIntervalSince1970) + let missed = try await store.findChannelMessageForReaction( + radioID: device.id, + channelIndex: 0, + parsedReaction: parsed, + localNodeName: "Local", + timestampWindow: (now - 300)...(now + 300), + limit: 200 + ) + #expect(missed == nil) + } - let timestamp: UInt32 = 1_700_000_200 - let channelIndex: UInt8 = 0 - let createdAt = Date(timeIntervalSince1970: TimeInterval(timestamp)) - let image = MessageDTO.testChannelMessage( + @Test + func `Timed channel MCOimg matches in the window and a zero sender timestamp uses the untimed hash`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + let text = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) + let sender = "Ada" + let timestamp = UInt32(Date().timeIntervalSince1970) + var timed = MessageDTO.testChannelMessage( radioID: device.id, - channelIndex: channelIndex, - text: "im4:pixel", + channelIndex: 1, + text: text, timestamp: timestamp, - createdAt: createdAt, + createdAt: Date(timeIntervalSince1970: TimeInterval(timestamp)), direction: .incoming, status: .delivered, - senderNodeName: "RemoteNode" + senderNodeName: sender + ) + timed.senderTimestamp = nil + timed.timestampCorrected = false + var datagram = datagramImage( + radioID: device.id, channelIndex: 2, text: text, sender: sender, + createdAt: Date(timeIntervalSince1970: TimeInterval(timestamp)) + ) + datagram.timestamp = timestamp + try await store.saveMessage(timed) + try await store.saveMessage(datagram) + + let timedHash = ReactionParser.generateMessageHash(text: text, timestamp: timed.reactionTimestamp) + let untimedHash = try ReactionParser.generateUntimedHash(MCOImageTransport.dataField(text: text, senderName: sender)) + let timedParsed = try #require(ReactionParser.parse("@[\(sender)]👍\n\(timedHash)")) + let untimedParsed = try #require(ReactionParser.parse("@[\(sender)]🔥\n\(untimedHash)")) + let window = (timestamp - 300)...(timestamp + 300) + + let foundTimed = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 1, parsedReaction: timedParsed, + localNodeName: "Local", timestampWindow: window, limit: 200 ) - let text = MessageDTO.testChannelMessage( + let missedUntimed = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 1, parsedReaction: untimedParsed, + localNodeName: "Local", timestampWindow: window, limit: 200 + ) + let missedDatagram = try await store.findChannelDatagramForReaction( + radioID: device.id, channelIndex: 1, parsedReaction: untimedParsed + ) + #expect(foundTimed?.id == timed.id) + #expect(missedUntimed == nil) + #expect(missedDatagram == nil) + + let windowedDatagram = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 2, parsedReaction: untimedParsed, + localNodeName: "Local", timestampWindow: window, limit: 200 + ) + let foundDatagram = try await store.findChannelDatagramForReaction( + radioID: device.id, channelIndex: 2, parsedReaction: untimedParsed + ) + #expect(windowedDatagram == nil) + #expect(foundDatagram?.id == datagram.id) + } + + @Test + func `Outgoing datagram MCOimg keeps the stored sender name after a rename`() async throws { + let store = try await createTestStore() + var device = createTestDevice().copy { $0.nodeName = "Painter" } + try await store.saveDevice(device) + let text = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) + let image = MessageDTO.testChannelMessage( radioID: device.id, - channelIndex: channelIndex, - text: "Plain channel text", - timestamp: timestamp, - createdAt: createdAt, - direction: .incoming, - status: .delivered, - senderNodeName: "RemoteNode" + channelIndex: 0, + text: text, + timestamp: 1_000_000, + createdAt: Date(timeIntervalSince1970: 1_000_000), + direction: .outgoing, + status: .sent, + senderNodeName: "Painter" ) try await store.saveMessage(image) - try await store.saveMessage(text) + device = device.copy { $0.nodeName = "Other" } + try await store.saveDevice(device) - let reactionService = ReactionService() - let imageReaction = reactionService.buildReactionText( - emoji: "👍", - targetSender: "RemoteNode", - targetText: image.text, - targetTimestamp: image.reactionTimestamp + let hash = try ReactionParser.generateUntimedHash(MCOImageTransport.dataField(text: text, senderName: "Painter")) + let parsed = try #require(ReactionParser.parse("@[Painter]👍\n\(hash)")) + let renamed = try #require(ReactionParser.parse("@[Other]👍\n\(hash)")) + let found = try await store.findChannelDatagramForReaction( + radioID: device.id, channelIndex: 0, parsedReaction: parsed ) - let textReaction = reactionService.buildReactionText( - emoji: "👍", - targetSender: "RemoteNode", - targetText: text.text, - targetTimestamp: text.reactionTimestamp + let missed = try await store.findChannelDatagramForReaction( + radioID: device.id, channelIndex: 0, parsedReaction: renamed ) - let imageParsed = try #require(ReactionParser.parse(imageReaction)) - let textParsed = try #require(ReactionParser.parse(textReaction)) - let window = (timestamp - 300)...(timestamp + 300) + #expect(found?.id == image.id) + #expect(missed == nil) + #expect(try await store.fetchDevice(radioID: device.radioID)?.nodeName == "Other") + } - let foundImage = try await store.findChannelMessageForReaction( + @Test + func `Group text outside the window does not match and an empty sender does not admit`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + let text = MessageDTO.testChannelMessage( radioID: device.id, - channelIndex: channelIndex, - parsedReaction: imageParsed, - localNodeName: "LocalNode", - timestampWindow: window, - limit: 200 + channelIndex: 0, + text: "Plain channel text", + timestamp: 100, + createdAt: Date(timeIntervalSince1970: 100), + direction: .incoming, + status: .delivered, + senderNodeName: "Ada" ) - let foundText = try await store.findChannelMessageForReaction( + var empty = try datagramImage( radioID: device.id, - channelIndex: channelIndex, - parsedReaction: textParsed, - localNodeName: "LocalNode", - timestampWindow: window, - limit: 200 + channelIndex: 0, + text: MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])), + sender: "", + createdAt: Date(timeIntervalSince1970: 100) ) - #expect(foundImage == nil) - #expect(foundText?.id == text.id) - #expect(try await store.channelImageMatchesReaction( - radioID: device.id, - channelIndex: channelIndex, - parsedReaction: imageParsed, - localNodeName: "LocalNode", - timestampWindow: window, - limit: 200 - )) - #expect(try await store.channelImageMatchesReaction( - radioID: device.id, - channelIndex: channelIndex, - parsedReaction: textParsed, - localNodeName: "LocalNode", - timestampWindow: window, - limit: 200 - ) == false) + empty.senderNodeName = "" + try await store.saveMessage(text) + try await store.saveMessage(empty) + let parsed = try #require(ReactionParser.parse( + ReactionService().buildReactionText( + emoji: "👍", targetSender: "Ada", targetText: text.text, targetTimestamp: text.reactionTimestamp + ) + )) + let now = UInt32(Date().timeIntervalSince1970) + let found = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 0, parsedReaction: parsed, + localNodeName: "Local", timestampWindow: (now - 300)...(now + 300), limit: 200 + ) + #expect(found == nil) let admission = try await store.admitReaction(ReactionDTO( - messageID: image.id, + messageID: empty.id, emoji: "👍", - senderName: "RemoteNode", - messageHash: imageParsed.messageHash, - rawText: imageReaction, - channelIndex: image.channelIndex, + senderName: "Bea", + messageHash: "aaaaa", + rawText: "@[]👍\naaaaa", + channelIndex: empty.channelIndex, radioID: device.id )) #expect(admission == nil) - #expect(try await store.fetchReactions(for: image.id).isEmpty) - #expect(try await store.fetchMessage(id: image.id)?.reactionSummary == nil) + #expect(try await store.fetchReactions(for: empty.id).isEmpty) + } + + @Test + func `Direct message MCOimg matches the timed hash`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + let timestamp: UInt32 = 1_700_000_200 + let contactID = UUID() + let message = MessageDTO.testDirectMessage( + radioID: device.id, + contactID: contactID, + text: "im4:pixel", + timestamp: timestamp, + createdAt: Date(timeIntervalSince1970: TimeInterval(timestamp)), + direction: .incoming, + status: .delivered + ) + try await store.saveMessage(message) + let hash = ReactionParser.generateMessageHash(text: message.text, timestamp: message.reactionTimestamp) + let found = try await store.findDMMessageForReaction( + radioID: device.id, + contactID: contactID, + messageHash: hash, + timestampWindow: (timestamp - 300)...(timestamp + 300), + limit: 200 + ) + #expect(found?.id == message.id) + } + + private func datagramImage( + radioID: UUID, + channelIndex: UInt8, + text: String, + sender: String, + createdAt: Date + ) -> MessageDTO { + var message = MessageDTO.testChannelMessage( + radioID: radioID, + channelIndex: channelIndex, + text: text, + timestamp: UInt32(createdAt.timeIntervalSince1970), + createdAt: createdAt, + direction: .incoming, + status: .delivered, + senderNodeName: sender + ) + message.senderTimestamp = 0 + return message } @Test diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift index 1313676f0a..b1eeb2649a 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueReactionTests.swift @@ -210,7 +210,7 @@ struct ChatSendQueueReactionTests { } @Test - func `a channel image does not enqueue a reaction`() async throws { + func `a channel MCOimg with an empty sender does not enqueue a reaction`() async throws { let (env, _) = try await makeChannelEnvironment() do { let connection = try #require(env.manager.currentConnection) @@ -219,7 +219,7 @@ struct ChatSendQueueReactionTests { text: "im4:pixel", direction: .incoming, status: .delivered, - senderNodeName: "Ada" + senderNodeName: "" ) try await env.manager.persistenceStore.saveMessage(image) let queue = try #require(connection.services.chatSendQueueService) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift index 068ac9a3de..490dadd777 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift @@ -215,7 +215,8 @@ struct ChatSendQueueServiceTests { @Test func `isTransientChannelMessageError unwraps sessionError on deviceError(2)`() { let wrapped = MessageServiceError.sessionError(.deviceError(code: 2)) - #expect(ChatSendQueueService.isTransientChannelMessageError(wrapped) == true) + #expect(ChatSendQueueService.isTransientChannelMessageError(wrapped, sentDatagram: false) == true) + #expect(ChatSendQueueService.isTransientChannelMessageError(wrapped, sentDatagram: true) == true) } /// A DM-path classifier must not park on code 2 — only code 3 is the DM @@ -226,12 +227,11 @@ struct ChatSendQueueServiceTests { #expect(ChatSendQueueService.isTransientDirectMessageError(wrapped) == false) } - /// Symmetric guard for the channel classifier: code 3 is the DM signal, - /// not the channel one. @Test - func `isTransientChannelMessageError treats deviceError(3) as terminal`() { + func `isTransientChannelMessageError treats deviceError(3) as terminal for text`() { let wrapped = MessageServiceError.sessionError(.deviceError(code: 3)) - #expect(ChatSendQueueService.isTransientChannelMessageError(wrapped) == false) + #expect(ChatSendQueueService.isTransientChannelMessageError(wrapped, sentDatagram: false) == false) + #expect(ChatSendQueueService.isTransientChannelMessageError(wrapped, sentDatagram: true) == true) } /// Regression: the channel-cap helper recognises the raw @@ -999,6 +999,47 @@ struct ChatSendQueueServiceTests { messageID: pending.id ) } + + @Test + func `enqueueReaction returns a row for a channel MCOimg and nil when the sender name is empty`() async throws { + let store = try Self.makeStore() + let radioID = UUID() + try await store.saveDevice(.testDevice(id: radioID, radioID: radioID, nodeName: "Painter")) + try await store.saveChannel(.testChannel(radioID: radioID, index: 0)) + let text = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) + let image = MessageDTO.testChannelMessage( + radioID: radioID, + channelIndex: 0, + text: text, + direction: .outgoing, + status: .sent, + senderNodeName: "Painter" + ) + try await store.saveMessage(image) + let queue = await ChatSendQueueService( + radioID: radioID, + dataStore: store, + messageService: Self.makeMessageService(dataStore: store), + channelService: Self.makeChannelService(dataStore: store), + reactionService: ReactionService(), + config: ChatSendQueueConfig(transportWaitTimeout: 0.05) + ) + let outgoing = try await queue.enqueueReaction(to: image, emoji: "👍", senderName: "Painter") + let saved = try #require(outgoing) + let hash = try ReactionParser.generateUntimedHash(MCOImageTransport.dataField(text: text, senderName: "Painter")) + #expect(saved.text == "@[Painter]👍\n\(hash)") + #expect(try await store.fetchMessage(id: saved.id) != nil) + + var unnamed = image + unnamed.id = UUID() + unnamed.senderNodeName = "" + try await store.saveMessage(unnamed) + let refused = try await queue.enqueueReaction(to: unnamed, emoji: "👍", senderName: "Painter") + #expect(refused == nil) + let messages = try await store.fetchMessages(radioID: radioID, channelIndex: 0) + #expect(messages.contains { $0.reactionTargetMessageID == unnamed.id } == false) + await queue.shutdown() + } } private struct ForcedSaveFailure: Error {} diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ReactionParserTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ReactionParserTests.swift index 3234fe58dd..0105ca80fa 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ReactionParserTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ReactionParserTests.swift @@ -409,4 +409,39 @@ struct ReactionParserTests { let expectedHash = ReactionParser.generateMessageHash(text: targetText, timestamp: timestamp) #expect(parsed?.messageHash == expectedHash) } + + @Test + func `Untimed hash ignores the timestamp and differs from the timed im4 hash`() throws { + let payload = Data([0x14, 0, 0, 0, 0]) + let sender = "Ada" + let text = try MCOImageCodec.text(fromAppPayload: payload) + let data = try MCOImageTransport.dataField(text: text, senderName: sender) + let first = ReactionParser.generateUntimedHash(data) + let second = ReactionParser.generateUntimedHash(data) + #expect(first == second) + let im4 = try MCOImageCodec.text(fromAppPayload: payload) + let timed = ReactionParser.generateMessageHash(text: im4, timestamp: 1_700_000_000) + let later = ReactionParser.generateMessageHash(text: im4, timestamp: 1_700_000_100) + #expect(first != timed) + #expect(timed != later) + + var changed = payload + changed[1] = changed[1] &+ 1 + let changedText = try MCOImageCodec.text(fromAppPayload: changed) + let changedData = try MCOImageTransport.dataField(text: changedText, senderName: sender) + #expect(ReactionParser.generateUntimedHash(changedData) != first) + } + + @Test + func `V3 receive fixture hashes the original data field and not the transmit upgrade`() throws { + let payload = try #require(Data(base64Encoded: "E3oBjQBCvgE=")) + let sender = "Peer:名" + let stored = try MCOImageCodec.text(fromAppPayload: payload) + let packet = try MCOImageTransport.dataField(text: stored, senderName: sender) + let manual = Data([UInt8(sender.utf8.count)]) + Data(sender.utf8) + payload + #expect(packet == manual) + let hash = ReactionParser.generateUntimedHash(packet) + let encoded = try MCOImageTransport.encode(text: stored, senderName: sender) + #expect(ReactionParser.generateUntimedHash(encoded) != hash) + } } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift index 6650b2579a..2e5c5a81c9 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift @@ -580,17 +580,16 @@ struct ReactionServiceTests { } @Test - func `Indexing a channel image drops only that pending hash`() async throws { + func `Indexing a datagram hash returns that pending reaction and leaves the text reaction`() async throws { let service = ReactionService() let radioID = UUID() let timestamp: UInt32 = 1_704_067_200 - let imageText = "im4:pixel" - let imageReactionText = service.buildReactionText( - emoji: "👍", - targetSender: "Ada", - targetText: imageText, - targetTimestamp: timestamp + let imageText = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) + let sender = "Ada" + let hash = try ReactionParser.generateUntimedHash( + MCOImageTransport.dataField(text: imageText, senderName: sender) ) + let imageReactionText = "@[\(sender)]👍\n\(hash)" let imageParsed = try #require(ReactionParser.parse(imageReactionText)) await service.queuePendingReaction( parsed: imageParsed, @@ -602,7 +601,7 @@ struct ReactionServiceTests { let textReactionText = service.buildReactionText( emoji: "🔥", - targetSender: "Ada", + targetSender: sender, targetText: "Hello world", targetTimestamp: timestamp ) @@ -618,17 +617,18 @@ struct ReactionServiceTests { let imageMatches = await service.indexMessage( id: UUID(), channelIndex: 0, - senderName: "Ada", + senderName: sender, text: imageText, - timestamp: timestamp + timestamp: 0, + messageHash: hash ) - #expect(imageMatches.isEmpty) - #expect(await service.findTargetMessage(parsed: imageParsed, channelIndex: 0) == nil) + #expect(imageMatches.count == 1) + #expect(imageMatches.first?.parsed.emoji == "👍") let textMatches = await service.indexMessage( id: UUID(), channelIndex: 0, - senderName: "Ada", + senderName: sender, text: "Hello world", timestamp: timestamp ) diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelImageReactionTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift similarity index 70% rename from MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelImageReactionTests.swift rename to MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift index 41ead9a044..3fb6a51efc 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelImageReactionTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift @@ -3,14 +3,14 @@ import Foundation import MeshCoreTestSupport import Testing -@Suite("Channel image reactions") +@Suite("Channel MCOimg reactions") @MainActor -struct SyncCoordinatorChannelImageReactionTests { +struct SyncCoordinatorChannelMCOImageReactionTests { /// Matches `ReactionService`'s pending cap. One more entry evicts the oldest. private static let pendingReactionCap = 100 @Test - func `Reactions that match a stored channel image do not evict a pending text reaction`() async throws { + func `Reactions that match a stored channel MCOimg do not evict a pending text reaction`() async throws { let radioID = UUID() let session = MeshCoreSession(transport: SimulatorMockTransport()) let services = try await ServiceContainer.forTesting(session: session, radioID: radioID) @@ -71,11 +71,11 @@ struct SyncCoordinatorChannelImageReactionTests { ) #expect(matches.count == 1) #expect(matches.first?.parsed.emoji == "🔥") - #expect(try await services.dataStore.fetchReactions(for: image.id).isEmpty) + #expect(try await services.dataStore.fetchReactions(for: image.id).count == 1) } @Test - func `A channel image arrival drops a reaction queued for that image`() async throws { + func `A reaction queued before an MCOimg attaches when the MCOimg is indexed`() async throws { let radioID = UUID() let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) try await store.saveDevice(.testDevice(id: radioID)) @@ -91,7 +91,6 @@ struct SyncCoordinatorChannelImageReactionTests { let sender = "Ada" let appPayload = Data([0x14, 0, 0, 0, 0]) - let expectedText = try MCOImageCodec.text(fromAppPayload: appPayload) try await queueReaction( on: services.reactionService, emoji: "🔥", @@ -101,13 +100,15 @@ struct SyncCoordinatorChannelImageReactionTests { channelIndex: channel.index, radioID: radioID ) - try await queueReaction( - on: services.reactionService, - emoji: "👍", - targetSender: sender, - targetText: expectedText, - targetTimestamp: 0, + let packetData = Data([UInt8(sender.utf8.count)]) + Data(sender.utf8) + appPayload + let imageHash = ReactionParser.generateUntimedHash(packetData) + let imageReaction = "@[\(sender)]👍\n\(imageHash)" + let imageParsed = try #require(ReactionParser.parse(imageReaction)) + await services.reactionService.queuePendingReaction( + parsed: imageParsed, channelIndex: channel.index, + senderNodeName: "Bea", + rawText: imageReaction, radioID: radioID ) @@ -121,34 +122,17 @@ struct SyncCoordinatorChannelImageReactionTests { channelIndex: channel.index, pathLength: 2, dataType: MCOImageTransport.applicationDataType, - data: Data([UInt8(sender.utf8.count)]) + Data(sender.utf8) + appPayload, + data: packetData, snr: 6.25 ) let handler = try #require(await poller.capturedChannelDatagramHandler) let scope = try #require(try await store.captureReceiveScope(radioID: radioID, link: ReceiveScope.Lifetime())) await handler(packet, channel, .live, scope, nil, Date()) - let imageReaction = services.reactionService.buildReactionText( - emoji: "👍", - targetSender: sender, - targetText: expectedText, - targetTimestamp: 0 - ) - let imageParsed = try #require(ReactionParser.parse(imageReaction)) - #expect(await services.reactionService.findTargetMessage(parsed: imageParsed, channelIndex: channel.index) == nil) - - // Filling back to the cap evicts the text reaction only if the image key is still queued. - for index in 0..<(Self.pendingReactionCap - 1) { - try await queueReaction( - on: services.reactionService, - emoji: "👀", - targetSender: "Filler", - targetText: "filler \(index)", - targetTimestamp: 1_700_000_200, - channelIndex: channel.index, - radioID: radioID - ) - } + let messages = try await store.fetchMessages(radioID: radioID, channelIndex: channel.index) + let image = try #require(messages.first) + #expect(try await store.fetchReactions(for: image.id).count == 1) + #expect(await services.reactionService.findTargetMessage(parsed: imageParsed, channelIndex: channel.index) == image.id) let matches = await services.reactionService.indexMessage( id: UUID(), @@ -158,9 +142,42 @@ struct SyncCoordinatorChannelImageReactionTests { timestamp: 1_700_000_100 ) #expect(matches.count == 1) - let messages = try await store.fetchMessages(radioID: radioID, channelIndex: channel.index) - let image = try #require(messages.first) - #expect(try await store.fetchReactions(for: image.id).isEmpty) + } + + @Test + func `A reaction that arrives after a stored MCOimg attaches`() async throws { + let radioID = UUID() + let session = MeshCoreSession(transport: SimulatorMockTransport()) + let services = try await ServiceContainer.forTesting(session: session, radioID: radioID) + defer { Task { await services.tearDown() } } + + let sender = "Ada" + let text = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) + var image = MessageDTO.testChannelMessage( + radioID: radioID, + channelIndex: 0, + text: text, + timestamp: 1_000_000, + createdAt: Date(timeIntervalSince1970: 1_000_000), + direction: .incoming, + status: .delivered, + senderNodeName: sender + ) + image.senderTimestamp = 0 + try await services.dataStore.saveMessage(image) + let hash = try ReactionParser.generateUntimedHash(MCOImageTransport.dataField(text: text, senderName: sender)) + let reaction = "@[\(sender)]👍\n\(hash)" + let consumed = await SyncCoordinator().handleChannelReaction( + text: reaction, + channelIndex: 0, + senderNodeName: "Bea", + selfNodeName: "Local", + receiveTime: Date(), + radioID: radioID, + dependencies: services.syncDependencies + ) + #expect(consumed) + #expect(try await services.dataStore.fetchReactions(for: image.id).count == 1) } private func queueReaction( diff --git a/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift b/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift index 85d19c1795..36ea1347f8 100644 --- a/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift +++ b/MC1Tests/Views/Chats/ChatSendAdmissionTests.swift @@ -1,6 +1,7 @@ import Foundation @testable import MC1 @testable import MC1Services +import Observation import SwiftUI import Testing import UIKit @@ -42,7 +43,7 @@ struct ChatSendAdmissionTests { } @Test(arguments: [false, true]) - func `retired queue rejects before creation so the composer restores the Draft`(isChannel: Bool) async throws { + func `retired queue rejects before creation and leaves the conversation alert unset`(isChannel: Bool) async throws { let radioID = UUID() let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) let services = ServiceContainer( @@ -62,7 +63,48 @@ struct ChatSendAdmissionTests { #expect(!reachedService) #expect(viewModel.messages.isEmpty) #expect(try await store.fetchPendingSends(radioID: radioID).isEmpty) - #expect(viewModel.sendErrorMessage == L10n.Chats.Chats.Alert.UnableToSend.message) + #expect(viewModel.sendErrorMessage == nil) + } + + @Test func `keyboard false writes the conversation alert and restores the draft`() async throws { + let appState = try AppState( + modelContainer: PersistenceStore.createContainer(inMemory: true), + isPlaceholder: true + ) + appState.connectionManager.setTestState(connectionState: .ready) + let contact = ContactDTO(from: Contact( + radioID: UUID(), + publicKey: Data(repeating: 1, count: ProtocolLimits.publicKeySize), + name: "Test", typeRawValue: ContactType.chat.rawValue, + lastHeardTimestamp: 0 + )) + let model = KeyboardAdmissionModel() + let controller = UIHostingController( + rootView: KeyboardAdmissionHarness(contact: contact, model: model) + .environment(\.appState, appState) + ) + let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + window.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + window.rootViewController = controller + window.makeKeyAndVisible() + defer { + window.rootViewController = nil + window.isHidden = true + window.windowScene = nil + appState.shutdown() + } + + try await waitUntil(timeout: timeout, "composer should show the draft") { + composer(in: window)?.text == "Retain this text" + } + let field = try #require(composer(in: window)) + let accepted = field.onSend?() == true + #expect(accepted) + try await waitUntil(timeout: timeout, "rejected send should restore the draft and write the alert") { + model.text == "Retain this text" && model.notAdmitted == 1 + } + #expect(model.sendErrorMessage == L10n.Chats.Chats.Alert.UnableToSend.message) } @Test(arguments: [false, true]) @@ -78,7 +120,8 @@ struct ChatSendAdmissionTests { #expect(await !submit(text, to: viewModel, isChannel: isChannel)) #expect(viewModel.messages.isEmpty) - #expect(viewModel.errorMessage != nil) + #expect(viewModel.errorMessage == nil) + #expect(viewModel.sendErrorMessage == nil) #expect(try await store.fetchPendingSends(radioID: radioID).isEmpty) if let contact = viewModel.currentContact { #expect(try await store.fetchMessages(contactID: contact.id).isEmpty) @@ -174,3 +217,32 @@ struct ChatSendAdmissionTests { } } } + +@Observable +@MainActor +private final class KeyboardAdmissionModel { + var text = "Retain this text" + var focusRequest = 0 + var notAdmitted = 0 + var sendErrorMessage: String? +} + +private struct KeyboardAdmissionHarness: View { + let contact: ContactDTO + @Bindable var model: KeyboardAdmissionModel + + var body: some View { + ChatConversationInputBar( + conversationType: .dm(contact), + composingText: $model.text, + focusRequest: $model.focusRequest, + nodeNameByteCount: 0, + onSend: { _ in false }, + onWillSend: {}, + onNotAdmitted: { + model.notAdmitted += 1 + model.sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + } + ) + } +} diff --git a/MC1Tests/Views/Chats/Components/ChatKeyboardTransitionTests.swift b/MC1Tests/Views/Chats/Components/ChatKeyboardTransitionTests.swift index 4b1f9cdb89..966ef8830d 100644 --- a/MC1Tests/Views/Chats/Components/ChatKeyboardTransitionTests.swift +++ b/MC1Tests/Views/Chats/Components/ChatKeyboardTransitionTests.swift @@ -61,7 +61,7 @@ struct ChatKeyboardTransitionTests { ChatConversationInputBar( conversationType: .channel(channel), composingText: $composerModel.text, focusRequest: $focusRequest, nodeNameByteCount: 0, - onSend: { _ in true }, onWillSend: {}, onDrawingRejected: {} + onSend: { _ in true }, onWillSend: {}, onNotAdmitted: {} ) .overlay(alignment: .bottomLeading) { Color(red: 1, green: 0, blue: 0) diff --git a/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift b/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift index c2cc1a2aed..9435af8527 100644 --- a/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift +++ b/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift @@ -1033,7 +1033,7 @@ private struct ChatNativeSplitHarness: View { nodeNameByteCount: 0, onSend: { _ in true }, onWillSend: { model.scrollToBottomRequest += 1 }, - onDrawingRejected: {} + onNotAdmitted: {} ) .background { GateAIdentifierView(identifier: "gateA.composer") diff --git a/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift b/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift index 108e1ea291..2541fa0b4d 100644 --- a/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift +++ b/MC1Tests/Views/Chats/Components/RoomMessageBubbleA11yLabelTests.swift @@ -7,7 +7,7 @@ import Testing @Suite("RoomMessageBubble accessibility label") struct RoomMessageBubbleA11yLabelTests { @Test(arguments: ["im3:g/5WjAL`NA", "im4:AAAAA", "im5:unknown", "im3:"]) - func `image messages announce their localized content`(_ text: String) throws { + func `MCOimg messages announce their localized content`(_ text: String) throws { let message = RoomMessageDTO(sessionID: UUID(), authorKeyPrefix: Data([0xAA]), authorName: "Alice", text: text, timestamp: 100) let content = try #require(MCOImageCodec.content(from: text)) diff --git a/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift b/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift index 0cf30530c5..7513fef387 100644 --- a/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift +++ b/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift @@ -198,14 +198,26 @@ struct MessageActionAvailabilityTests { } @Test - func `channel image cannot react`() { - let message = makeMessage(channelIndex: 0, text: "im4:pixel") - let availability = MessageActionAvailability(message: message) - #expect(availability.canReact == false) + func `channel MCOimg with a sender can react`() throws { + let incoming = makeMessage(channelIndex: 0, text: "im4:pixel") + #expect(MessageActionAvailability(message: incoming).canReact) + + let text = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) + let outgoing = makeMessage(channelIndex: 0, text: text, direction: .outgoing) + #expect(MessageActionAvailability(message: outgoing).canReact) + } + + @Test + func `channel MCOimg with an empty sender cannot react`() { + var message = makeMessage(channelIndex: 0, text: "im4:pixel") + message.senderNodeName = "" + #expect(MessageActionAvailability(message: message).canReact == false) + message.senderNodeName = nil + #expect(MessageActionAvailability(message: message).canReact == false) } @Test - func `direct image can react`() { + func `direct MCOimg can react`() { let message = makeMessage(contactID: UUID(), text: "im4:pixel") let availability = MessageActionAvailability(message: message) #expect(availability.canReact == true) diff --git a/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift b/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift index 071b99b25e..8e4d9cefbb 100644 --- a/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift +++ b/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift @@ -86,14 +86,14 @@ struct MessageFragmentBuilderTests { } @Test - func `channel image omits a stored reaction summary`() { + func `channel MCOimg keeps a stored reaction summary`() { let message = makeMessage(text: "im4:pixel", reactionSummary: "👍:1", channelIndex: 0, contactID: nil) let item = MessageFragmentBuilder.makeItem(for: message, inputs: makeInputs(messageID: message.id), envInputs: makeEnvInputs()) - #expect(item.content.map(Self.kind(of:)) == [.mcoImage]) + #expect(item.content.map(Self.kind(of:)) == [.mcoImage, .reactionSummary]) } @Test - func `direct image keeps a stored reaction summary`() { + func `direct MCOimg keeps a stored reaction summary`() { let message = makeMessage(text: "im4:pixel", reactionSummary: "👍:1") let item = MessageFragmentBuilder.makeItem(for: message, inputs: makeInputs(messageID: message.id), envInputs: makeEnvInputs()) #expect(item.content.map(Self.kind(of:)) == [.mcoImage, .reactionSummary]) diff --git a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift index 77065595f3..db85b1a24c 100644 --- a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift @@ -67,14 +67,13 @@ struct PixelPaintDraftTests { await task?.value #expect(probe.payloads.isEmpty) #expect(probe.admitted == 0) - #expect(probe.rejected == 0) #expect(draft.errorTitle == nil) #expect(draft.errorMessage == nil) #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) #expect(!draft.isSubmitting) } - @Test func `rejected admission keeps pixels and clears the conversation send error`() async { + @Test func `rejected admission keeps pixels and leaves the conversation alert unset`() async { let draft = PixelPaintDraft() draft.paint(x: 2, y: 3) draft.endStroke() @@ -83,7 +82,6 @@ struct PixelPaintDraftTests { probe.accept = false await probe.submit(draft)?.value #expect(probe.payloads.count == 1) - #expect(probe.rejected == 1) #expect(probe.sendErrorMessage == nil) #expect(draft.errorTitle == L10n.Chats.Chats.Alert.UnableToSend.title) #expect(draft.errorMessage == L10n.Chats.Chats.Alert.UnableToSend.message) @@ -108,7 +106,6 @@ struct PixelPaintDraftTests { probe.pause.resume() await task?.value #expect(probe.payloads.isEmpty) - #expect(probe.rejected == 0) #expect(probe.sendErrorMessage == nil) #expect(draft.errorTitle == L10n.Chats.Chats.Alert.UnableToSend.title) #expect(draft.errorMessage == L10n.Chats.Chats.Alert.UnableToSend.message) @@ -125,7 +122,6 @@ struct PixelPaintDraftTests { probe.failEncode = true await probe.submit(draft)?.value #expect(probe.payloads.isEmpty) - #expect(probe.rejected == 0) #expect(draft.errorTitle == L10n.Chats.Chats.Mcoimg.encodingFailedTitle) #expect(draft.errorMessage == L10n.Chats.Chats.Mcoimg.encodingFailed) #expect(draft.image == snapshot) @@ -161,7 +157,6 @@ struct PixelPaintDraftTests { private final class AdmissionProbe { var payloads: [String] = [] var captured: [MCOImageRaster] = [] - var rejected = 0 var admitted = 0 var ready = true var accept = true @@ -188,16 +183,9 @@ private final class AdmissionProbe { onSend: { text in self.payloads.append(text) if pauseOnSend { await pause.pause() } - if !self.accept { - self.sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message - } return self.accept }, onWillSend: {}, - onRejected: { - self.rejected += 1 - self.sendErrorMessage = nil - }, onAdmitted: { self.admitted += 1 }, encode: { image, isChannel in await MainActor.run { self.captured.append(image) } diff --git a/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift index 5a0bfc5ba5..b6ec06ae74 100644 --- a/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift @@ -165,7 +165,6 @@ struct PixelPaintPresentationTests { return true }, onWillSend: {}, - onRejected: { model.sendErrorMessage = nil }, onAdmitted: {}, encode: { image, isChannel in await pause.pause() @@ -252,13 +251,9 @@ struct PixelPaintPresentationTests { onSend: { text in model.payloads.append(text) await model.pause.pause() - if !model.accept { - model.sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message - } return model.accept }, onWillSend: {}, - onRejected: { model.sendErrorMessage = nil }, onAdmitted: { model.isPresented = false } ) } From 5477df2b4044c652c03a623bad699c09df450240 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:46:16 -0800 Subject: [PATCH 07/13] feat: match MCOimg paths on the data field A channel MCOimg has no sender timestamp, so extra paths join on the datagram data field. - Decrypt a group datagram as a data type and blob, and leave the sender timestamp empty. - Use the earliest matching RX row for the hop list, route, and region. Later rows add paths. Group text at wire time 0 stays a separate row. - On import, merge the same incoming picture for one radio and one channel. - Attach an RX row that was saved before the outgoing message. --- .../MC1Services/Models/RxLogEntry.swift | 14 +- .../Persistence/HeardRepeatPersisting.swift | 38 +++ .../Persistence/RxLogPersisting.swift | 16 + .../MC1Services/ServiceContainer.swift | 15 +- .../Services/HeardRepeatsService.swift | 125 ++++++- .../Services/MessageDTO+MCOImage.swift | 23 ++ .../Services/MessageService+SendChannel.swift | 9 + .../MC1Services/Services/MessageService.swift | 6 +- .../PersistenceStore+BackupBatchInsert.swift | 40 +++ .../PersistenceStore+Diagnostics.swift | 22 ++ .../Services/PersistenceStore+Messages.swift | 41 +++ .../RxLogService+RegionResolution.swift | 30 ++ .../MC1Services/Services/RxLogService.swift | 117 +++++-- .../SyncCoordinator+MessageHandlers.swift | 120 ++++++- .../Utilities/ChannelRXCorrelation.swift | 18 + .../Utilities/DeduplicationKey.swift | 9 + .../BackupIntegrationTests.swift | 280 ++++++++++++++++ .../MCOImageReceiveIntegrationTests.swift | 309 ++++++++++++++++++ .../Services/HeardRepeatsServiceTests.swift | 268 +++++++++++++++ .../Services/RxLogServiceReprocessTests.swift | 159 +++++++++ .../MeshCore/Protocol/ChannelCrypto.swift | 75 +++-- .../MeshCoreTests/ChannelCryptoTests.swift | 45 +++ 22 files changed, 1724 insertions(+), 55 deletions(-) diff --git a/MC1Services/Sources/MC1Services/Models/RxLogEntry.swift b/MC1Services/Sources/MC1Services/Models/RxLogEntry.swift index 9477b3b176..dea805d983 100644 --- a/MC1Services/Sources/MC1Services/Models/RxLogEntry.swift +++ b/MC1Services/Sources/MC1Services/Models/RxLogEntry.swift @@ -158,6 +158,12 @@ public struct RxLogEntryDTO: Sendable, Identifiable, Equatable, Hashable { /// Transient - set by UI layer after decryption public var decodedText: String? + /// Group-datagram data type. Filled by decryption and not stored. + public var datagramDataType: UInt16? + + /// Group-datagram data field. Filled by decryption and not stored. + public var datagramData: Data? + /// Initialize from SwiftData model. init(from model: RxLogEntry) { id = model.id @@ -186,6 +192,8 @@ public struct RxLogEntryDTO: Sendable, Identifiable, Equatable, Hashable { regionScopeMatches = model.regionScopeMatches payloadTypeBits = UInt8(model.payloadTypeBits & 0x0F) decodedText = model.decodedText + datagramDataType = nil + datagramData = nil } /// Initialize from ParsedRxLogData (for new entries). @@ -202,7 +210,9 @@ public struct RxLogEntryDTO: Sendable, Identifiable, Equatable, Hashable { senderTimestamp: UInt32? = nil, regionScope: String? = nil, regionScopeMatches: [String] = [], - decodedText: String? = nil + decodedText: String? = nil, + datagramDataType: UInt16? = nil, + datagramData: Data? = nil ) { self.id = id self.radioID = radioID @@ -228,6 +238,8 @@ public struct RxLogEntryDTO: Sendable, Identifiable, Equatable, Hashable { self.regionScopeMatches = regionScopeMatches payloadTypeBits = parsed.payloadTypeBits self.decodedText = decodedText + self.datagramDataType = datagramDataType + self.datagramData = datagramData } // MARK: - Computed Properties diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift index 3f9f508668..b28f2eefe9 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift @@ -1,4 +1,5 @@ import Foundation +import MeshCore /// Store operations for correlating RX observations with a known message. public protocol HeardRepeatPersisting: Actor { @@ -9,6 +10,9 @@ public protocol HeardRepeatPersisting: Actor { /// Incoming extras join on the content-based key, not `Message.timestamp`. func fetchMessage(deduplicationKey: String, radioID: UUID) async throws -> MessageDTO? + /// Every message on one radio and channel. Datagram path matching filters this set in memory. + func fetchChannelMessages(radioID: UUID, channelIndex: UInt8) async throws -> [MessageDTO] + /// Save a message repeat entry func saveMessageRepeat(_ dto: MessageRepeatDTO) async throws @@ -46,6 +50,21 @@ public protocol HeardRepeatPersisting: Actor { rxLogEntryID: UUID? ) async throws -> Int? + /// Route and region copied from the earliest matching datagram RX row when its path is adopted. + func applyDatagramCanonicalContext( + messageID: UUID, + routeType: RouteType?, + regionScope: String?, + regionScopeMatches: [String] + ) async throws + + /// Region written onto a datagram message from the canonical RX row, including a later rewrite. + func updateMessageRegion( + id: UUID, + regionScope: String?, + regionScopeMatches: [String] + ) async throws + /// Writes path columns only when they are still nil. Fetch by id; `#Predicate` cannot match `Data`. /// Leaves snr and heardRepeats unchanged. func adoptIncomingPathIfUnknown( @@ -57,3 +76,22 @@ public protocol HeardRepeatPersisting: Actor { /// Increment send count and return new count func incrementMessageSendCount(id: UUID) async throws -> Int } + +extension HeardRepeatPersisting { + func fetchChannelMessages(radioID: UUID, channelIndex: UInt8) async throws -> [MessageDTO] { + [] + } + + func applyDatagramCanonicalContext( + messageID: UUID, + routeType: RouteType?, + regionScope: String?, + regionScopeMatches: [String] + ) async throws {} + + func updateMessageRegion( + id: UUID, + regionScope: String?, + regionScopeMatches: [String] + ) async throws {} +} diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift index 75146e9f57..8667216f2f 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift @@ -1,4 +1,5 @@ import Foundation +import MeshCore /// Retention bounds for the RX log radio partition. /// @@ -41,6 +42,13 @@ public protocol RxLogPersisting: Actor { senderTimestamp: UInt32 ) async throws -> [RxLogEntryDTO] + /// Group-datagram rows for one radio and channel. No sender timestamp. + func fetchRxLogEntries( + radioID: UUID, + channelIndex: UInt8, + payloadType: PayloadType + ) async throws -> [RxLogEntryDTO] + /// Find a DM RxLogEntry by matching the sender prefix byte in the packet payload. /// Fallback for when the primary timestamp-based lookup fails. func findRxLogEntryBySenderPrefix( @@ -112,6 +120,14 @@ public protocol RxLogPersisting: Actor { // MARK: - Default Parameter Values extension RxLogPersisting { + func fetchRxLogEntries( + radioID: UUID, + channelIndex: UInt8, + payloadType: PayloadType + ) async throws -> [RxLogEntryDTO] { + [] + } + func flushPendingRxLogEntries() async throws {} /// Fetch RX log entries with the default limit of 500 diff --git a/MC1Services/Sources/MC1Services/ServiceContainer.swift b/MC1Services/Sources/MC1Services/ServiceContainer.swift index fd55a18070..e7fedfa7e8 100644 --- a/MC1Services/Sources/MC1Services/ServiceContainer.swift +++ b/MC1Services/Sources/MC1Services/ServiceContainer.swift @@ -207,6 +207,9 @@ public final class ServiceContainer { contactRadioOwner.bind(contactService) let plainTextSendGate = PlainTextSendGate() self.plainTextSendGate = plainTextSendGate + let repeats = heardRepeatsService + let rxLog = rxLogService + let store = dataStore messageService = MessageService( session: session, dataStore: dataStore, @@ -214,7 +217,17 @@ public final class ServiceContainer { config: messageConfig, ackEvents: ackEvents, dmSendBudget: { DMSendBudget.current() }, - plainTextSendGate: plainTextSendGate + plainTextSendGate: plainTextSendGate, + datagramPathHarvest: { message in + guard let channelIndex = message.channelIndex else { return } + let raw = await (try? store.fetchRxLogEntries( + radioID: message.radioID, + channelIndex: channelIndex, + payloadType: .groupData + )) ?? [] + let decoded = await rxLog.decodedEntries(raw) + await repeats.harvestDatagramPaths(for: message, decodedCandidates: decoded) + } ) channelService = ChannelService( session: session, diff --git a/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift index ff2d255f5b..2643e90047 100644 --- a/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift +++ b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift @@ -69,6 +69,9 @@ public actor HeardRepeatsService { /// - Returns: The updated heardRepeats count if a match was found, nil otherwise @discardableResult public func processForRepeats(_ entry: RxLogEntryDTO) async -> Int? { + if entry.payloadType == .groupData { + return await processDatagramRepeat(entry) + } // Only process successfully decrypted channel messages guard entry.payloadType == .groupText, entry.decryptStatus == .success, let decodedText = entry.decodedText, let channelIndex = entry.channelIndex, let senderTimestamp = entry.senderTimestamp, let radioID else { return nil } @@ -153,7 +156,11 @@ public actor HeardRepeatsService { snr: Double?, rssi: Int?, receivedAt: Date, - rxLogEntryID: UUID? + rxLogEntryID: UUID?, + canonicalRoute: RouteType? = nil, + canonicalRegion: String? = nil, + canonicalRegionMatches: [String] = [], + applyCanonicalContext: Bool = false ) async -> Int? { #if DEBUG if let hold = admissionHoldForTesting { @@ -170,6 +177,14 @@ public actor HeardRepeatsService { receivedAt: receivedAt, rxLogEntryID: rxLogEntryID ) + if case .adoptedCanonical = admission, applyCanonicalContext { + try await dataStore.applyDatagramCanonicalContext( + messageID: message.id, + routeType: canonicalRoute, + regionScope: canonicalRegion, + regionScopeMatches: canonicalRegionMatches + ) + } guard case let .recordedExtra(count) = admission else { return nil } logger.info("Recorded extra path #\(count) for message \(message.id)") eventBroadcaster.yield(HeardRepeatEvent(messageID: message.id, count: count)) @@ -180,6 +195,74 @@ public actor HeardRepeatsService { } } + /// Outgoing rows count echoes. Incoming rows adopt the earliest path, then extras. + /// A nil service radio skips an outgoing row. + func harvestDatagramPaths( + for message: MessageDTO, + decodedCandidates: [RxLogEntryDTO] + ) async { + guard message.isDatagramPathMCOImage else { return } + if message.isOutgoing, message.radioID != radioID { return } + guard let blob = message.datagramDataField, + let channelIndex = message.channelIndex else { return } + let matching = ChannelRXCorrelation.matchingDatagrams( + decodedCandidates, + blob: blob, + radioID: message.radioID, + channelIndex: channelIndex + ) + for entry in matching { + if message.isOutgoing { + _ = try? await recordSentEcho(message: message, entry: entry) + } else { + _ = await recordDistinctPathIfNeeded( + message: message, + pathNodes: entry.pathNodes, + pathLength: entry.pathLength, + snr: entry.snr, + rssi: entry.rssi, + receivedAt: entry.receivedAt, + rxLogEntryID: entry.id, + canonicalRoute: entry.routeType, + canonicalRegion: entry.regionScope, + canonicalRegionMatches: entry.regionScopeMatches, + applyCanonicalContext: true + ) + } + } + } + + /// Copies a later region from the earliest matching datagram RX row onto each path MCOimg. + func copyDatagramRegionIfCanonical( + entry: RxLogEntryDTO, + regionScope: String?, + regionScopeMatches: [String], + channelEntries: [RxLogEntryDTO] + ) async { + guard entry.datagramDataType == MCOImageTransport.applicationDataType, + let blob = entry.datagramData, + let channelIndex = entry.channelIndex else { return } + let sameField = channelEntries.filter { + $0.channelIndex == channelIndex && + $0.datagramDataType == entry.datagramDataType && + $0.datagramData == blob + } + guard let earliest = sameField.min(by: { $0.receivedAt < $1.receivedAt }), + earliest.id == entry.id else { return } + do { + let messages = try await dataStore.fetchChannelMessages(radioID: entry.radioID, channelIndex: channelIndex) + for message in messages where message.datagramDataField == blob { + try await dataStore.updateMessageRegion( + id: message.id, + regionScope: regionScope, + regionScopeMatches: regionScopeMatches + ) + } + } catch { + logger.error("Failed to copy datagram region: \(error.localizedDescription)") + } + } + /// Adopts an unknown canonical from the earliest `ChannelRXCorrelation` match, /// then records later distinct paths as extras. func harvestIncomingPaths( @@ -221,4 +304,44 @@ public actor HeardRepeatsService { return [] } } + + private func processDatagramRepeat(_ entry: RxLogEntryDTO) async -> Int? { + guard entry.datagramDataType == MCOImageTransport.applicationDataType, + let blob = entry.datagramData, + let channelIndex = entry.channelIndex, + let radioID, + entry.radioID == radioID else { return nil } + if await isDuplicateRepeat(entry.id) { return nil } + do { + let messages = try await dataStore.fetchChannelMessages(radioID: radioID, channelIndex: channelIndex) + let matches = messages.filter { $0.datagramDataField == blob } + var lastCount: Int? + for message in matches where message.isOutgoing { + if let count = try await recordSentEcho(message: message, entry: entry) { + lastCount = count + } + } + for message in matches where !message.isOutgoing { + if let count = await recordDistinctPathIfNeeded( + message: message, + pathNodes: entry.pathNodes, + pathLength: entry.pathLength, + snr: entry.snr, + rssi: entry.rssi, + receivedAt: entry.receivedAt, + rxLogEntryID: entry.id, + canonicalRoute: entry.routeType, + canonicalRegion: entry.regionScope, + canonicalRegionMatches: entry.regionScopeMatches, + applyCanonicalContext: true + ) { + lastCount = count + } + } + return lastCount + } catch { + logger.error("Failed to process datagram repeat: \(error.localizedDescription)") + return nil + } + } } diff --git a/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift index 1cc56f8cac..d902216e9f 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift @@ -18,6 +18,29 @@ public extension MessageDTO { return senderTimestamp == 0 } + /// Path join for a channel MCOimg. Group text keeps the content key, including wire time 0. + /// Reactions use `isDatagramMCOImage`, which still includes that group-text row. + var isDatagramPathMCOImage: Bool { + guard isChannelMCOImage, let channelIndex else { return false } + if isOutgoing { return true } + guard senderTimestamp == 0 else { return false } + let contentKey = DeduplicationKey.contentBased( + contactID: nil, + channelIndex: channelIndex, + senderNodeName: senderNodeName, + timestamp: 0, + content: text + ) + return deduplicationKey != contentKey + } + + /// Nil unless this row is a path MCOimg and the data field can be rebuilt. + var datagramDataField: Data? { + guard isDatagramPathMCOImage, + let name = senderNodeName, !name.isEmpty else { return nil } + return try? MCOImageTransport.dataField(text: text, senderName: name) + } + /// Nil when the name is missing or the datagram bytes cannot be rebuilt. func mcoImageReactionTarget() -> (senderName: String, messageHash: String)? { guard isChannelMCOImage else { return nil } diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index 965a3ae4ed..3451e5c2f9 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -58,6 +58,7 @@ public extension MessageService { mcoImageSenderName: prepared.mcoImageSenderName ) try await dataStore.saveMessage(messageDTO) + await harvestOutgoingDatagramPathsIfNeeded(messageDTO) do { let transmission = try await channelTransmission( @@ -118,10 +119,18 @@ public extension MessageService { mcoImageSenderName: prepared.mcoImageSenderName ) try await dataStore.saveMessage(messageDTO) + await harvestOutgoingDatagramPathsIfNeeded(messageDTO) return messageDTO } + /// An RX row saved before the message is attached here. A later row is attached by `processForRepeats`. + /// The harvest writes only while `HeardRepeatsService` still owns this radio. + private func harvestOutgoingDatagramPathsIfNeeded(_ message: MessageDTO) async { + guard message.isOutgoing, message.isDatagramPathMCOImage else { return } + await datagramPathHarvest?(message) + } + /// Sends an already-created pending channel message. /// /// Use this after ``createPendingChannelMessage(text:channelIndex:radioID:textType:)`` diff --git a/MC1Services/Sources/MC1Services/Services/MessageService.swift b/MC1Services/Sources/MC1Services/Services/MessageService.swift index bd8763e5cc..68b26b91e5 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService.swift @@ -44,6 +44,8 @@ public actor MessageService { /// Read once at the start of each DM retry loop. let dmSendBudgetProvider: @Sendable () -> DMSendBudget let plainTextSendGate: PlainTextSendGate? + /// Runs after an outgoing channel MCOimg is stored. Nil when path harvest is not installed. + let datagramPathHarvest: (@Sendable (MessageDTO) async -> Void)? /// Contact service for path management (optional - retry with reset requires this). /// Injected by `ServiceContainer` at construction. @@ -136,7 +138,8 @@ public actor MessageService { config: MessageServiceConfig = .default, ackEvents: AsyncStream? = nil, dmSendBudget: @escaping @Sendable () -> DMSendBudget = { .default }, - plainTextSendGate: PlainTextSendGate? = nil + plainTextSendGate: PlainTextSendGate? = nil, + datagramPathHarvest: (@Sendable (MessageDTO) async -> Void)? = nil ) { self.session = session self.dataStore = dataStore @@ -145,6 +148,7 @@ public actor MessageService { dmSendBudgetProvider = dmSendBudget self.plainTextSendGate = plainTextSendGate bufferedAckEvents = ackEvents + self.datagramPathHarvest = datagramPathHarvest } /// Whether a contact service was injected at construction. diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift index 93b344946d..ca808828ed 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -301,6 +301,27 @@ extension PersistenceStore { !secret.isEmpty && !secret.allSatisfy { $0 == 0 } } + /// Incoming MCOimg on this radio and local slot with the same data field, including one accepted earlier in this pass. + /// Outgoing rows stay on message id. An MCOimg that cannot rebuild a data field matches by dedup string only. + private func matchingImportedIncomingPicture( + _ dto: MessageDTO, + accepted: [MessageDTO], + storedCache: inout [String: [MessageDTO]] + ) throws -> MessageDTO? { + guard dto.direction == .incoming, + let channelIndex = dto.channelIndex, + let blob = dto.datagramDataField else { return nil } + let cacheKey = "\(dto.radioID.uuidString)-\(channelIndex)" + if storedCache[cacheKey] == nil { + storedCache[cacheKey] = try storedChannelMessages(radioID: dto.radioID, channelIndex: channelIndex).filter { + !$0.isOutgoing && $0.datagramDataField != nil + } + } + let stored = storedCache[cacheKey] ?? [] + let acceptedHere = accepted.filter { $0.radioID == dto.radioID && $0.channelIndex == channelIndex } + return (stored + acceptedHere).first { $0.datagramDataField == blob } + } + @discardableResult func batchInsertMessages( _ dtos: [MessageDTO], @@ -321,6 +342,8 @@ extension PersistenceStore { toInsert.reserveCapacity(dtos.count) var skipped = 0 var merged = 0 + var acceptedIncomingPictures: [MessageDTO] = [] + var storedIncomingPictures: [String: [MessageDTO]] = [:] // Pass 1: resolve duplicates and build the backup→local ID remap. Doing this // before any insert lets pass 2 rewrite replyToID onto winning local UUIDs, @@ -341,6 +364,20 @@ extension PersistenceStore { skipped += 1 continue } + if let match = try matchingImportedIncomingPicture( + dto, + accepted: acceptedIncomingPictures, + storedCache: &storedIncomingPictures + ) { + if match.id != dto.id { + messageIDByBackupID[dto.id] = match.id + } + skippedIncomingParents.append((localMessageID: match.id, dto: dto)) + knownKeys.insert(key) + idsByKey[key, default: []].append(match.id) + skipped += 1 + continue + } // Message.id is unique; skip so this unsaved context does not hold two // objects for one identity. if !knownIDs.insert(dto.id).inserted { @@ -350,6 +387,9 @@ extension PersistenceStore { knownKeys.insert(key) idsByKey[key, default: []].append(dto.id) toInsert.append(dto) + if dto.direction == .incoming, dto.datagramDataField != nil { + acceptedIncomingPictures.append(dto) + } } // Pass 2: insert, rewriting replyToID through the remap so retained messages diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift index 64d7f5c957..e68f05affe 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift @@ -300,6 +300,26 @@ public extension PersistenceStore { return try modelContext.fetch(descriptor).map { RxLogEntryDTO(from: $0) } } + func fetchRxLogEntries( + radioID: UUID, + channelIndex: UInt8, + payloadType: PayloadType + ) async throws -> [RxLogEntryDTO] { + let targetRadioID = radioID + let targetChannelIndex = Int(channelIndex) + let targetPayloadType = Int(payloadType.rawValue) + let predicate = #Predicate { entry in + entry.radioID == targetRadioID && + entry.channelIndex == targetChannelIndex && + entry.payloadType == targetPayloadType + } + let descriptor = FetchDescriptor( + predicate: predicate, + sortBy: [SortDescriptor(\.receivedAt, order: .forward)] + ) + return try modelContext.fetch(descriptor).map { RxLogEntryDTO(from: $0) } + } + /// Find a DM RxLogEntry by matching the sender prefix byte in the packet payload. /// /// Fallback for when the primary `findRxLogEntry(senderTimestamp:)` fails because @@ -439,6 +459,8 @@ public extension PersistenceStore { } ) for message in try modelContext.fetch(descriptor) { + // senderTimestamp 0 on an MCOimg is a missing clock, so a wire-time region write must not land here. + if MessageDTO(from: message).isDatagramPathMCOImage { continue } message.regionScope = update.regionScope message.regionScopeMatches = update.regionScopeMatches touchedIDs.append(message.id) diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index 7de6d44c6f..73fd39e353 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -1,4 +1,5 @@ import Foundation +import MeshCore import os import SwiftData @@ -849,6 +850,46 @@ public extension PersistenceStore { // MARK: - Heard Repeats + /// Every channel message for one radio, with no fetch limit, so path matching sees the whole channel. + func fetchChannelMessages(radioID: UUID, channelIndex: UInt8) async throws -> [MessageDTO] { + try storedChannelMessages(radioID: radioID, channelIndex: channelIndex) + } + + func storedChannelMessages(radioID: UUID, channelIndex: UInt8) throws -> [MessageDTO] { + let targetRadioID = radioID + let targetChannelIndex: UInt8? = channelIndex + let predicate = #Predicate { message in + message.radioID == targetRadioID && message.channelIndex == targetChannelIndex + } + return try modelContext.fetch(FetchDescriptor(predicate: predicate)).map { MessageDTO(from: $0) } + } + + func applyDatagramCanonicalContext( + messageID: UUID, + routeType: RouteType?, + regionScope: String?, + regionScopeMatches: [String] + ) async throws { + guard let message = try fetchMessageModel(id: messageID) else { return } + if let routeType { + message.routeTypeRawValue = Int(routeType.rawValue) + } + message.regionScope = regionScope + message.regionScopeMatches = regionScopeMatches + try modelContext.save() + } + + func updateMessageRegion( + id: UUID, + regionScope: String?, + regionScopeMatches: [String] + ) async throws { + guard let message = try fetchMessageModel(id: id) else { return } + message.regionScope = regionScope + message.regionScopeMatches = regionScopeMatches + try modelContext.save() + } + /// Finds the outgoing channel message a heard repeat echoes back. The sender /// embeds a timestamp the channel payload authenticates and every mesh hop /// forwards byte-identical, so exact channel, timestamp, and text on the sending diff --git a/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift b/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift index 0c8faea989..013f5f9913 100644 --- a/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift +++ b/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift @@ -126,6 +126,7 @@ extension RxLogService { let cacheSnapshot = scopeKeyCache var rxUpdates: [(id: UUID, regionScope: String?, regionScopeMatches: [String])] = [] + var datagramRegionUpdates: [(channelIndex: UInt8, id: UUID, regionScope: String?, regionScopeMatches: [String])] = [] var channelMessageUpdates: [(channelIndex: UInt8, senderTimestamp: UInt32, regionScope: String?, regionScopeMatches: [String])] = [] var dmMessageUpdates: [(senderPrefixByte: UInt8, senderTimestamp: UInt32, regionScope: String?, regionScopeMatches: [String])] = [] @@ -154,6 +155,15 @@ extension RxLogService { regionScopeMatches: resolved.regionScopeMatches )) + if entry.senderTimestamp == nil, entry.payloadType == .groupData, let channelIndex = entry.channelIndex { + datagramRegionUpdates.append(( + channelIndex: channelIndex, + id: entry.id, + regionScope: resolved.regionScope, + regionScopeMatches: resolved.regionScopeMatches + )) + } + guard let senderTimestamp = entry.senderTimestamp else { continue } if let channelIndex = entry.channelIndex { channelMessageUpdates.append(( @@ -176,6 +186,26 @@ extension RxLogService { if !rxUpdates.isEmpty { try await dataStore.batchUpdateRxLogRegion(updates: rxUpdates) } + if let heardRepeatsService, !datagramRegionUpdates.isEmpty { + let byChannel = Dictionary(grouping: datagramRegionUpdates, by: \.channelIndex) + for (channelIndex, updates) in byChannel { + let raw = try await dataStore.fetchRxLogEntries( + radioID: radioID, + channelIndex: channelIndex, + payloadType: .groupData + ) + let decoded = decodedEntries(raw) + for update in updates { + guard let entry = decoded.first(where: { $0.id == update.id }) else { continue } + await heardRepeatsService.copyDatagramRegionIfCanonical( + entry: entry, + regionScope: update.regionScope, + regionScopeMatches: update.regionScopeMatches, + channelEntries: decoded + ) + } + } + } var touchedMessageIDs = Set() if !channelMessageUpdates.isEmpty { diff --git a/MC1Services/Sources/MC1Services/Services/RxLogService.swift b/MC1Services/Sources/MC1Services/Services/RxLogService.swift index 060fdcd7cb..eb03a5c765 100644 --- a/MC1Services/Sources/MC1Services/Services/RxLogService.swift +++ b/MC1Services/Sources/MC1Services/Services/RxLogService.swift @@ -37,7 +37,7 @@ public actor RxLogService { /// Heard repeats processing. /// Injected by `ServiceContainer` at construction. - private let heardRepeatsService: HeardRepeatsService? + let heardRepeatsService: HeardRepeatsService? // Reentrancy guards for reprocessing (separate to avoid mutual blocking) private var isReprocessingChannels = false @@ -240,13 +240,19 @@ public actor RxLogService { guard !Task.isCancelled else { break } let decrypted = decryptEntry(entry) - guard decrypted.decodedText != nil else { continue } + // A group datagram has no text. A nil decodedText must not drop the channel update. + let isGroupDatagram = entry.payloadType == .groupData + if isGroupDatagram { + guard decrypted.datagramDataType != nil else { continue } + } else { + guard decrypted.decodedText != nil else { continue } + } updates.append(( id: entry.id, channelIndex: decrypted.channelIndex, channelName: decrypted.channelName, - senderTimestamp: decrypted.senderTimestamp + senderTimestamp: isGroupDatagram ? nil : decrypted.senderTimestamp )) decryptedEntries.append(decrypted) } @@ -381,6 +387,8 @@ public actor RxLogService { var decryptStatus = DecryptStatus.notApplicable var decodedText: String? var senderTimestamp: UInt32? + var datagramDataType: UInt16? + var datagramData: Data? var fromContactName: String? if parsed.payloadType == .groupText || parsed.payloadType == .groupData { @@ -394,15 +402,19 @@ public actor RxLogService { let encryptedPayload = Data(rawPayload.dropFirst(1)) for (index, secret) in channelSecrets { - let result = ChannelCrypto.decrypt(payload: encryptedPayload, secret: secret) - if case let .success(timestamp, _, text) = result { - channelIndex = index - channelName = channelNames[index] ?? "Channel \(index)" - decryptStatus = .success - senderTimestamp = timestamp - decodedText = text - break - } + guard let decoded = decodeChannelPayload( + payloadType: parsed.payloadType, + encryptedPayload: encryptedPayload, + secret: secret + ) else { continue } + channelIndex = index + channelName = channelNames[index] ?? "Channel \(index)" + decryptStatus = .success + senderTimestamp = decoded.senderTimestamp + decodedText = decoded.decodedText + datagramDataType = decoded.datagramDataType + datagramData = decoded.datagramData + break } if decryptStatus == .notApplicable { @@ -479,7 +491,9 @@ public actor RxLogService { senderTimestamp: senderTimestamp, regionScope: regionFields.regionScope, regionScopeMatches: regionFields.regionScopeMatches, - decodedText: decodedText + decodedText: decodedText, + datagramDataType: datagramDataType, + datagramData: datagramData ) // Persist @@ -557,31 +571,78 @@ public actor RxLogService { // Fast path: use stored channel index if previously decrypted successfully if entry.decryptStatus == .success, let channelIndex = entry.channelIndex, - let secret = channelSecrets[channelIndex] { - let decryptResult = ChannelCrypto.decrypt(payload: encryptedPayload, secret: secret) - if case let .success(timestamp, _, text) = decryptResult { - result.senderTimestamp = timestamp - result.decodedText = text - return result - } + let secret = channelSecrets[channelIndex], + let decoded = decodeChannelPayload( + payloadType: entry.payloadType, + encryptedPayload: encryptedPayload, + secret: secret + ) { + applyDecoded(decoded, to: &result) + return result } // Slow path: try all secrets (for .noMatchingKey entries or if fast path failed) // and record which channel's secret matched so the entry is attributed correctly. for (index, secret) in channelSecrets { - let decryptResult = ChannelCrypto.decrypt(payload: encryptedPayload, secret: secret) - if case let .success(timestamp, _, text) = decryptResult { - result.channelIndex = index - result.channelName = channelNames[index] ?? "Channel \(index)" - result.senderTimestamp = timestamp - result.decodedText = text - break - } + guard let decoded = decodeChannelPayload( + payloadType: entry.payloadType, + encryptedPayload: encryptedPayload, + secret: secret + ) else { continue } + result.channelIndex = index + result.channelName = channelNames[index] ?? "Channel \(index)" + applyDecoded(decoded, to: &result) + break } return result } + private struct DecodedChannelPayload { + var senderTimestamp: UInt32? + var decodedText: String? + var datagramDataType: UInt16? + var datagramData: Data? + } + + /// Group text parses a timestamp and UTF-8. A group datagram parses a data type and blob. + /// The datagram has no clock, so the sender timestamp stays empty. + private func decodeChannelPayload( + payloadType: PayloadType, + encryptedPayload: Data, + secret: Data + ) -> DecodedChannelPayload? { + if payloadType == .groupData { + guard case let .success(plaintext) = ChannelCrypto.decryptPlaintext(payload: encryptedPayload, secret: secret), + let datagram = ChannelCrypto.readGroupDatagram(plaintext) else { + return nil + } + return DecodedChannelPayload( + senderTimestamp: nil, + decodedText: nil, + datagramDataType: datagram.dataType, + datagramData: datagram.data + ) + } + + guard case let .success(timestamp, _, text) = ChannelCrypto.decrypt(payload: encryptedPayload, secret: secret) else { + return nil + } + return DecodedChannelPayload( + senderTimestamp: timestamp, + decodedText: text, + datagramDataType: nil, + datagramData: nil + ) + } + + private func applyDecoded(_ decoded: DecodedChannelPayload, to result: inout RxLogEntryDTO) { + result.senderTimestamp = decoded.senderTimestamp + result.decodedText = decoded.decodedText + result.datagramDataType = decoded.datagramDataType + result.datagramData = decoded.datagramData + } + /// Try decrypting a DM payload by iterating candidate keys for the sender prefix byte. /// Returns the decrypted timestamp and text, or nil if no key matched. private static func tryDecryptDM( diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 9a243c35d6..935d3c2687 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -156,6 +156,79 @@ extension SyncCoordinator { return messageDTO } + /// RX rows for a channel MCOimg join on the data field. The push has no RX id, so it is not admitted. + private func harvestDatagramAndRefresh( + messageDTO: MessageDTO, + dependencies: SyncDependencies, + scope: ReceiveScope + ) async throws -> MessageDTO { + guard scope.isCurrent, let channelIndex = messageDTO.channelIndex else { return messageDTO } + do { + let raw = try await dependencies.dataStore.fetchRxLogEntries( + radioID: messageDTO.radioID, + channelIndex: channelIndex, + payloadType: .groupData + ) + let decoded = await dependencies.rxLogService.decodedEntries(raw) + guard scope.isCurrent else { return messageDTO } + await dependencies.heardRepeatsService.harvestDatagramPaths( + for: messageDTO, + decodedCandidates: decoded + ) + } catch { + logger.error("Failed to harvest datagram paths: \(error)") + } + if let refreshed = try await dependencies.dataStore.fetchMessage(id: messageDTO.id) { + return refreshed + } + return messageDTO + } + + /// True when this data field already has an MCOimg row. The push is not admitted. + /// An incoming hit harvests stored RX rows onto that row. + private func skipExistingDatagramPicture( + _ message: MessageDTO, + dependencies: SyncDependencies, + scope: ReceiveScope + ) async -> Bool { + guard let existing = await existingDatagramPicture(message, dependencies: dependencies) else { + return false + } + guard scope.isCurrent else { return true } + if !existing.isOutgoing { + _ = try? await harvestDatagramAndRefresh( + messageDTO: existing, + dependencies: dependencies, + scope: scope + ) + } + return true + } + + /// Outgoing MCOimg first, then any incoming MCOimg with the same data field. + /// A group-text row is not a hit. An MCOimg that cannot rebuild a data field is not a hit. + private func existingDatagramPicture( + _ message: MessageDTO, + dependencies: SyncDependencies + ) async -> MessageDTO? { + guard let blob = message.datagramDataField, let channelIndex = message.channelIndex else { + return nil + } + do { + let rows = try await dependencies.dataStore.fetchChannelMessages( + radioID: message.radioID, + channelIndex: channelIndex + ) + if let outgoing = rows.first(where: { $0.isOutgoing && $0.datagramDataField == blob }) { + return outgoing + } + return rows.first { !$0.isOutgoing && $0.datagramDataField == blob } + } catch { + logger.warning("Datagram MCOimg lookup failed, proceeding with save: \(error)") + return nil + } + } + /// True when a row already owns this content key. A known distinct channel path /// is recorded as an extra; a nil path is unknown and is not written as one. private func recordChannelArrivalAndSkipDuplicate( @@ -298,8 +371,8 @@ extension SyncCoordinator { logger.debug("Corrected invalid \(resolvedKind.logLabel) message timestamp from \(Date(timeIntervalSince1970: TimeInterval(wireTimestamp))) to \(receiveTime)") } } else { - // An MCOimg has no wire time. The receive second sorts and dedups the row. - // senderTimestamp 0 is that absence, and it is not a packet clock. + // An MCOimg has no wire time. senderTimestamp 0 is that absence. + // A rebuilt data field dedups the row. Otherwise the receive second does. finalTimestamp = UInt32(receiveTime.timeIntervalSince1970) timestampCorrected = true storedSenderTimestamp = 0 @@ -312,8 +385,10 @@ extension SyncCoordinator { // Use content-based key for dedup (stable across retry attempts). // The RX log packetHash is per-encrypted-packet and differs between // retries with different attempt counters, so it must not drive dedup. - let deduplicationKey = Self.fallbackDeduplicationKey( - contactID: contactID, channelIndex: channelIndex, + let deduplicationKey = Self.channelDeduplicationKey( + kind: resolvedKind, + contactID: contactID, + channelIndex: channelIndex, senderNodeName: senderNodeName, timestamp: dedupTimestamp, content: text @@ -427,6 +502,11 @@ extension SyncCoordinator { preference: TextRulesPreference?, dependencies: SyncDependencies ) async { + if await skipExistingDatagramPicture( + message, dependencies: dependencies, scope: scope + ) { + return + } if await recordChannelArrivalAndSkipDuplicate( deduplicationKey: deduplicationKey, radioID: message.radioID, @@ -475,6 +555,12 @@ extension SyncCoordinator { dependencies: dependencies, scope: scope ) + } else if message.isDatagramPathMCOImage { + try await harvestDatagramAndRefresh( + messageDTO: message, + dependencies: dependencies, + scope: scope + ) } else { message } @@ -844,6 +930,32 @@ extension SyncCoordinator { ) } + /// A channel MCOimg that can rebuild its data field keys on that field. + /// Group text, and an MCOimg that cannot rebuild, keep the content key. + private nonisolated static func channelDeduplicationKey( + kind: IncomingMessageKind, + contactID: UUID?, + channelIndex: UInt8?, + senderNodeName: String?, + timestamp: UInt32, + content: String + ) -> String { + if case .mcoImage = kind, + let channelIndex, + let senderNodeName, + !senderNodeName.isEmpty, + let field = try? MCOImageTransport.dataField(text: content, senderName: senderNodeName) { + return DeduplicationKey.channelMCOImage(channelIndex: channelIndex, dataField: field) + } + return fallbackDeduplicationKey( + contactID: contactID, + channelIndex: channelIndex, + senderNodeName: senderNodeName, + timestamp: timestamp, + content: content + ) + } + nonisolated static func parseChannelMessage(_ text: String) -> (senderNodeName: String?, messageText: String) { let parts = text.split(separator: ":", maxSplits: 1) if parts.count > 1 { diff --git a/MC1Services/Sources/MC1Services/Utilities/ChannelRXCorrelation.swift b/MC1Services/Sources/MC1Services/Utilities/ChannelRXCorrelation.swift index 764ac468f8..ad8c3b0a67 100644 --- a/MC1Services/Sources/MC1Services/Utilities/ChannelRXCorrelation.swift +++ b/MC1Services/Sources/MC1Services/Utilities/ChannelRXCorrelation.swift @@ -30,4 +30,22 @@ enum ChannelRXCorrelation { } .sorted { $0.receivedAt < $1.receivedAt } } + + /// Group-datagram rows whose `0x0120` data field equals `blob`, oldest first. + /// Group text is not a match. Other data types are not a match. + static func matchingDatagrams( + _ entries: [RxLogEntryDTO], + blob: Data, + radioID: UUID, + channelIndex: UInt8 + ) -> [RxLogEntryDTO] { + entries.filter { entry in + entry.payloadType == .groupData && + entry.radioID == radioID && + entry.channelIndex == channelIndex && + entry.datagramDataType == MCOImageTransport.applicationDataType && + entry.datagramData == blob + } + .sorted { $0.receivedAt < $1.receivedAt } + } } diff --git a/MC1Services/Sources/MC1Services/Utilities/DeduplicationKey.swift b/MC1Services/Sources/MC1Services/Utilities/DeduplicationKey.swift index 71c176c167..754862220d 100644 --- a/MC1Services/Sources/MC1Services/Utilities/DeduplicationKey.swift +++ b/MC1Services/Sources/MC1Services/Utilities/DeduplicationKey.swift @@ -10,6 +10,15 @@ enum DeduplicationKey { static let outgoingIdentityPrefix = "out-" static let unknownContactPlaceholder = "unknown" + /// Not a decimal timestamp, so an MCOimg key cannot collide with a group-text key. + static let channelMCOImageMarker = "mcoimg" + + /// Incoming channel MCOimg identity: slot, marker, and data field. No clock. + static func channelMCOImage(channelIndex: UInt8, dataField: Data) -> String { + let encoded = dataField.map { String(format: "%02x", $0) }.joined() + return "\(channelPrefix)\(channelIndex)-\(channelMCOImageMarker)-\(encoded)" + } + static func contentBased( contactID: UUID?, channelIndex: UInt8?, diff --git a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift index 30f23455bb..07db0cd180 100644 --- a/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/BackupIntegrationTests.swift @@ -5608,6 +5608,286 @@ struct BackupIntegrationTests { #expect(object["isPinned"] as? Bool == true) #expect(object["isFavorite"] == nil) } + + @Test + func `import remaps an MCOimg from slot 2 onto the local slot 5 row and merges the path`() async throws { + let radioID = UUID() + let secret = Data(repeating: 0x42, count: 16) + let backupSlot: UInt8 = 2 + let localSlot: UInt8 = 5 + let fixture = try adaMCOImage() + let destStore = try await PersistenceStore.createTestDataStore(radioID: radioID) + try await destStore.saveChannel(ChannelDTO.testChannel( + radioID: radioID, index: localSlot, name: "#north", secret: secret + )) + let local = incomingMCOImage( + radioID: radioID, + channelIndex: localSlot, + text: fixture.text, + deduplicationKey: receiveSecondKey(channelIndex: localSlot, text: fixture.text, timestamp: 1_700_000_100), + pathNodes: Data([0x11]), + pathLength: 1 + ) + try await destStore.saveMessage(local) + + let backup = incomingMCOImage( + radioID: radioID, + channelIndex: backupSlot, + text: fixture.text, + deduplicationKey: DeduplicationKey.channelMCOImage(channelIndex: backupSlot, dataField: fixture.field), + pathNodes: Data([0x22]), + pathLength: 1 + ) + let result = try await AppBackupService().importBackup( + envelope: .test( + devices: [DeviceDTO.testDevice(id: radioID, radioID: radioID)], + channels: [ChannelDTO.testChannel( + id: UUID(), radioID: radioID, index: backupSlot, name: "#north", secret: secret + )], + messages: [backup] + ), + into: destStore + ) + + #expect(result.messagesInserted == 0) + #expect(result.messagesSkipped == 1) + let messages = try await destStore.fetchAllMessages(radioID: radioID) + let message = try #require(messages.first) + #expect(messages.count == 1) + #expect(message.id == local.id) + #expect(message.channelIndex == localSlot) + #expect(message.senderTimestamp == 0) + #expect(message.pathNodes == Data([0x11])) + #expect(message.heardRepeats == 1) + let repeats = try await destStore.fetchMessageRepeats(messageID: local.id) + #expect(repeats.map(\.pathNodes) == [Data([0x22])]) + } + + @Test + func `import of a data-field MCOimg key merges onto a receive-second key on the same slot`() async throws { + let radioID = UUID() + let secret = Data(repeating: 0x42, count: 16) + let slot: UInt8 = 2 + let fixture = try adaMCOImage() + let destStore = try await PersistenceStore.createTestDataStore(radioID: radioID) + try await destStore.saveChannel(ChannelDTO.testChannel( + radioID: radioID, index: slot, name: "#north", secret: secret + )) + let local = incomingMCOImage( + radioID: radioID, + channelIndex: slot, + text: fixture.text, + deduplicationKey: receiveSecondKey(channelIndex: slot, text: fixture.text, timestamp: 1_700_000_100), + pathNodes: Data([0x11]), + pathLength: 1 + ) + try await destStore.saveMessage(local) + + let backup = incomingMCOImage( + radioID: radioID, + channelIndex: slot, + text: fixture.text, + deduplicationKey: DeduplicationKey.channelMCOImage(channelIndex: slot, dataField: fixture.field), + pathNodes: Data([0x22]), + pathLength: 1 + ) + let result = try await AppBackupService().importBackup( + envelope: .test( + devices: [DeviceDTO.testDevice(id: radioID, radioID: radioID)], + channels: [ChannelDTO.testChannel( + id: UUID(), radioID: radioID, index: slot, name: "#north", secret: secret + )], + messages: [backup] + ), + into: destStore + ) + + #expect(result.messagesInserted == 0) + #expect(result.messagesSkipped == 1) + let messages = try await destStore.fetchAllMessages(radioID: radioID) + let message = try #require(messages.first) + #expect(messages.count == 1) + #expect(message.id == local.id) + #expect(message.channelIndex == slot) + #expect(message.senderTimestamp == 0) + #expect(message.pathNodes == Data([0x11])) + #expect(message.heardRepeats == 1) + #expect(try await destStore.fetchMessageRepeats(messageID: local.id).map(\.pathNodes) == [Data([0x22])]) + } + + @Test + func `import of two receive-second MCOimg keys for one data field keeps one row and the second reaction`() async throws { + let radioID = UUID() + let secret = Data(repeating: 0x42, count: 16) + let slot: UInt8 = 2 + let fixture = try adaMCOImage() + let destStore = try await PersistenceStore.createTestDataStore(radioID: radioID) + let firstID = UUID() + let secondID = UUID() + let first = incomingMCOImage( + id: firstID, + radioID: radioID, + channelIndex: slot, + text: fixture.text, + deduplicationKey: receiveSecondKey(channelIndex: slot, text: fixture.text, timestamp: 1_700_000_100), + pathNodes: Data([0x11]), + pathLength: 1 + ) + let second = incomingMCOImage( + id: secondID, + radioID: radioID, + channelIndex: slot, + text: fixture.text, + deduplicationKey: receiveSecondKey(channelIndex: slot, text: fixture.text, timestamp: 1_700_000_200), + pathNodes: Data([0x22]), + pathLength: 1 + ) + let reaction = ReactionDTO( + messageID: secondID, + emoji: "👍", + senderName: "Bea", + messageHash: "ABCD2345", + rawText: "@[Ada]👍ABCD2345", + channelIndex: slot, + radioID: radioID + ) + let result = try await AppBackupService().importBackup( + envelope: .test( + devices: [DeviceDTO.testDevice(id: radioID, radioID: radioID)], + channels: [ChannelDTO.testChannel( + id: UUID(), radioID: radioID, index: slot, name: "#north", secret: secret + )], + messages: [first, second], + reactions: [reaction] + ), + into: destStore + ) + + #expect(result.messagesInserted == 1) + #expect(result.messagesSkipped == 1) + #expect(result.reactionsInserted == 1) + let messages = try await destStore.fetchAllMessages(radioID: radioID) + let message = try #require(messages.first) + #expect(messages.count == 1) + #expect(message.id == firstID) + #expect(message.senderTimestamp == 0) + #expect(message.pathNodes == Data([0x11])) + #expect(message.heardRepeats == 1) + #expect(try await destStore.fetchMessageRepeats(messageID: firstID).map(\.pathNodes) == [Data([0x22])]) + let reactions = try await destStore.fetchReactions(for: firstID) + #expect(reactions.count == 1) + #expect(reactions.first?.senderName == "Bea") + } + + @Test + func `import keeps an MCOimg on channel 2 and channel 3 and the second reaction`() async throws { + let radioID = UUID() + let fixture = try adaMCOImage() + let destStore = try await PersistenceStore.createTestDataStore(radioID: radioID) + let slot2: UInt8 = 2 + let slot3: UInt8 = 3 + let secret2 = Data(repeating: 0x42, count: 16) + let secret3 = Data(repeating: 0x43, count: 16) + try await destStore.saveChannel(ChannelDTO.testChannel( + radioID: radioID, index: slot2, name: "#north", secret: secret2 + )) + try await destStore.saveChannel(ChannelDTO.testChannel( + radioID: radioID, index: slot3, name: "#south", secret: secret3 + )) + let firstID = UUID() + let secondID = UUID() + let first = incomingMCOImage( + id: firstID, + radioID: radioID, + channelIndex: slot2, + text: fixture.text, + deduplicationKey: DeduplicationKey.channelMCOImage(channelIndex: slot2, dataField: fixture.field), + pathNodes: Data([0x11]), + pathLength: 1 + ) + let second = incomingMCOImage( + id: secondID, + radioID: radioID, + channelIndex: slot3, + text: fixture.text, + deduplicationKey: DeduplicationKey.channelMCOImage(channelIndex: slot3, dataField: fixture.field), + pathNodes: Data([0x22]), + pathLength: 1 + ) + let reaction = ReactionDTO( + messageID: secondID, + emoji: "👍", + senderName: "Bea", + messageHash: "ABCD2345", + rawText: "@[Ada]👍ABCD2345", + channelIndex: slot3, + radioID: radioID + ) + let result = try await AppBackupService().importBackup( + envelope: .test( + devices: [DeviceDTO.testDevice(id: radioID, radioID: radioID)], + channels: [ + ChannelDTO.testChannel(id: UUID(), radioID: radioID, index: slot2, name: "#north", secret: secret2), + ChannelDTO.testChannel(id: UUID(), radioID: radioID, index: slot3, name: "#south", secret: secret3) + ], + messages: [first, second], + reactions: [reaction] + ), + into: destStore + ) + + #expect(result.messagesInserted == 2) + #expect(result.messagesSkipped == 0) + let messages = try await destStore.fetchAllMessages(radioID: radioID) + #expect(messages.count == 2) + #expect(Set(messages.map(\.id)) == Set([firstID, secondID])) + let reactions = try await destStore.fetchReactions(for: secondID) + #expect(reactions.count == 1) + #expect(reactions.first?.senderName == "Bea") + #expect(try await destStore.fetchReactions(for: firstID).isEmpty) + } + + private func adaMCOImage() throws -> (text: String, field: Data) { + let payload = try #require(Data(base64Encoded: "E3oBjQBCvgE=")) + let text = try MCOImageCodec.text(fromAppPayload: payload) + let field = try MCOImageTransport.dataField(text: text, senderName: "Ada") + return (text, field) + } + + private func receiveSecondKey(channelIndex: UInt8, text: String, timestamp: UInt32) -> String { + DeduplicationKey.contentBased( + contactID: nil, + channelIndex: channelIndex, + senderNodeName: "Ada", + timestamp: timestamp, + content: text + ) + } + + private func incomingMCOImage( + id: UUID = UUID(), + radioID: UUID, + channelIndex: UInt8, + text: String, + deduplicationKey: String, + pathNodes: Data?, + pathLength: UInt8 + ) -> MessageDTO { + var message = MessageDTO.testChannelMessage( + id: id, + radioID: radioID, + channelIndex: channelIndex, + text: text, + timestamp: 1_700_000_000, + direction: .incoming, + pathLength: pathLength, + senderNodeName: "Ada" + ) + message.senderTimestamp = 0 + message.deduplicationKey = deduplicationKey + message.pathNodes = pathNodes + return message + } } private enum InjectedImportFailure: Error { diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift index 93fbfbb0d4..f56cbc84bc 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift @@ -1,3 +1,5 @@ +import CommonCrypto +import CryptoKit import Foundation @testable import MC1Services import MeshCoreTestSupport @@ -144,6 +146,272 @@ struct MCOImageReceiveIntegrationTests { #expect(messages.first?.senderNodeName == sender) } + @Test + func `two MCOimg pushes more than a minute apart stay one row and take the later RX path`() async throws { + let opened = try await openChannel() + defer { Task { await opened.services.tearDown() } } + let payload = try v3Payload() + let first = Date(timeIntervalSince1970: 1_700_000_000) + try await push(opened, payload: payload, at: first) + try await plantRX(opened, payload: payload, path: [0x21]) + try await push(opened, payload: payload, at: first.addingTimeInterval(61)) + + let messages = try await opened.store.fetchMessages(radioID: opened.radioID, channelIndex: opened.channel.index) + let message = try #require(messages.first) + #expect(messages.count == 1) + #expect(message.senderTimestamp == 0) + #expect(message.pathNodes == Data([0x21])) + #expect(message.pathLength == 1) + #expect(message.snr == 6.25) + #expect(message.heardRepeats == 0) + #expect(try await opened.store.fetchMessageRepeats(messageID: message.id).isEmpty) + } + + @Test + func `two MCOimg pushes with no RX row keep the push path length`() async throws { + let opened = try await openChannel() + defer { Task { await opened.services.tearDown() } } + let payload = try v3Payload() + let first = Date(timeIntervalSince1970: 1_700_000_000) + try await push(opened, payload: payload, at: first) + try await push(opened, payload: payload, at: first.addingTimeInterval(61)) + + let messages = try await opened.store.fetchMessages(radioID: opened.radioID, channelIndex: opened.channel.index) + let message = try #require(messages.first) + #expect(messages.count == 1) + #expect(message.senderNodeName == "Ada") + #expect(message.senderTimestamp == 0) + #expect(message.pathNodes == nil) + #expect(message.pathLength == 2) + #expect(message.snr == 6.25) + } + + @Test + func `a different MCOimg data field saves a second message`() async throws { + let opened = try await openChannel() + defer { Task { await opened.services.tearDown() } } + let when = Date(timeIntervalSince1970: 1_700_000_000) + try await push(opened, payload: v3Payload(), at: when) + try await push(opened, payload: Data([0x14, 0, 0, 0, 0]), at: when.addingTimeInterval(61)) + + let messages = try await opened.store.fetchMessages(radioID: opened.radioID, channelIndex: opened.channel.index) + #expect(messages.count == 2) + #expect(messages.allSatisfy { $0.senderTimestamp == 0 }) + } + + @Test + func `an older receive-second MCOimg key absorbs the later push`() async throws { + let opened = try await openChannel() + defer { Task { await opened.services.tearDown() } } + let payload = try v3Payload() + let text = try MCOImageCodec.text(fromAppPayload: payload) + let receiveSecond: UInt32 = 1_700_000_100 + var stored = MessageDTO.testChannelMessage( + radioID: opened.radioID, + channelIndex: opened.channel.index, + text: text, + timestamp: receiveSecond, + direction: .incoming, + pathLength: 1, + senderNodeName: "Ada" + ) + stored.senderTimestamp = 0 + stored.deduplicationKey = DeduplicationKey.contentBased( + contactID: nil, + channelIndex: opened.channel.index, + senderNodeName: "Ada", + timestamp: receiveSecond, + content: text + ) + stored.pathNodes = Data([0x11]) + try await opened.store.saveMessage(stored) + + try await push(opened, payload: payload, at: Date(timeIntervalSince1970: 1_700_000_200)) + + let messages = try await opened.store.fetchMessages(radioID: opened.radioID, channelIndex: opened.channel.index) + let message = try #require(messages.first) + #expect(messages.count == 1) + #expect(message.id == stored.id) + #expect(message.senderTimestamp == 0) + #expect(message.deduplicationKey?.contains("1700000100") == true) + #expect(message.pathNodes == Data([0x11])) + #expect(message.pathLength == 1) + } + + @Test + func `group text at wire time 0 with an im4 body stays beside the MCOimg`() async throws { + let opened = try await openChannel() + defer { Task { await opened.services.tearDown() } } + let payload = Data([0x14, 0, 0, 0, 0]) + let text = try MCOImageCodec.text(fromAppPayload: payload) + #expect(text.hasPrefix("im4:")) + var textRow = MessageDTO.testChannelMessage( + radioID: opened.radioID, + channelIndex: opened.channel.index, + text: text, + timestamp: 0, + direction: .incoming, + pathLength: 1, + senderNodeName: "Ada" + ) + textRow.senderTimestamp = 0 + textRow.deduplicationKey = DeduplicationKey.contentBased( + contactID: nil, + channelIndex: opened.channel.index, + senderNodeName: "Ada", + timestamp: 0, + content: text + ) + textRow.pathNodes = Data([0x31]) + try await opened.store.saveMessage(textRow) + + try await push(opened, payload: payload, at: Date(timeIntervalSince1970: 1_700_000_300)) + + let messages = try await opened.store.fetchMessages(radioID: opened.radioID, channelIndex: opened.channel.index) + #expect(messages.count == 2) + let kept = try #require(messages.first { $0.id == textRow.id }) + let datagram = try #require(messages.first { $0.id != textRow.id }) + #expect(kept.pathNodes == Data([0x31])) + #expect(kept.pathLength == 1) + #expect(kept.isDatagramPathMCOImage == false) + #expect(datagram.senderTimestamp == 0) + #expect(datagram.isDatagramPathMCOImage) + } + + @Test + func `an outgoing MCOimg saved after its RX row records that repeat`() async throws { + let opened = try await openChannel() + defer { Task { await opened.services.tearDown() } } + let text = try outgoingChannelText() + let payload = try MCOImageCodec.appPayload(fromText: text) + try await plantRX(opened, payload: payload, path: [0x21], sender: "TestDevice") + _ = try await opened.services.messageService.createPendingChannelMessage( + text: text, + channelIndex: opened.channel.index, + radioID: opened.radioID + ) + + let messages = try await opened.store.fetchMessages(radioID: opened.radioID, channelIndex: opened.channel.index) + let message = try #require(messages.first) + let rxID = try #require(try await opened.store.fetchRxLogEntries(radioID: opened.radioID, limit: 10).first?.id) + #expect(messages.count == 1) + #expect(message.isOutgoing) + #expect(message.heardRepeats == 1) + #expect(try await opened.store.fetchMessageRepeats(messageID: message.id).map(\.rxLogEntryID) == [rxID]) + } + + private struct OpenedChannel { + let radioID: UUID + let store: PersistenceStore + let channel: ChannelDTO + let services: ServiceContainer + /// The datagram handler captures the coordinator weakly. + let coordinator: SyncCoordinator + let handler: DatagramHandler + let scope: ReceiveScope + let secret: Data + } + + private typealias DatagramHandler = @Sendable ( + ChannelDatagram, ChannelDTO?, DeliveryContext, ReceiveScope, TextRulesPreference?, Date + ) async -> Void + + private func openChannel(secret: Data = Data(repeating: 0x42, count: 16)) async throws -> OpenedChannel { + let radioID = UUID() + let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) + try await store.saveDevice(.testDevice(id: radioID)) + let channel = ChannelDTO.testChannel(radioID: radioID, index: 2, secret: secret) + try await store.saveChannel(channel) + let services = ServiceContainer( + session: MeshCoreSession(transport: SimulatorMockTransport()), + dataStore: store, + radioID: radioID + ) + services.notificationService.isSuppressingNotifications = true + let poller = MockMessagePollingService() + let coordinator = SyncCoordinator() + await coordinator.wireMessageHandlers( + dependencies: services.syncDependencies.with(dataStore: store, messagePollingService: poller), + radioID: radioID + ) + let handler = try #require(await poller.capturedChannelDatagramHandler) + let scope = try #require(try await store.captureReceiveScope(radioID: radioID, link: ReceiveScope.Lifetime())) + return OpenedChannel( + radioID: radioID, + store: store, + channel: channel, + services: services, + coordinator: coordinator, + handler: handler, + scope: scope, + secret: secret + ) + } + + private func push(_ opened: OpenedChannel, payload: Data, at date: Date) async throws { + let text = try MCOImageCodec.text(fromAppPayload: payload) + let field = try MCOImageTransport.dataField(text: text, senderName: "Ada") + await opened.handler( + ChannelDatagram( + channelIndex: opened.channel.index, + pathLength: 2, + dataType: MCOImageTransport.applicationDataType, + data: field, + snr: 6.25 + ), + opened.channel, + .live, + opened.scope, + nil, + date + ) + } + + private func plantRX( + _ opened: OpenedChannel, + payload: Data, + path: [UInt8], + sender: String = "Ada" + ) async throws { + let text = try MCOImageCodec.text(fromAppPayload: payload) + let field = try MCOImageTransport.dataField(text: text, senderName: sender) + await opened.services.heardRepeatsService.configure(radioID: opened.radioID) + await opened.services.rxLogService.startEventMonitoring(radioID: opened.radioID) + await opened.services.rxLogService.updateChannels( + secrets: [opened.channel.index: opened.secret], + names: [opened.channel.index: opened.channel.name] + ) + let wire = Self.encryptedGroupDatagram( + dataType: MCOImageTransport.applicationDataType, + data: field, + secret: opened.secret + ) + await opened.services.rxLogService.process(ParsedRxLogData( + snr: 1, + rssi: -80, + rawPayload: wire, + routeType: .flood, + payloadType: .groupData, + payloadVersion: 0, + payloadTypeBits: 6, + transportCode: nil, + pathLength: UInt8(path.count), + pathNodes: path, + packetPayload: wire + )) + } + + private func v3Payload() throws -> Data { + try #require(Data(base64Encoded: "E3oBjQBCvgE=")) + } + + /// Text `prepareChannelMessage` stores. The send path upgrades a v3 payload before the row is saved. + private func outgoingChannelText() throws -> String { + let source = try MCOImageCodec.text(fromAppPayload: v3Payload()) + let payload = try MCOImageCodec.channelAppPayload(fromText: source) + return try MCOImageCodec.text(fromAppPayload: payload) + } + private func datagram(channel: ChannelDTO, sender: String, payload: Data) -> ChannelDatagram { ChannelDatagram( channelIndex: channel.index, @@ -153,4 +421,45 @@ struct MCOImageReceiveIntegrationTests { snr: 6.25 ) } + + private static func encryptedGroupDatagram(dataType: UInt16, data: Data, secret: Data) -> Data { + var plaintext = withUnsafeBytes(of: dataType.littleEndian) { Data($0) } + plaintext.append(UInt8(data.count)) + plaintext.append(data) + return encryptedRawPlaintext(plaintext, secret: secret) + } + + private static func encryptedRawPlaintext(_ plaintext: Data, secret: Data) -> Data { + var padded = plaintext + let blockSize = kCCBlockSizeAES128 + let paddedCount = (padded.count + blockSize - 1) / blockSize * blockSize + if padded.count < paddedCount { + padded.append(Data(count: paddedCount - padded.count)) + } + var ciphertext = Data(count: padded.count) + var encryptedCount: size_t = 0 + let keyBytes = secret.prefix(kCCKeySizeAES128) + let status = ciphertext.withUnsafeMutableBytes { outPtr in + padded.withUnsafeBytes { inPtr in + keyBytes.withUnsafeBytes { keyPtr in + CCCrypt( + CCOperation(kCCEncrypt), + CCAlgorithm(kCCAlgorithmAES), + CCOptions(kCCOptionECBMode), + keyPtr.baseAddress, kCCKeySizeAES128, + nil, + inPtr.baseAddress, padded.count, + outPtr.baseAddress, padded.count, + &encryptedCount + ) + } + } + } + precondition(status == kCCSuccess, "test fixture encryption failed") + let mac = Data( + HMAC.authenticationCode(for: ciphertext, using: SymmetricKey(data: secret)) + .prefix(ChannelCrypto.macSize) + ) + return Data([0x00]) + mac + ciphertext.prefix(encryptedCount) + } } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift index 36801a403d..2def917daa 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift @@ -659,4 +659,272 @@ struct HeardRepeatsServiceTests { #expect(repeats.count == 1) #expect(repeats.first?.pathNodes == Data([0xBB])) } + + // MARK: - Datagram paths + + private let imageText = "im3:g/5WjAL`NA" + private let imageSender = "Ada" + + private func imageBlob() throws -> Data { + try MCOImageTransport.dataField(text: imageText, senderName: imageSender) + } + + private func channelMCOImage( + id: UUID = UUID(), + radioID: UUID, + channelIndex: UInt8, + direction: MessageDirection, + senderTimestamp: UInt32?, + deduplicationKey: String?, + pathLength: UInt8 = 4, + snr: Double? = 9, + timestamp: UInt32 = 1_700_000_000 + ) -> MessageDTO { + var message = MessageDTO.testChannelMessage( + id: id, + radioID: radioID, + channelIndex: channelIndex, + text: imageText, + timestamp: timestamp, + direction: direction, + pathLength: pathLength, + snr: snr, + senderNodeName: imageSender + ) + message.senderTimestamp = senderTimestamp + message.deduplicationKey = deduplicationKey + message.pathNodes = nil + return message + } + + private func makeDatagramEcho( + radioID: UUID, + channelIndex: UInt8, + blob: Data, + id: UUID = UUID(), + pathNodes: [UInt8] = [0x42], + pathLength: UInt8 = 1, + receivedAt: Date = Date(), + routeType: RouteType = .flood, + regionScope: String? = nil, + dataType: UInt16 = MCOImageTransport.applicationDataType + ) -> RxLogEntryDTO { + let parsed = ParsedRxLogData( + snr: 1.0, + rssi: -80, + rawPayload: Data([0x01]), + routeType: routeType, + payloadType: .groupData, + payloadVersion: 0, + payloadTypeBits: 6, + transportCode: nil, + pathLength: pathLength, + pathNodes: pathNodes, + packetPayload: Data([0x01]) + ) + return RxLogEntryDTO( + id: id, + radioID: radioID, + receivedAt: receivedAt, + from: parsed, + channelIndex: channelIndex, + decryptStatus: .success, + regionScope: regionScope, + datagramDataType: dataType, + datagramData: blob + ) + } + + @Test + func `one outgoing channel MCOimg and one RX row count a single echo`() async throws { + let (store, service) = try makeStoreAndService() + let radioID = UUID() + let channelIndex: UInt8 = 1 + let blob = try imageBlob() + let message = channelMCOImage( + radioID: radioID, + channelIndex: channelIndex, + direction: .outgoing, + senderTimestamp: nil, + deduplicationKey: nil + ) + try await store.saveMessage(message) + await service.configure(radioID: radioID) + + let echo = makeDatagramEcho(radioID: radioID, channelIndex: channelIndex, blob: blob) + let count = await service.processForRepeats(echo) + let again = await service.processForRepeats(echo) + let other = await service.processForRepeats(makeDatagramEcho( + radioID: radioID, + channelIndex: channelIndex, + blob: Data([0x00]) + )) + + #expect(count == 1) + #expect(again == nil) + #expect(other == nil) + let updated = try #require(await store.fetchMessage(id: message.id)) + #expect(updated.heardRepeats == 1) + #expect(updated.snr == 9) + let repeats = try await store.fetchMessageRepeats(messageID: message.id) + #expect(repeats.count == 1) + #expect(repeats.first?.rxLogEntryID == echo.id) + } + + @Test + func `an incoming extra path increments and an empty path is one arrival`() async throws { + let (store, service) = try makeStoreAndService() + let radioID = UUID() + let channelIndex: UInt8 = 2 + let blob = try imageBlob() + let message = channelMCOImage( + radioID: radioID, + channelIndex: channelIndex, + direction: .incoming, + senderTimestamp: 0, + deduplicationKey: "ch-2-mcoimg" + ) + try await store.saveMessage(message) + await service.configure(radioID: radioID) + + let empty = makeDatagramEcho( + radioID: radioID, channelIndex: channelIndex, blob: blob, pathNodes: [], pathLength: 0 + ) + _ = await service.processForRepeats(empty) + _ = await service.processForRepeats(makeDatagramEcho( + radioID: radioID, channelIndex: channelIndex, blob: blob, pathNodes: [], pathLength: 0 + )) + var afterEmpty = try #require(await store.fetchMessage(id: message.id)) + #expect(afterEmpty.pathNodes == Data()) + #expect(afterEmpty.pathLength == 0) + #expect(afterEmpty.heardRepeats == 0) + #expect(afterEmpty.senderTimestamp == 0) + #expect(afterEmpty.snr == 9) + + _ = await service.processForRepeats(makeDatagramEcho( + radioID: radioID, channelIndex: channelIndex, blob: blob, pathNodes: [0x21], pathLength: 1 + )) + afterEmpty = try #require(await store.fetchMessage(id: message.id)) + #expect(afterEmpty.heardRepeats == 1) + let repeats = try await store.fetchMessageRepeats(messageID: message.id) + #expect(repeats.count == 1) + #expect(repeats.first?.pathNodes == Data([0x21])) + } + + @Test + func `the earliest datagram RX row becomes the canonical path`() async throws { + let (store, service) = try makeStoreAndService() + let radioID = UUID() + let blob = try imageBlob() + let message = channelMCOImage( + radioID: radioID, channelIndex: 3, direction: .incoming, + senderTimestamp: 0, deduplicationKey: "ch-3-mcoimg" + ) + try await store.saveMessage(message) + await service.configure(radioID: radioID) + let earlier = Date(timeIntervalSince1970: 1_700_000_100) + let later = earlier.addingTimeInterval(2) + let first = makeDatagramEcho( + radioID: radioID, channelIndex: 3, blob: blob, + pathNodes: [0xAA], pathLength: 1, receivedAt: earlier, routeType: .flood, regionScope: "Ridge" + ) + let second = makeDatagramEcho( + radioID: radioID, channelIndex: 3, blob: blob, + pathNodes: [0xBB], pathLength: 2, receivedAt: later + ) + await service.harvestDatagramPaths(for: message, decodedCandidates: [second, first]) + + let updated = try #require(await store.fetchMessage(id: message.id)) + #expect(updated.pathNodes == Data([0xAA])) + #expect(updated.pathLength == 1) + #expect(updated.routeType == .flood) + #expect(updated.regionScope == "Ridge") + #expect(updated.heardRepeats == 1) + #expect(updated.senderTimestamp == 0) + #expect(updated.snr == 9) + let repeats = try await store.fetchMessageRepeats(messageID: message.id) + #expect(repeats.map(\.rxLogEntryID) == [second.id]) + } + + @Test + func `group text with wire time 0 does not take the datagram path`() async throws { + let (store, service) = try makeStoreAndService() + let radioID = UUID() + let channelIndex: UInt8 = 4 + let blob = try imageBlob() + let key = DeduplicationKey.contentBased( + contactID: nil, + channelIndex: channelIndex, + senderNodeName: imageSender, + timestamp: 0, + content: imageText + ) + var message = channelMCOImage( + radioID: radioID, + channelIndex: channelIndex, + direction: .incoming, + senderTimestamp: 0, + deduplicationKey: key, + pathLength: 7 + ) + message.pathNodes = Data([0x99]) + try await store.saveMessage(message) + await service.configure(radioID: radioID) + + let count = await service.processForRepeats(makeDatagramEcho( + radioID: radioID, channelIndex: channelIndex, blob: blob, pathNodes: [0x11] + )) + #expect(count == nil) + let updated = try #require(await store.fetchMessage(id: message.id)) + #expect(updated.pathNodes == Data([0x99])) + #expect(updated.pathLength == 7) + #expect(updated.heardRepeats == 0) + let repeats = try await store.fetchMessageRepeats(messageID: message.id) + #expect(repeats.isEmpty) + } + + @Test + func `a later datagram region updates the MCOimg and a timestamp 0 write does not`() async throws { + let (store, service) = try makeStoreAndService() + let radioID = UUID() + let channelIndex: UInt8 = 5 + let blob = try imageBlob() + let message = channelMCOImage( + radioID: radioID, channelIndex: channelIndex, direction: .incoming, + senderTimestamp: 0, deduplicationKey: "ch-5-mcoimg" + ) + try await store.saveMessage(message) + var text = MessageDTO.testChannelMessage( + radioID: radioID, + channelIndex: channelIndex, + text: "plain", + timestamp: 50, + direction: .incoming, + senderNodeName: "Ada" + ) + text.senderTimestamp = 0 + text.deduplicationKey = DeduplicationKey.contentBased( + contactID: nil, channelIndex: channelIndex, senderNodeName: "Ada", timestamp: 0, content: "plain" + ) + try await store.saveMessage(text) + + let echo = makeDatagramEcho(radioID: radioID, channelIndex: channelIndex, blob: blob, pathNodes: [0x01]) + await service.copyDatagramRegionIfCanonical( + entry: echo, + regionScope: "Ridge", + regionScopeMatches: ["Ridge"], + channelEntries: [echo] + ) + var updated = try #require(await store.fetchMessage(id: message.id)) + #expect(updated.regionScope == "Ridge") + + _ = try await store.batchUpdateChannelMessageRegion( + radioID: radioID, + updates: [(channelIndex: channelIndex, senderTimestamp: 0, regionScope: "South", regionScopeMatches: ["South"])] + ) + updated = try #require(await store.fetchMessage(id: message.id)) + let textRow = try #require(await store.fetchMessage(id: text.id)) + #expect(updated.regionScope == "Ridge") + #expect(textRow.regionScope == "South") + } } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/RxLogServiceReprocessTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/RxLogServiceReprocessTests.swift index 0408ee254a..2186e6ceac 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/RxLogServiceReprocessTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/RxLogServiceReprocessTests.swift @@ -69,6 +69,124 @@ struct RxLogServiceReprocessTests { #expect(updated.decryptStatus == .success) } + @Test + func `group datagram decrypt exposes the data field and a nil sender timestamp`() async throws { + let radioID = UUID() + let secret = Data(repeating: 0x42, count: 16) + let container = try PersistenceStore.createContainer(inMemory: true) + let dataStore = PersistenceStore(modelContainer: container) + let session = MeshCoreSession(transport: MockTransport()) + let service = RxLogService(session: session, dataStore: dataStore, heardRepeatsService: nil) + try await dataStore.saveChannel(ChannelDTO.testChannel( + radioID: radioID, index: 0, name: "Public", secret: secret + )) + await service.startEventMonitoring(radioID: radioID) + defer { Task { await service.stopEventMonitoring() } } + await service.updateChannels(secrets: [0: secret], names: [0: "Public"]) + + let blob = Data([0x13, 0x01, 0xAA]) + await service.process(Self.makeParsed( + payloadType: .groupData, + packetPayload: Self.encryptedGroupDatagram(dataType: 0x0120, data: blob, secret: secret) + )) + + let stored = try #require(try await dataStore.fetchRxLogEntries(radioID: radioID).first) + #expect(stored.channelIndex == 0) + #expect(stored.senderTimestamp == nil) + #expect(stored.decryptStatus == .success) + #expect(stored.datagramDataType == nil, "the data field is not a stored column") + + let decoded = await service.decryptEntry(stored) + #expect(decoded.datagramDataType == 0x0120) + #expect(decoded.datagramData == blob) + #expect(decoded.senderTimestamp == nil) + #expect(decoded.decodedText == nil) + } + + @Test + func `a truncated or bad MAC datagram does not set a channel or sender timestamp`() async throws { + let radioID = UUID() + let secret = Data(repeating: 0x42, count: 16) + let container = try PersistenceStore.createContainer(inMemory: true) + let dataStore = PersistenceStore(modelContainer: container) + let session = MeshCoreSession(transport: MockTransport()) + let service = RxLogService(session: session, dataStore: dataStore, heardRepeatsService: nil) + try await dataStore.saveChannel(ChannelDTO.testChannel( + radioID: radioID, index: 0, name: "Public", secret: secret + )) + await service.startEventMonitoring(radioID: radioID) + defer { Task { await service.stopEventMonitoring() } } + await service.updateChannels(secrets: [0: secret], names: [0: "Public"]) + + await service.process(Self.makeParsed( + payloadType: .groupData, + packetPayload: Data(repeating: 0, count: 8) + )) + var badMAC = Self.encryptedGroupDatagram(dataType: 0x0120, data: Data([0x01]), secret: secret) + badMAC[1] ^= 0xFF + badMAC[2] ^= 0xFF + await service.process(Self.makeParsed(payloadType: .groupData, packetPayload: badMAC)) + var overLong = Data(count: 16) + overLong[0] = 0x20 + overLong[1] = 0x01 + overLong[2] = 14 + await service.process(Self.makeParsed( + payloadType: .groupData, + packetPayload: Self.encryptedRawPlaintext(overLong, secret: secret) + )) + + let stored = try await dataStore.fetchRxLogEntries(radioID: radioID) + #expect(stored.count == 3) + for entry in stored { + #expect(entry.channelIndex == nil) + #expect(entry.senderTimestamp == nil) + #expect(entry.decryptStatus != .success) + let decoded = await service.decryptEntry(entry) + #expect(decoded.datagramDataType == nil) + #expect(decoded.senderTimestamp == nil) + } + } + + @Test + func `a group datagram saved with no matching key gains its channel and keeps a nil sender timestamp`() async throws { + let radioID = UUID() + let container = try PersistenceStore.createContainer(inMemory: true) + let dataStore = PersistenceStore(modelContainer: container) + let session = MeshCoreSession(transport: MockTransport()) + let service = RxLogService(session: session, dataStore: dataStore, heardRepeatsService: nil) + + let secret = Data(repeating: 0x42, count: 16) + try await dataStore.saveChannel(ChannelDTO.testChannel( + radioID: radioID, index: 3, name: "Three", secret: secret + )) + await service.startEventMonitoring(radioID: radioID) + defer { Task { await service.stopEventMonitoring() } } + + let blob = Data([0x13, 0x04, 0x01]) + let entry = RxLogEntryDTO( + radioID: radioID, + from: Self.makeParsed( + payloadType: .groupData, + packetPayload: Self.encryptedGroupDatagram(dataType: 0x0120, data: blob, secret: secret) + ), + decryptStatus: .noMatchingKey + ) + try await dataStore.saveRxLogEntry(entry) + + await service.updateChannels(secrets: [3: secret], names: [3: "Three"]) + + let updated = try #require(try await dataStore.fetchRxLogEntries(radioID: radioID).first { $0.id == entry.id }) + #expect(updated.channelIndex == 3) + #expect(updated.channelName == "Three") + #expect(updated.senderTimestamp == nil) + #expect(updated.decryptStatus == .success) + let decoded = await service.decryptEntry(updated) + #expect(decoded.datagramDataType == 0x0120) + #expect(decoded.datagramData == blob) + #expect(decoded.senderTimestamp == nil) + #expect(decoded.decodedText == nil) + } + @Test func `coexisting entry stream subscribers each receive every entry`() async throws { let radioID = UUID() @@ -190,4 +308,45 @@ struct RxLogServiceReprocessTests { ) return Data([0x00]) + mac + ciphertext.prefix(encryptedCount) } + + private static func encryptedGroupDatagram(dataType: UInt16, data: Data, secret: Data) -> Data { + var plaintext = withUnsafeBytes(of: dataType.littleEndian) { Data($0) } + plaintext.append(UInt8(data.count)) + plaintext.append(data) + return encryptedRawPlaintext(plaintext, secret: secret) + } + + private static func encryptedRawPlaintext(_ plaintext: Data, secret: Data) -> Data { + var padded = plaintext + let blockSize = kCCBlockSizeAES128 + let paddedCount = (padded.count + blockSize - 1) / blockSize * blockSize + if padded.count < paddedCount { + padded.append(Data(count: paddedCount - padded.count)) + } + var ciphertext = Data(count: padded.count) + var encryptedCount: size_t = 0 + let keyBytes = secret.prefix(kCCKeySizeAES128) + let status = ciphertext.withUnsafeMutableBytes { outPtr in + padded.withUnsafeBytes { inPtr in + keyBytes.withUnsafeBytes { keyPtr in + CCCrypt( + CCOperation(kCCEncrypt), + CCAlgorithm(kCCAlgorithmAES), + CCOptions(kCCOptionECBMode), + keyPtr.baseAddress, kCCKeySizeAES128, + nil, + inPtr.baseAddress, padded.count, + outPtr.baseAddress, padded.count, + &encryptedCount + ) + } + } + } + precondition(status == kCCSuccess, "test fixture encryption failed") + let mac = Data( + HMAC.authenticationCode(for: ciphertext, using: SymmetricKey(data: secret)) + .prefix(ChannelCrypto.macSize) + ) + return Data([0x00]) + mac + ciphertext.prefix(encryptedCount) + } } diff --git a/MeshCore/Sources/MeshCore/Protocol/ChannelCrypto.swift b/MeshCore/Sources/MeshCore/Protocol/ChannelCrypto.swift index 0e53e6958a..2f70064f19 100644 --- a/MeshCore/Sources/MeshCore/Protocol/ChannelCrypto.swift +++ b/MeshCore/Sources/MeshCore/Protocol/ChannelCrypto.swift @@ -22,6 +22,23 @@ public enum ChannelCrypto { /// Total header size before message text: timestamp (4) + txt_type (1) = 5 bytes. public static let plaintextHeaderSize = timestampSize + txtTypeSize + /// Little-endian data type at the start of a group-datagram plaintext. + public static let groupDatagramTypeSize = 2 + + /// Length byte that follows the group-datagram data type. + public static let groupDatagramLengthSize = 1 + + /// Bytes before the group-datagram blob: data type (2) + length (1). + public static let groupDatagramHeaderSize = groupDatagramTypeSize + groupDatagramLengthSize + + /// MAC-checked AES plaintext, still including block padding. + public enum PlaintextResult: Sendable { + case success(Data) + case hmacFailed + case decryptFailed + case payloadTooShort + } + /// Result of attempting to decrypt a channel message. public enum DecryptResult: Sendable { /// Successfully decrypted the message. @@ -38,34 +55,59 @@ public enum ChannelCrypto { case payloadTooShort } - /// Decrypt a channel message payload. - /// - /// - Parameters: - /// - payload: The channel message payload (after channel index byte). - /// Format: [MAC: 2B] [ciphertext: N bytes] - /// - secret: The 16-byte channel secret. - /// - Returns: Decryption result with message text or failure reason. - public static func decrypt(payload: Data, secret: Data) -> DecryptResult { - // Minimum: 2 bytes MAC + 16 bytes (1 AES block for timestamp + some text) + /// MAC-check and AES-128-ECB decrypt. The plaintext still includes block padding. + /// AES uses the first 16 secret bytes. HMAC uses the whole secret. + public static func decryptPlaintext(payload: Data, secret: Data) -> PlaintextResult { guard payload.count >= macSize + 16 else { return .payloadTooShort } let receivedMAC = payload.prefix(macSize) let ciphertext = Data(payload.dropFirst(macSize)) - - // Verify HMAC-SHA256 (truncated to 2 bytes) let computedMAC = computeHMAC(data: ciphertext, key: secret) guard receivedMAC == computedMAC else { return .hmacFailed } - // Decrypt using AES-128 ECB guard let plaintext = decryptAES128ECB(ciphertext: ciphertext, key: secret) else { return .decryptFailed } + return .success(plaintext) + } - // Parse decrypted payload: [timestamp: 4B] [txt_type: 1B] [message: rest] + /// Decrypt a group-text payload into a timestamp, text type, and UTF-8 body. + /// + /// - Parameters: + /// - payload: The channel message payload (after channel index byte). + /// Format: [MAC: 2B] [ciphertext: N bytes] + /// - secret: The 16-byte channel secret. + /// - Returns: Decryption result with message text or failure reason. + public static func decrypt(payload: Data, secret: Data) -> DecryptResult { + switch decryptPlaintext(payload: payload, secret: secret) { + case .hmacFailed: + .hmacFailed + case .decryptFailed: + .decryptFailed + case .payloadTooShort: + .payloadTooShort + case let .success(plaintext): + parseGroupText(plaintext) + } + } + + /// Little-endian data type, one length byte, then that blob. + /// A short header or a length past the plaintext returns nil. Padding after the blob is not the data field. + public static func readGroupDatagram(_ plaintext: Data) -> (dataType: UInt16, data: Data)? { + guard plaintext.count >= groupDatagramHeaderSize else { return nil } + let dataType = plaintext.readUInt16LE(at: 0) + let declared = Int(plaintext[plaintext.startIndex + groupDatagramTypeSize]) + let available = plaintext.count - groupDatagramHeaderSize + guard declared <= available else { return nil } + let body = plaintext.dropFirst(groupDatagramHeaderSize).prefix(declared) + return (dataType, Data(body)) + } + + private static func parseGroupText(_ plaintext: Data) -> DecryptResult { guard plaintext.count >= plaintextHeaderSize else { return .decryptFailed } @@ -73,17 +115,12 @@ public enum ChannelCrypto { let timestamp = plaintext.prefix(timestampSize).withUnsafeBytes { $0.loadUnaligned(as: UInt32.self).littleEndian } - - let txtType = plaintext[timestampSize] - - // Extract message text, trimming null padding + let txtType = plaintext[plaintext.startIndex + timestampSize] let messageData = plaintext.dropFirst(plaintextHeaderSize) let trimmedData = messageData.prefix(while: { $0 != 0 }) - guard let text = String(data: Data(trimmedData), encoding: .utf8) else { return .decryptFailed } - return .success(timestamp: timestamp, txtType: txtType, text: text) } diff --git a/MeshCore/Tests/MeshCoreTests/ChannelCryptoTests.swift b/MeshCore/Tests/MeshCoreTests/ChannelCryptoTests.swift index 9e04884f23..419016e71f 100644 --- a/MeshCore/Tests/MeshCoreTests/ChannelCryptoTests.swift +++ b/MeshCore/Tests/MeshCoreTests/ChannelCryptoTests.swift @@ -356,4 +356,49 @@ struct ChannelCryptoTests { Issue.record("Expected success for 32-byte secret") } } + + @Test + func `group datagram plaintext returns the data type and data field`() { + let blob = Data([0x13, 0x01, 0xAA, 0x02]) + guard let payload = createEncryptedDatagram(dataType: 0x0120, data: blob, secret: testSecret) else { + Issue.record("Failed to create datagram payload") + return + } + + guard case let .success(plaintext) = ChannelCrypto.decryptPlaintext(payload: payload, secret: testSecret) else { + Issue.record("Expected plaintext") + return + } + let datagram = ChannelCrypto.readGroupDatagram(plaintext) + #expect(datagram?.dataType == 0x0120) + #expect(datagram?.data == blob) + } + + @Test + func `group datagram reader rejects a short plaintext`() { + #expect(ChannelCrypto.readGroupDatagram(Data([0x20, 0x01])) == nil) + } + + @Test + func `group datagram reader rejects a length past the plaintext`() { + var plaintext = Data(count: 16) + plaintext[0] = 0x20 + plaintext[1] = 0x01 + plaintext[2] = 14 + #expect(ChannelCrypto.readGroupDatagram(plaintext) == nil) + } + + private func createEncryptedDatagram(dataType: UInt16, data: Data, secret: Data) -> Data? { + var plaintext = Data() + var type = dataType.littleEndian + plaintext.append(Data(bytes: &type, count: 2)) + plaintext.append(UInt8(data.count)) + plaintext.append(data) + return createEncryptedRawPlaintext(plaintext, secret: secret) + } + + private func createEncryptedRawPlaintext(_ plaintext: Data, secret: Data) -> Data? { + guard let ciphertext = encryptAES128ECB(plaintext: plaintext, key: secret) else { return nil } + return computeMAC(data: ciphertext, key: secret) + ciphertext + } } From 6cbc9f8a5936783ba15a4d4d3e2964674975db23 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:39:49 -0800 Subject: [PATCH 08/13] fix: address MCOimg review findings - Show "Pixel drawing" instead of im4 text in notifications, the chat list, and VoiceOver - Hide the sent-time rows in Message Info for a channel image with no wire time - Send channel drawings as im3 group text on radios below firmware v11, which can't send group data - Match duplicate channel images only within five minutes, so a later identical drawing is no longer merged into an old row - Stamp send time on channel data so echoes of a delayed send still match - Bound channel and RX-log lookups by that window instead of scanning the whole channel - Treat text like "im2: on my way" as plain text unless the rest is Base91 - Draw raster images as one bitmap instead of one fill per pixel - Name palette colors and pixel colors for VoiceOver, and say that the channel size limit counts the node name - Restore the ChannelMessageEnvelope comment and fix the copy-matching rule in Reactions.md --- MC1/Resources/Generated/L10n.swift | 32 +++++++-- .../Localization/de.lproj/Chats.strings | 32 +++++++-- .../Localization/en.lproj/Chats.strings | 34 ++++++++-- .../Localization/es.lproj/Chats.strings | 32 +++++++-- .../Localization/fr.lproj/Chats.strings | 32 +++++++-- .../Localization/it.lproj/Chats.strings | 32 +++++++-- .../Localization/ko.lproj/Chats.strings | 32 +++++++-- .../Localization/nl.lproj/Chats.strings | 32 +++++++-- .../Localization/pl.lproj/Chats.strings | 32 +++++++-- .../Localization/pt.lproj/Chats.strings | 32 +++++++-- .../Localization/ru.lproj/Chats.strings | 32 +++++++-- .../Localization/uk.lproj/Chats.strings | 32 +++++++-- .../Localization/zh-Hans.lproj/Chats.strings | 32 +++++++-- .../Chats/ChatConversationInputBar.swift | 6 +- MC1/Views/Chats/MCOimg/MCOImageRenderer.swift | 45 +++++++++++-- MC1/Views/Chats/MCOimg/PixelPaintDraft.swift | 36 ++++------ MC1/Views/Chats/MCOimg/PixelPaintEditor.swift | 14 +++- .../Chats/MCOimg/PixelPaintTransport.swift | 43 ++++++++++++ .../Sections/ActionsDetailsSection.swift | 22 +++--- .../ChatMessageBakeState+ItemBuild.swift | 6 +- .../ChatViewModel+ConversationList.swift | 1 + .../Models/ChannelMessageEnvelope.swift | 11 ++- .../Sources/MC1Services/Models/Device.swift | 6 ++ .../Persistence/HeardRepeatPersisting.swift | 5 +- .../Persistence/RxLogPersisting.swift | 8 ++- .../MC1Services/ServiceContainer.swift | 3 +- .../ChatSendQueueService+ChannelDrain.swift | 2 +- .../Services/ChatSendQueueService.swift | 4 +- .../Services/HeardRepeatsService.swift | 12 +++- .../Services/MessageDTO+MCOImage.swift | 11 ++- .../Services/MessageService+MCOImage.swift | 39 ++++++++--- .../Services/MessageService+SendChannel.swift | 9 +++ .../Services/NotificationService.swift | 16 ++++- .../PersistenceStore+BackupBatchInsert.swift | 12 ++-- .../PersistenceStore+Diagnostics.swift | 8 ++- .../Services/PersistenceStore+Messages.swift | 18 ++++- .../Services/ReactionService.swift | 12 +++- .../RxLogService+RegionResolution.swift | 7 +- .../SyncCoordinator+MessageHandlers.swift | 19 ++++-- .../Utilities/MCOImageTransport.swift | 27 ++++++++ .../Utilities/MCOimg/MCOImageBase91.swift | 5 ++ .../Utilities/MCOimg/MCOImageCodec.swift | 12 +++- .../Utilities/MCOimg/MCOImageWireBudget.swift | 2 +- .../BackupIntegrationTests.swift | 44 +++++++++++- .../MCOImageBinarySendTests.swift | 67 ++++++++++++++++--- .../MCOImageReceiveIntegrationTests.swift | 23 +++++-- .../MCOImageSendIntegrationTests.swift | 4 +- .../MECPNotificationTests.swift | 7 ++ .../Services/ChatSendQueueServiceTests.swift | 2 +- .../Services/HeardRepeatsServiceTests.swift | 8 ++- .../Views/Chats/MCOImageMessageTests.swift | 2 +- .../Views/Chats/PixelPaintDraftTests.swift | 29 +++++++- .../Chats/PixelPaintPresentationTests.swift | 8 +-- .../MeshCore/Protocol/PacketBuilder.swift | 2 +- docs/Reactions.md | 2 +- 55 files changed, 861 insertions(+), 176 deletions(-) create mode 100644 MC1/Views/Chats/MCOimg/PixelPaintTransport.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index 79536e40fc..ae613290e0 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -563,20 +563,16 @@ public enum L10n { public static let canvas = L10n.tr("Chats", "chats.mcoimg.canvas", fallback: "Pixel canvas") /// Erases every pixel in the editor public static let clear = L10n.tr("Chats", "chats.mcoimg.clear", fallback: "Clear Drawing") - /// VoiceOver name for a palette swatch; the argument is 1-based - public static func color(_ p1: Int) -> String { - return L10n.tr("Chats", "chats.mcoimg.color", p1, fallback: "Color %d") - } /// Placeholder when an MCOimg payload cannot be decoded public static let damaged = L10n.tr("Chats", "chats.mcoimg.damaged", fallback: "Damaged image") /// Progress label while a pixel drawing is encoded - public static let encoding = L10n.tr("Chats", "chats.mcoimg.encoding", fallback: "Encoding Drawing") + public static let encoding = L10n.tr("Chats", "chats.mcoimg.encoding", fallback: "Encoding drawing") /// Error when a pixel drawing cannot be encoded public static let encodingFailed = L10n.tr("Chats", "chats.mcoimg.encodingFailed", fallback: "Unable to encode the drawing.") /// Alert title when a pixel drawing cannot be encoded public static let encodingFailedTitle = L10n.tr("Chats", "chats.mcoimg.encodingFailedTitle", fallback: "Unable to Encode") - /// VoiceOver name for a rendered MCOimg - public static let image = L10n.tr("Chats", "chats.mcoimg.image", fallback: "MCOimg image") + /// Name for an MCOimg in VoiceOver, notifications, and the chat list + public static let image = L10n.tr("Chats", "chats.mcoimg.image", fallback: "Pixel drawing") /// VoiceOver name for one cell; arguments are 1-based column and row public static func pixel(_ p1: Int, _ p2: Int) -> String { return L10n.tr("Chats", "chats.mcoimg.pixel", p1, p2, fallback: "Pixel %d, %d") @@ -591,10 +587,32 @@ public enum L10n { public static func tooLarge(_ p1: Int, _ p2: Int) -> String { return L10n.tr("Chats", "chats.mcoimg.tooLarge", p1, p2, fallback: "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again.") } + /// Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit + public static func tooLargeChannel(_ p1: Int, _ p2: Int) -> String { + return L10n.tr("Chats", "chats.mcoimg.tooLargeChannel", p1, p2, fallback: "Drawing is %d bytes, including your node name; this channel allows %d. Simplify the drawing and try again.") + } /// Alert title when a pixel drawing exceeds the conversation limit public static let tooLargeTitle = L10n.tr("Chats", "chats.mcoimg.tooLargeTitle", fallback: "Drawing Too Large") /// Placeholder when an MCOimg version cannot be shown public static let unsupported = L10n.tr("Chats", "chats.mcoimg.unsupported", fallback: "Unsupported image format") + public enum ColorName { + /// VoiceOver name for a Pixel Paint palette color + public static let black = L10n.tr("Chats", "chats.mcoimg.colorName.black", fallback: "Black") + /// VoiceOver name for a Pixel Paint palette color + public static let blue = L10n.tr("Chats", "chats.mcoimg.colorName.blue", fallback: "Blue") + /// VoiceOver name for a Pixel Paint palette color + public static let gray = L10n.tr("Chats", "chats.mcoimg.colorName.gray", fallback: "Gray") + /// VoiceOver name for a Pixel Paint palette color + public static let green = L10n.tr("Chats", "chats.mcoimg.colorName.green", fallback: "Green") + /// VoiceOver name for a Pixel Paint palette color + public static let purple = L10n.tr("Chats", "chats.mcoimg.colorName.purple", fallback: "Purple") + /// VoiceOver name for a Pixel Paint palette color + public static let red = L10n.tr("Chats", "chats.mcoimg.colorName.red", fallback: "Red") + /// VoiceOver name for a Pixel Paint palette color + public static let white = L10n.tr("Chats", "chats.mcoimg.colorName.white", fallback: "White") + /// VoiceOver name for a Pixel Paint palette color + public static let yellow = L10n.tr("Chats", "chats.mcoimg.colorName.yellow", fallback: "Yellow") + } } public enum Mention { public enum Accessibility { diff --git a/MC1/Resources/Localization/de.lproj/Chats.strings b/MC1/Resources/Localization/de.lproj/Chats.strings index 69fd8c27b8..4e5a26bcb2 100644 --- a/MC1/Resources/Localization/de.lproj/Chats.strings +++ b/MC1/Resources/Localization/de.lproj/Chats.strings @@ -1070,8 +1070,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Beschädigtes Bild"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg Bild"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Pixelzeichnung"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Zeichnung löschen"; @@ -1079,8 +1079,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Senden"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Farbe %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Weiß"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Grau"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Schwarz"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Rot"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Gelb"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Grün"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Blau"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Lila"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Pixel-Leinwand"; @@ -1094,6 +1115,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "Die Zeichnung ist %d Bytes groß; diese Unterhaltung erlaubt %d Bytes. Vereinfache die Zeichnung und versuche es erneut."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "Die Zeichnung ist einschließlich deines Knotennamens %d Bytes groß; dieser Kanal erlaubt %d Bytes. Vereinfache die Zeichnung und versuche es erneut."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Kodieren nicht möglich"; diff --git a/MC1/Resources/Localization/en.lproj/Chats.strings b/MC1/Resources/Localization/en.lproj/Chats.strings index bcae40210f..2a474ac609 100644 --- a/MC1/Resources/Localization/en.lproj/Chats.strings +++ b/MC1/Resources/Localization/en.lproj/Chats.strings @@ -1080,8 +1080,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Damaged image"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg image"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Pixel drawing"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Clear Drawing"; @@ -1089,8 +1089,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Send"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "White"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Gray"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Black"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Red"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Yellow"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Green"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Blue"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Purple"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Pixel canvas"; @@ -1104,6 +1125,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "Drawing is %d bytes; this conversation allows %d. Simplify the drawing and try again."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "Drawing is %d bytes, including your node name; this channel allows %d. Simplify the drawing and try again."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Unable to Encode"; @@ -1111,7 +1135,7 @@ "chats.mcoimg.encodingFailed" = "Unable to encode the drawing."; /* Progress label while a pixel drawing is encoded */ -"chats.mcoimg.encoding" = "Encoding Drawing"; +"chats.mcoimg.encoding" = "Encoding drawing"; /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Sending drawing"; diff --git a/MC1/Resources/Localization/es.lproj/Chats.strings b/MC1/Resources/Localization/es.lproj/Chats.strings index 281273c9d6..ade7c9697b 100644 --- a/MC1/Resources/Localization/es.lproj/Chats.strings +++ b/MC1/Resources/Localization/es.lproj/Chats.strings @@ -1070,8 +1070,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Imagen dañada"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "Imagen MCOimg"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Dibujo de píxeles"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Borrar dibujo"; @@ -1079,8 +1079,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Enviar"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Color %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Blanco"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Gris"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Negro"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Rojo"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Amarillo"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Verde"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Azul"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Morado"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Lienzo de píxeles"; @@ -1094,6 +1115,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "El dibujo es de %d bytes; esta conversación permite %d. Simplifica el dibujo e inténtalo de nuevo."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "El dibujo ocupa %d bytes, incluido el nombre de tu nodo; este canal permite %d. Simplifica el dibujo e inténtalo de nuevo."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "No se puede codificar"; diff --git a/MC1/Resources/Localization/fr.lproj/Chats.strings b/MC1/Resources/Localization/fr.lproj/Chats.strings index 19bffaed81..a507ad16f3 100644 --- a/MC1/Resources/Localization/fr.lproj/Chats.strings +++ b/MC1/Resources/Localization/fr.lproj/Chats.strings @@ -1070,8 +1070,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Image endommagée"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "Image MCOimg"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Dessin pixel"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Effacer le dessin"; @@ -1079,8 +1079,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Envoyer"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Couleur %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Blanc"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Gris"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Noir"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Rouge"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Jaune"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Vert"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Bleu"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Violet"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Canevas de pixels"; @@ -1094,6 +1115,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "Le dessin fait %d octets ; cette conversation en autorise %d. Simplifiez le dessin et réessayez."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "Le dessin fait %d octets, nom du nœud compris ; ce canal autorise %d. Simplifiez le dessin et réessayez."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Encodage impossible"; diff --git a/MC1/Resources/Localization/it.lproj/Chats.strings b/MC1/Resources/Localization/it.lproj/Chats.strings index 79bdd33e9b..456ac59f6a 100644 --- a/MC1/Resources/Localization/it.lproj/Chats.strings +++ b/MC1/Resources/Localization/it.lproj/Chats.strings @@ -1063,8 +1063,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Immagine danneggiata"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "Immagine MCOimg"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Disegno a pixel"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Cancella disegno"; @@ -1072,8 +1072,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Invia"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Colore %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Bianco"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Grigio"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Nero"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Rosso"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Giallo"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Verde"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Blu"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Viola"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Area di disegno a pixel"; @@ -1087,6 +1108,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "Il disegno è di %d byte; questa conversazione consente %d byte. Semplifica il disegno e riprova."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "Il disegno occupa %d byte, incluso il nome del tuo nodo; questo canale ne consente %d. Semplifica il disegno e riprova."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Impossibile codificare"; diff --git a/MC1/Resources/Localization/ko.lproj/Chats.strings b/MC1/Resources/Localization/ko.lproj/Chats.strings index cc65212488..7b1da445a2 100644 --- a/MC1/Resources/Localization/ko.lproj/Chats.strings +++ b/MC1/Resources/Localization/ko.lproj/Chats.strings @@ -1063,8 +1063,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "손상된 이미지"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg 이미지"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "픽셀 그림"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "그림 지우기"; @@ -1072,8 +1072,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "보내기"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "색상 %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "흰색"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "회색"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "검은색"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "빨간색"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "노란색"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "초록색"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "파란색"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "보라색"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "픽셀 캔버스"; @@ -1087,6 +1108,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "그림이 %d바이트입니다. 이 대화는 %d바이트까지 허용합니다. 그림을 단순화한 후 다시 시도하십시오."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "그림 크기는 노드 이름을 포함해 %d바이트이며, 이 채널은 %d바이트까지 허용합니다. 그림을 단순하게 만든 후 다시 시도하세요."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "인코딩할 수 없음"; diff --git a/MC1/Resources/Localization/nl.lproj/Chats.strings b/MC1/Resources/Localization/nl.lproj/Chats.strings index 0b1ec29e99..973478c473 100644 --- a/MC1/Resources/Localization/nl.lproj/Chats.strings +++ b/MC1/Resources/Localization/nl.lproj/Chats.strings @@ -1070,8 +1070,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Beschadigde afbeelding"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg-afbeelding"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Pixeltekening"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Tekening wissen"; @@ -1079,8 +1079,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Verzenden"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Kleur %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Wit"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Grijs"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Zwart"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Rood"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Geel"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Groen"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Blauw"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Paars"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Pixelcanvas"; @@ -1094,6 +1115,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "De tekening is %d bytes; dit gesprek staat %d toe. Vereenvoudig de tekening en probeer het opnieuw."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "De tekening is %d bytes, inclusief je nodenaam; dit kanaal staat %d toe. Vereenvoudig de tekening en probeer het opnieuw."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Kan niet coderen"; diff --git a/MC1/Resources/Localization/pl.lproj/Chats.strings b/MC1/Resources/Localization/pl.lproj/Chats.strings index 51d84400e0..8101733fd1 100644 --- a/MC1/Resources/Localization/pl.lproj/Chats.strings +++ b/MC1/Resources/Localization/pl.lproj/Chats.strings @@ -1062,8 +1062,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Uszkodzony obraz"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "Obraz MCOimg"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Rysunek pikselowy"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Wyczyść rysunek"; @@ -1071,8 +1071,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Wyślij"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Kolor %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Biały"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Szary"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Czarny"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Czerwony"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Żółty"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Zielony"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Niebieski"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Fioletowy"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Płótno pikseli"; @@ -1086,6 +1107,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "Rysunek ma %d bajtów; ta rozmowa pozwala na %d. Uprość rysunek i spróbuj ponownie."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "Rysunek ma %d bajtów, wliczając nazwę węzła; ten kanał pozwala na %d. Uprość rysunek i spróbuj ponownie."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Nie można zakodować"; diff --git a/MC1/Resources/Localization/pt.lproj/Chats.strings b/MC1/Resources/Localization/pt.lproj/Chats.strings index df2de4c7d1..8a48344818 100644 --- a/MC1/Resources/Localization/pt.lproj/Chats.strings +++ b/MC1/Resources/Localization/pt.lproj/Chats.strings @@ -1063,8 +1063,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Imagem danificada"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "Imagem MCOimg"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Desenho de píxeis"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Limpar desenho"; @@ -1072,8 +1072,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Enviar"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Cor %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Branco"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Cinzento"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Preto"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Vermelho"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Amarelo"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Verde"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Azul"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Roxo"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Área de píxeis"; @@ -1087,6 +1108,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "O desenho tem %d bytes; esta conversa permite %d. Simplifique o desenho e tente novamente."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "O desenho tem %d bytes, incluindo o nome do seu nó; este canal permite %d. Simplifique o desenho e tente novamente."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Não foi possível codificar"; diff --git a/MC1/Resources/Localization/ru.lproj/Chats.strings b/MC1/Resources/Localization/ru.lproj/Chats.strings index e86154dddd..c32d5164bc 100644 --- a/MC1/Resources/Localization/ru.lproj/Chats.strings +++ b/MC1/Resources/Localization/ru.lproj/Chats.strings @@ -1061,8 +1061,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Повреждённое изображение"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "Изображение MCOimg"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Пиксельный рисунок"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Очистить рисунок"; @@ -1070,8 +1070,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Отправить"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Цвет %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Белый"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Серый"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Чёрный"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Красный"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Жёлтый"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Зелёный"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Синий"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Фиолетовый"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Пиксельный холст"; @@ -1085,6 +1106,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "Рисунок — %d байт; этот разговор допускает %d. Упрости рисунок и попробуй снова."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "Рисунок занимает %d байт вместе с именем узла; этот канал допускает %d. Упростите рисунок и попробуйте снова."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Не удалось закодировать"; diff --git a/MC1/Resources/Localization/uk.lproj/Chats.strings b/MC1/Resources/Localization/uk.lproj/Chats.strings index 96ba0f1f01..dfeb8d8c00 100644 --- a/MC1/Resources/Localization/uk.lproj/Chats.strings +++ b/MC1/Resources/Localization/uk.lproj/Chats.strings @@ -1061,8 +1061,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "Пошкоджене зображення"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "Зображення MCOimg"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Піксельний малюнок"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "Очистити малюнок"; @@ -1070,8 +1070,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "Надіслати"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "Колір %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "Білий"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "Сірий"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "Чорний"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "Червоний"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "Жовтий"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "Зелений"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "Синій"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "Фіолетовий"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Піксельне полотно"; @@ -1085,6 +1106,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "Малюнок займає %d байт; ця розмова дозволяє %d. Спрости малюнок і спробуй ще раз."; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "Малюнок має %d байтів разом з назвою вузла; цей канал дозволяє %d. Спростіть малюнок і спробуйте ще раз."; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "Не вдалося закодувати"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings index f4f0f02f71..6fb88cc3c4 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings @@ -1127,8 +1127,8 @@ /* Placeholder when an MCOimg payload cannot be decoded */ "chats.mcoimg.damaged" = "图片已损坏"; -/* VoiceOver name for a rendered MCOimg */ -"chats.mcoimg.image" = "MCOimg 图片"; +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "像素画"; /* Erases every pixel in the editor */ "chats.mcoimg.clear" = "清除绘图"; @@ -1136,8 +1136,29 @@ /* Sends the open pixel drawing */ "chats.mcoimg.send" = "发送"; -/* VoiceOver name for a palette swatch; the argument is 1-based */ -"chats.mcoimg.color" = "颜色 %d"; +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.white" = "白色"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.gray" = "灰色"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.black" = "黑色"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.red" = "红色"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.yellow" = "黄色"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.green" = "绿色"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.blue" = "蓝色"; + +/* VoiceOver name for a Pixel Paint palette color */ +"chats.mcoimg.colorName.purple" = "紫色"; /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "像素画布"; @@ -1151,6 +1172,9 @@ /* Error when a pixel drawing exceeds the conversation limit; arguments are size then limit */ "chats.mcoimg.tooLarge" = "绘图为 %d 字节,此对话允许 %d 字节。请简化绘图并重试。"; +/* Error when a channel pixel drawing exceeds the limit; the size counts the sender node name; arguments are size then limit */ +"chats.mcoimg.tooLargeChannel" = "绘图大小为 %d 字节(含节点名称);此频道最多允许 %d 字节。请简化绘图后重试。"; + /* Alert title when a pixel drawing cannot be encoded */ "chats.mcoimg.encodingFailedTitle" = "无法编码"; diff --git a/MC1/Views/Chats/ChatConversationInputBar.swift b/MC1/Views/Chats/ChatConversationInputBar.swift index cccd889d18..b2c4320286 100644 --- a/MC1/Views/Chats/ChatConversationInputBar.swift +++ b/MC1/Views/Chats/ChatConversationInputBar.swift @@ -67,6 +67,10 @@ struct ChatConversationInputBar: View { private func sendDrawing() { let isChannel = if case .channel = conversationType { true } else { false } + let transport = PixelPaintTransport( + isChannel: isChannel, + supportsChannelData: appState.connectedDevice?.supportsChannelData == true + ) let radioID = conversationType.radioID let ready = { appState.connectionState == .ready && appState.connectedDevice?.radioID == radioID @@ -75,7 +79,7 @@ struct ChatConversationInputBar: View { let task = Task { await drawing.run( attempt, - isChannel: isChannel, + transport: transport, senderName: { appState.connectedDevice?.nodeName ?? "" }, isReady: ready, onSend: onSend, diff --git a/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift b/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift index f328bd1570..0756a881c2 100644 --- a/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift +++ b/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift @@ -42,15 +42,46 @@ struct MCOImageRenderer: View { blue: Double(rgb & 0xFF) / maximumComponent, opacity: 1) } + private static let bitsPerComponent = 8 + private static let bytesPerPixel = 4 + private static let opaqueAlpha: UInt8 = 0xFF + + /// Draws the raster as one bitmap without interpolation, so pixels stay sharp at any scale. static func raster(_ image: MCOImageRaster, origin: CGPoint, context: inout GraphicsContext) { - for row in 0.. CGImage? { + guard image.width > 0, image.height > 0, image.pixels.count == image.width * image.height else { return nil } + var bytes = [UInt8](repeating: 0, count: image.pixels.count * bytesPerPixel) + for (index, reference) in image.pixels.enumerated() where reference != image.transparentColor { + let rgb = MCOImagePalette.color(reference, profile: image.profile) + let offset = index * bytesPerPixel + bytes[offset] = UInt8((rgb >> 16) & 0xFF) + bytes[offset + 1] = UInt8((rgb >> 8) & 0xFF) + bytes[offset + 2] = UInt8(rgb & 0xFF) + bytes[offset + 3] = opaqueAlpha } + guard let provider = CGDataProvider(data: Data(bytes) as CFData), + let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil } + return CGImage( + width: image.width, + height: image.height, + bitsPerComponent: bitsPerComponent, + bitsPerPixel: bitsPerComponent * bytesPerPixel, + bytesPerRow: image.width * bytesPerPixel, + space: colorSpace, + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue), + provider: provider, + decode: nil, + shouldInterpolate: false, + intent: .defaultIntent + ) } static func figure(_ figure: MCOImageFigure, profile: Int, canvasWidth: Int, context: inout GraphicsContext) { diff --git a/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift b/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift index 3a2dd9cf78..5d03400b0e 100644 --- a/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift +++ b/MC1/Views/Chats/MCOimg/PixelPaintDraft.swift @@ -88,18 +88,18 @@ final class PixelPaintDraft { /// Encodes `attempt` and admits it only while that generation is still current. func run( _ attempt: Attempt, - isChannel: Bool, + transport: PixelPaintTransport, senderName: @escaping () -> String, isReady: @escaping () -> Bool, onSend: @escaping (String) async -> Bool, onWillSend: @escaping () -> Void, onAdmitted: @escaping () -> Void, - encode: @escaping @Sendable (MCOImageRaster, Bool) async throws -> String = encodePixelDrawing + encode: @escaping @Sendable (MCOImageRaster, PixelPaintTransport) async throws -> String = encodePixelDrawing ) async { guard isCurrent(attempt.generation) else { return } let result = await outcome( snapshot: attempt.snapshot, - isChannel: isChannel, + transport: transport, generation: attempt.generation, senderName: senderName, isReady: isReady, @@ -117,17 +117,17 @@ final class PixelPaintDraft { private func outcome( snapshot: MCOImageRaster, - isChannel: Bool, + transport: PixelPaintTransport, generation: UInt, senderName: @escaping () -> String, isReady: @escaping () -> Bool, onSend: @escaping (String) async -> Bool, onWillSend: @escaping () -> Void, - encode: @escaping @Sendable (MCOImageRaster, Bool) async throws -> String + encode: @escaping @Sendable (MCOImageRaster, PixelPaintTransport) async throws -> String ) async -> SubmissionResult { let text: String do { - text = try await encode(snapshot, isChannel) + text = try await encode(snapshot, transport) } catch is CancellationError { return .retired } catch { @@ -141,17 +141,19 @@ final class PixelPaintDraft { } let bytes: Int do { - bytes = try Self.encodedByteCount(text: text, isChannel: isChannel, senderName: senderName()) + bytes = try transport.encodedByteCount(text: text, senderName: senderName()) } catch { guard isCurrent(generation) else { return .retired } return Self.encodeFailed } guard isCurrent(generation) else { return .retired } - let limit = Self.byteLimit(isChannel: isChannel) + let limit = transport.byteLimit guard bytes <= limit else { return .failed( title: L10n.Chats.Chats.Mcoimg.tooLargeTitle, - message: L10n.Chats.Chats.Mcoimg.tooLarge(bytes, limit) + message: transport.isChannel + ? L10n.Chats.Chats.Mcoimg.tooLargeChannel(bytes, limit) + : L10n.Chats.Chats.Mcoimg.tooLarge(bytes, limit) ) } guard isCurrent(generation) else { return .retired } @@ -191,18 +193,6 @@ final class PixelPaintDraft { submissionGeneration == generation && !Task.isCancelled } - private static func encodedByteCount(text: String, isChannel: Bool, senderName: String) throws -> Int { - if isChannel { - try MCOImageTransport.encode(text: text, senderName: senderName).count - } else { - text.utf8.count - } - } - - private static func byteLimit(isChannel: Bool) -> Int { - isChannel ? MCOImageWireBudget.maximumChannelDataBytes : ProtocolLimits.maxDirectMessageLength - } - private static var unableToSend: SubmissionResult { .failed( title: L10n.Chats.Chats.Alert.UnableToSend.title, @@ -226,9 +216,9 @@ final class PixelPaintDraft { } @concurrent -func encodePixelDrawing(_ image: MCOImageRaster, channel: Bool) async throws -> String { +func encodePixelDrawing(_ image: MCOImageRaster, transport: PixelPaintTransport) async throws -> String { let body = try MCOImageV3Codec.encode(image, nonce: UInt8.random(in: .min ... .max)) - let payload = channel + let payload = transport == .channelData ? try Data([MCOImageCodec.v4Subtype]) + MCOImageV4Codec.wrappingV3Body(body) : Data([MCOImageCodec.v3Subtype]) + body return try MCOImageCodec.text(fromAppPayload: payload) diff --git a/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift b/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift index e0be396174..94fe764308 100644 --- a/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift +++ b/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift @@ -12,6 +12,17 @@ struct PixelPaintEditor: View { private static let contentSpacing: CGFloat = 24 private static let paletteColumns = 4 private static let swatchPadding: CGFloat = 4 + /// Spoken names in `PixelPaintDraft.profile` palette order. + private static let colorNames = [ + L10n.Chats.Chats.Mcoimg.ColorName.white, L10n.Chats.Chats.Mcoimg.ColorName.gray, + L10n.Chats.Chats.Mcoimg.ColorName.black, L10n.Chats.Chats.Mcoimg.ColorName.red, + L10n.Chats.Chats.Mcoimg.ColorName.yellow, L10n.Chats.Chats.Mcoimg.ColorName.green, + L10n.Chats.Chats.Mcoimg.ColorName.blue, L10n.Chats.Chats.Mcoimg.ColorName.purple, + ] + + private static func colorName(_ index: Int) -> String { + colorNames.indices.contains(index) ? colorNames[index] : "" + } var body: some View { NavigationStack { @@ -36,7 +47,7 @@ struct PixelPaintEditor: View { .padding(Self.swatchPadding) } .buttonStyle(.plain) - .accessibilityLabel(L10n.Chats.Chats.Mcoimg.color(index + 1)) + .accessibilityLabel(Self.colorName(index)) .accessibilityAddTraits(index == draft.selectedColor ? .isSelected : []) .accessibilityIdentifier("pixelColor\(index)") } @@ -141,6 +152,7 @@ struct PixelPaintEditor: View { draft.paint(x: column, y: row) draft.endStroke() } + .accessibilityValue(Self.colorName(draft.pixels[row * PixelPaintDraft.side + column])) } } } diff --git a/MC1/Views/Chats/MCOimg/PixelPaintTransport.swift b/MC1/Views/Chats/MCOimg/PixelPaintTransport.swift new file mode 100644 index 0000000000..1dfe2bd09d --- /dev/null +++ b/MC1/Views/Chats/MCOimg/PixelPaintTransport.swift @@ -0,0 +1,43 @@ +import MC1Services + +/// How a Pixel Paint drawing leaves the radio. It picks the text version and the byte budget. +nonisolated enum PixelPaintTransport: Sendable { + /// `im3:` in a direct message. + case direct + /// `im3:` as group text, for a radio without `CMD_SEND_CHANNEL_DATA`. + case channelText + /// `im4:` as group data. + case channelData + + init(isChannel: Bool, supportsChannelData: Bool) { + if !isChannel { + self = .direct + } else { + self = supportsChannelData ? .channelData : .channelText + } + } + + var isChannel: Bool { + self != .direct + } + + /// Wire bytes counted against `byteLimit`. Channel sizes include the sender name. + func encodedByteCount(text: String, senderName: String) throws -> Int { + switch self { + case .direct: + text.utf8.count + case .channelText: + senderName.utf8.count + ProtocolLimits.channelSenderPrefixSeparatorUTF8Count + text.utf8.count + case .channelData: + try MCOImageTransport.encode(text: text, senderName: senderName).count + } + } + + var byteLimit: Int { + switch self { + case .direct: ProtocolLimits.maxDirectMessageLength + case .channelText: ProtocolLimits.maxChannelMessageTotalLength + case .channelData: MCOImageWireBudget.maximumChannelDataBytes + } + } +} diff --git a/MC1/Views/Chats/Reactions/Sections/ActionsDetailsSection.swift b/MC1/Views/Chats/Reactions/Sections/ActionsDetailsSection.swift index 0bbe5a1015..1999473451 100644 --- a/MC1/Views/Chats/Reactions/Sections/ActionsDetailsSection.swift +++ b/MC1/Views/Chats/Reactions/Sections/ActionsDetailsSection.swift @@ -111,16 +111,18 @@ private struct ActionsIncomingDetailsRows: View { ActionInfoRow(text: regionText, icon: "globe") } - let sentText = L10n.Chats.Chats.Message.Info.sent( - message.senderDate.formatted(date: .abbreviated, time: .standard) - ) - let adjusted = message.timestampCorrected ? " " + L10n.Chats.Chats.Message.Info.adjusted : "" - ActionInfoRow(text: sentText + adjusted) - - if message.timestampCorrected { - ActionInfoRow(text: L10n.Chats.Chats.Message.Info.originalSendTime( - message.wireSentDate.formatted(date: .abbreviated, time: .standard) - )) + if message.hasWireSendTime { + let sentText = L10n.Chats.Chats.Message.Info.sent( + message.senderDate.formatted(date: .abbreviated, time: .standard) + ) + let adjusted = message.timestampCorrected ? " " + L10n.Chats.Chats.Message.Info.adjusted : "" + ActionInfoRow(text: sentText + adjusted) + + if message.timestampCorrected { + ActionInfoRow(text: L10n.Chats.Chats.Message.Info.originalSendTime( + message.wireSentDate.formatted(date: .abbreviated, time: .standard) + )) + } } ActionInfoRow(text: L10n.Chats.Chats.Message.Info.received( diff --git a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift index ffcaa7a582..fe54eb36fc 100644 --- a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift +++ b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift @@ -112,10 +112,12 @@ extension ChatMessageBakeState { envInputs: EnvInputs, senderTables: ChatSenderTables ) -> MessageBuildInputs { - if message.mcoImage == nil { + // A prefix check, not a decode: the fragment builder decodes the picture once. + let isMCOImage = MCOImageCodec.isMCOImageText(message.text) + if !isMCOImage { seedPreviewStateIfNeeded(for: message, envInputs: envInputs) } - if envInputs.translationOffersEnabled, message.mcoImage == nil { + if envInputs.translationOffersEnabled, !isMCOImage { seedDetectedLanguageIfNeeded(for: message) } let flags = Self.computeDisplayFlags(for: message, previous: previous, next: next) diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationList.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationList.swift index b1d10f065b..d03b1f6d2e 100644 --- a/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationList.swift +++ b/MC1/Views/Chats/ViewModel/ChatViewModel+ConversationList.swift @@ -366,6 +366,7 @@ extension ChatViewModel { /// Get the cached last-message preview text for a conversation, keyed by its id. func lastMessagePreview(id: UUID) -> String? { guard let text = lastMessageCache[id]?.text else { return nil } + if MCOImageCodec.isMCOImageText(text) { return L10n.Chats.Chats.Mcoimg.image } return MECPCatalog.displayText(text) } diff --git a/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift b/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift index 44341cb0ee..2b9c8a22b4 100644 --- a/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift +++ b/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift @@ -1,7 +1,14 @@ import Foundation -/// `isResend` selects a fresh text timestamp; an MCOimg nonce is already in the captured text, so drain does not mint one. -/// Captured `messageText`, `messageTimestamp`, and `localNodeName` keep reaction indexing off a later channel or radio name. +/// Channel-message envelope for `SendQueue`. +/// +/// `isResend` is load-bearing: a resend calls `MessageService.resendChannelMessage`, which +/// stamps a fresh timestamp so the mesh dedup ring (128 cyclic slots) does not silently drop +/// the retry. A fresh send calls `sendPendingChannelMessage`, which keeps the original +/// timestamp. An MCOimg resend already carries a fresh nonce in the captured text. +/// +/// `messageText`, `messageTimestamp`, and `localNodeName` are captured at enqueue time so +/// post-send reaction indexing does not read a later channel selection or device name. public struct ChannelMessageEnvelope: Sendable { public let messageID: UUID public let channelIndex: UInt8 diff --git a/MC1Services/Sources/MC1Services/Models/Device.swift b/MC1Services/Sources/MC1Services/Models/Device.swift index 0d059a297f..ef502240a0 100644 --- a/MC1Services/Sources/MC1Services/Models/Device.swift +++ b/MC1Services/Sources/MC1Services/Models/Device.swift @@ -448,10 +448,16 @@ public struct DeviceDTO: Sendable, Equatable, Identifiable, Codable { } private static let autoAddConfigMinimumFirmwareVersion: UInt8 = 9 + private static let channelDataMinimumFirmwareVersion: UInt8 = 11 private static let autoAddMaxHopsMinimumFirmwareVersion: UInt8 = 10 /// Whether the device supports auto-add configuration beyond the manualAddContacts toggle. /// Code 8 covers 1.10 through 1.12, so a 1.12 version string still counts before code 9. + /// `CMD_SEND_CHANNEL_DATA` (MeshCore 1.15.0). Older radios send a channel MCOimg as group text. + public var supportsChannelData: Bool { + firmwareVersion >= Self.channelDataMinimumFirmwareVersion + } + public var supportsAutoAddConfig: Bool { firmwareVersion >= Self.autoAddConfigMinimumFirmwareVersion || firmwareVersionString.isAtLeast(major: 1, minor: 12) diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift index b28f2eefe9..923b4d85bc 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift @@ -11,7 +11,8 @@ public protocol HeardRepeatPersisting: Actor { func fetchMessage(deduplicationKey: String, radioID: UUID) async throws -> MessageDTO? /// Every message on one radio and channel. Datagram path matching filters this set in memory. - func fetchChannelMessages(radioID: UUID, channelIndex: UInt8) async throws -> [MessageDTO] + /// Channel rows whose `timestamp` falls in `timestampWindow`, for datagram identity matching. + func fetchChannelMessages(radioID: UUID, channelIndex: UInt8, timestampWindow: ClosedRange) async throws -> [MessageDTO] /// Save a message repeat entry func saveMessageRepeat(_ dto: MessageRepeatDTO) async throws @@ -78,7 +79,7 @@ public protocol HeardRepeatPersisting: Actor { } extension HeardRepeatPersisting { - func fetchChannelMessages(radioID: UUID, channelIndex: UInt8) async throws -> [MessageDTO] { + func fetchChannelMessages(radioID: UUID, channelIndex: UInt8, timestampWindow: ClosedRange) async throws -> [MessageDTO] { [] } diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift index 8667216f2f..cb7970b1e0 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift @@ -42,11 +42,12 @@ public protocol RxLogPersisting: Actor { senderTimestamp: UInt32 ) async throws -> [RxLogEntryDTO] - /// Group-datagram rows for one radio and channel. No sender timestamp. + /// Group-datagram rows for one radio and channel received inside `receivedWithin`. No sender timestamp. func fetchRxLogEntries( radioID: UUID, channelIndex: UInt8, - payloadType: PayloadType + payloadType: PayloadType, + receivedWithin: ClosedRange ) async throws -> [RxLogEntryDTO] /// Find a DM RxLogEntry by matching the sender prefix byte in the packet payload. @@ -123,7 +124,8 @@ extension RxLogPersisting { func fetchRxLogEntries( radioID: UUID, channelIndex: UInt8, - payloadType: PayloadType + payloadType: PayloadType, + receivedWithin: ClosedRange ) async throws -> [RxLogEntryDTO] { [] } diff --git a/MC1Services/Sources/MC1Services/ServiceContainer.swift b/MC1Services/Sources/MC1Services/ServiceContainer.swift index e7fedfa7e8..387839b72b 100644 --- a/MC1Services/Sources/MC1Services/ServiceContainer.swift +++ b/MC1Services/Sources/MC1Services/ServiceContainer.swift @@ -223,7 +223,8 @@ public final class ServiceContainer { let raw = await (try? store.fetchRxLogEntries( radioID: message.radioID, channelIndex: channelIndex, - payloadType: .groupData + payloadType: .groupData, + receivedWithin: MCOImageTransport.datagramReceiveWindow(around: message.timestamp) )) ?? [] let decoded = await rxLog.decodedEntries(raw) await repeats.harvestDatagramPaths(for: message, decodedCandidates: decoded) diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift index a99068686b..67f6f7ecb8 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift @@ -44,7 +44,7 @@ extension ChatSendQueueService { try cancelSendIfRetired(dependencies.sendsRetired) let capturedText = envelope.messageText - let sentDatagram = MCOImageCodec.isMCOImageText(capturedText) + let sentDatagram = MCOImageCodec.isChannelDataText(capturedText) switch try await transmitQueuedChannel(envelope: envelope, dependencies: dependencies) { case .dropped: return diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index 8e73aa5e9c..9b3ad5362a 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -286,7 +286,9 @@ public final class ChatSendQueueService { defer { finishAdmission() } let text: String if let indexed = target.mcoImageReactionTarget() { - text = "@[\(indexed.senderName)]\(emoji)\n\(indexed.messageHash)" + text = reactionService.buildReactionText( + emoji: emoji, targetSender: indexed.senderName, messageHash: indexed.messageHash + ) } else if target.isChannelMCOImage { return nil } else if target.channelIndex != nil { diff --git a/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift index 2643e90047..39ba5304c5 100644 --- a/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift +++ b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift @@ -250,7 +250,11 @@ public actor HeardRepeatsService { guard let earliest = sameField.min(by: { $0.receivedAt < $1.receivedAt }), earliest.id == entry.id else { return } do { - let messages = try await dataStore.fetchChannelMessages(radioID: entry.radioID, channelIndex: channelIndex) + let messages = try await dataStore.fetchChannelMessages( + radioID: entry.radioID, + channelIndex: channelIndex, + timestampWindow: MCOImageTransport.datagramMatchWindow(around: earliest.receivedAt) + ) for message in messages where message.datagramDataField == blob { try await dataStore.updateMessageRegion( id: message.id, @@ -313,7 +317,11 @@ public actor HeardRepeatsService { entry.radioID == radioID else { return nil } if await isDuplicateRepeat(entry.id) { return nil } do { - let messages = try await dataStore.fetchChannelMessages(radioID: radioID, channelIndex: channelIndex) + let messages = try await dataStore.fetchChannelMessages( + radioID: radioID, + channelIndex: channelIndex, + timestampWindow: MCOImageTransport.datagramMatchWindow(around: entry.receivedAt) + ) let matches = messages.filter { $0.datagramDataField == blob } var lastCount: Int? for message in matches where message.isOutgoing { diff --git a/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift index d902216e9f..4cc31672e5 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift @@ -11,18 +11,23 @@ public extension MessageDTO { /// A channel MCOimg with no packet sender timestamp. /// Incoming `senderTimestamp` nil is an accepted packet time. Zero is the datagram tuple. - /// Every outgoing channel MCOimg has no packet sender timestamp. + /// An outgoing `im4:` row went out as group data; an outgoing `im3:` row went out as group text. var isDatagramMCOImage: Bool { guard isChannelMCOImage else { return false } - if isOutgoing { return true } + if isOutgoing { return MCOImageCodec.isChannelDataText(text) } return senderTimestamp == 0 } + /// False for an incoming datagram MCOimg: the packet carries no send time, so only receipt is known. + var hasWireSendTime: Bool { + isOutgoing || !isDatagramMCOImage + } + /// Path join for a channel MCOimg. Group text keeps the content key, including wire time 0. /// Reactions use `isDatagramMCOImage`, which still includes that group-text row. var isDatagramPathMCOImage: Bool { guard isChannelMCOImage, let channelIndex else { return false } - if isOutgoing { return true } + if isOutgoing { return MCOImageCodec.isChannelDataText(text) } guard senderTimestamp == 0 else { return false } let contentKey = DeduplicationKey.contentBased( contactID: nil, diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift b/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift index 0459ae5ac6..8d86035774 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift @@ -6,18 +6,36 @@ extension MessageService { case mcoImage(Data) } - /// MCOimg bytes use the stored sender name, so a later rename does not change the payload. + /// `im4:` goes out as group data with the stored sender name, so a later rename does not + /// change the payload. Any other text, including an `im3:` picture, goes out as group text. func channelTransmission( text: String, senderNodeName: String?, radioID: UUID ) async throws -> ChannelTransmission { - if MCOImageCodec.isMCOImageText(text) { + if MCOImageCodec.isChannelDataText(text) { return try .mcoImage(channelMCOImagePayload(text, senderName: senderNodeName ?? "")) } try await rejectIfChannelTextTooLong(text, radioID: radioID) return .text(text) } + + /// Canonical channel MCOimg text for this radio: `im4:` when it can send group data, + /// otherwise the `im3:` text as group text. `im4:` has no `im3:` form, so older radios reject it. + func canonicalChannelMCOImageText(_ text: String, senderName: String, device: DeviceDTO) async throws -> String { + if device.supportsChannelData { + let canonical = try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: text)) + _ = try channelMCOImagePayload(canonical, senderName: senderName) + return canonical + } + guard !MCOImageCodec.isChannelDataText(text) else { + throw MessageServiceError.sendFailed("This image needs radio firmware 1.15 or later.") + } + guard case .raster = MCOImageCodec.content(from: text) else { throw MCOImageCodecError.damaged } + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + try await rejectIfChannelTextTooLong(trimmed, radioID: device.radioID) + return trimmed + } } public extension MessageService { @@ -25,13 +43,16 @@ public extension MessageService { func prepareMCOImageForResend(_ message: MessageDTO) async throws -> MessageDTO { guard message.mcoImage != nil else { return message } var refreshed = message - let text = message.channelIndex != nil - ? try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: message.text)) - : message.text - refreshed.text = try MCOImageCodec.refreshNonce(in: text) if message.channelIndex != nil { - _ = try channelMCOImagePayload(refreshed.text, senderName: message.senderNodeName ?? "") + guard let device = try await dataStore.fetchDevice(radioID: message.radioID) else { + throw MessageServiceError.notConnected + } + // The nonce byte keeps its size, so the canonical text's budget check still holds. + refreshed.text = try await MCOImageCodec.refreshNonce(in: canonicalChannelMCOImageText( + message.text, senderName: message.senderNodeName ?? "", device: device + )) } else { + refreshed.text = try MCOImageCodec.refreshNonce(in: message.text) guard refreshed.text.utf8.count <= ProtocolLimits.maxDirectMessageLength else { throw MessageServiceError.messageTooLong } @@ -48,12 +69,10 @@ public extension MessageService { try await rejectIfChannelTextTooLong(text, radioID: radioID) return (text, nil) } - let canonicalText = try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: text)) guard let device = try await dataStore.fetchDevice(radioID: radioID) else { throw MessageServiceError.notConnected } - _ = try channelMCOImagePayload(canonicalText, senderName: device.nodeName) - return (canonicalText, device.nodeName) + return try await (canonicalChannelMCOImageText(text, senderName: device.nodeName, device: device), device.nodeName) } internal func channelMCOImagePayload(_ text: String, senderName: String) throws -> Data { diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index 3451e5c2f9..599ce7d632 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -165,6 +165,11 @@ public extension MessageService { senderNodeName: message.senderNodeName, radioID: radioID ) + if case .mcoImage = transmission { + // Group data carries no clock, so echo matching anchors on this row's `timestamp`. + // Stamp air time, not enqueue time, so a send parked while disconnected still matches. + try await dataStore.updateMessageTimestamp(id: messageID, timestamp: UInt32(Date().timeIntervalSince1970)) + } try await withPoolBackoff(transientCode: channelPoolErrorCode(transmission), config: config.poolBackoff, logger: logger) { try await sendChannelMessageWithScope( transmission, @@ -247,6 +252,10 @@ public extension MessageService { senderNodeName: message.senderNodeName, radioID: message.radioID ) + if preserveTimestamp, case .mcoImage = transmission { + // Group data has no wire clock to preserve; anchor echo matching on air time. + try await dataStore.updateMessageTimestamp(id: messageID, timestamp: UInt32(Date().timeIntervalSince1970)) + } try await withPoolBackoff(transientCode: channelPoolErrorCode(transmission), config: config.poolBackoff, logger: logger) { try await sendChannelMessageWithScope( transmission, diff --git a/MC1Services/Sources/MC1Services/Services/NotificationService.swift b/MC1Services/Sources/MC1Services/Services/NotificationService.swift index b4f78964fc..944481454f 100644 --- a/MC1Services/Sources/MC1Services/Services/NotificationService.swift +++ b/MC1Services/Sources/MC1Services/Services/NotificationService.swift @@ -298,14 +298,26 @@ public final class NotificationService: NSObject { // MARK: - Sending Notifications + /// App `Chats` table entry that names an MCOimg, so a notification never shows Base91. + private nonisolated static let mcoImageNameKey = "chats.mcoimg.image" + private nonisolated static let mcoImageNameTable = "Chats" + private nonisolated static let mcoImageNameFallback = "Pixel drawing" + + /// Localized MCOimg name from the app bundle, or the English fallback when the table is absent. + nonisolated static func mcoImageName(bundle: Bundle = .main) -> String { + bundle.localizedString(forKey: mcoImageNameKey, value: mcoImageNameFallback, table: mcoImageNameTable) + } + /// Space-joined MECP reading, then the sender prefix. Decode runs on `messageText` - /// alone so a channel body is never parsed as `Ada: MECP/…`. + /// alone so a channel body is never parsed as `Ada: MECP/…`. An MCOimg reads as its name. nonisolated static func arrivalBody( messageText: String, senderName: String? = nil, bundle: Bundle = .main ) -> String { - let body = MECPCatalog.displayText(messageText, bundle: bundle) + let body = MCOImageCodec.isMCOImageText(messageText) + ? mcoImageName(bundle: bundle) + : MECPCatalog.displayText(messageText, bundle: bundle) if let senderName { return "\(senderName): \(body)" } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift index ca808828ed..6bf0061a2b 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -301,7 +301,8 @@ extension PersistenceStore { !secret.isEmpty && !secret.allSatisfy { $0 == 0 } } - /// Incoming MCOimg on this radio and local slot with the same data field, including one accepted earlier in this pass. + /// Incoming MCOimg on this radio and local slot with the same data field and a `timestamp` within + /// `MCOImageTransport.datagramMatchWindowSeconds`, including one accepted earlier in this pass. /// Outgoing rows stay on message id. An MCOimg that cannot rebuild a data field matches by dedup string only. private func matchingImportedIncomingPicture( _ dto: MessageDTO, @@ -319,7 +320,8 @@ extension PersistenceStore { } let stored = storedCache[cacheKey] ?? [] let acceptedHere = accepted.filter { $0.radioID == dto.radioID && $0.channelIndex == channelIndex } - return (stored + acceptedHere).first { $0.datagramDataField == blob } + let window = MCOImageTransport.datagramMatchWindow(around: dto.timestamp) + return (stored + acceptedHere).first { window.contains($0.timestamp) && $0.datagramDataField == blob } } @discardableResult @@ -350,7 +352,9 @@ extension PersistenceStore { // so reply chains survive imports where the parent already exists locally. for dto in dtos { let key = messageBackupKey(for: dto) - if knownKeys.contains(key) { + // An incoming picture's `mcoimg` key has no clock; its identity is the windowed data-field match below. + let isIncomingPicture = dto.direction == .incoming && dto.datagramDataField != nil + if !isIncomingPicture, knownKeys.contains(key) { // Deterministic tiebreak when multiple locals share a key. let winning = idsByKey[key]?.min(by: { $0.uuidString < $1.uuidString }) if let winning, winning != dto.id { @@ -387,7 +391,7 @@ extension PersistenceStore { knownKeys.insert(key) idsByKey[key, default: []].append(dto.id) toInsert.append(dto) - if dto.direction == .incoming, dto.datagramDataField != nil { + if isIncomingPicture { acceptedIncomingPictures.append(dto) } } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift index e68f05affe..6b5118e4f9 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift @@ -303,15 +303,19 @@ public extension PersistenceStore { func fetchRxLogEntries( radioID: UUID, channelIndex: UInt8, - payloadType: PayloadType + payloadType: PayloadType, + receivedWithin: ClosedRange ) async throws -> [RxLogEntryDTO] { let targetRadioID = radioID let targetChannelIndex = Int(channelIndex) let targetPayloadType = Int(payloadType.rawValue) + let earliest = receivedWithin.lowerBound + let latest = receivedWithin.upperBound let predicate = #Predicate { entry in entry.radioID == targetRadioID && entry.channelIndex == targetChannelIndex && - entry.payloadType == targetPayloadType + entry.payloadType == targetPayloadType && + entry.receivedAt >= earliest && entry.receivedAt <= latest } let descriptor = FetchDescriptor( predicate: predicate, diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index 73fd39e353..fc35b0fdec 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -850,9 +850,21 @@ public extension PersistenceStore { // MARK: - Heard Repeats - /// Every channel message for one radio, with no fetch limit, so path matching sees the whole channel. - func fetchChannelMessages(radioID: UUID, channelIndex: UInt8) async throws -> [MessageDTO] { - try storedChannelMessages(radioID: radioID, channelIndex: channelIndex) + /// Channel messages in a `timestamp` window, with no fetch limit, so every copy in the window is seen. + func fetchChannelMessages( + radioID: UUID, + channelIndex: UInt8, + timestampWindow: ClosedRange + ) async throws -> [MessageDTO] { + let targetRadioID = radioID + let targetChannelIndex: UInt8? = channelIndex + let lower = timestampWindow.lowerBound + let upper = timestampWindow.upperBound + let predicate = #Predicate { message in + message.radioID == targetRadioID && message.channelIndex == targetChannelIndex && + message.timestamp >= lower && message.timestamp <= upper + } + return try modelContext.fetch(FetchDescriptor(predicate: predicate)).map { MessageDTO(from: $0) } } func storedChannelMessages(radioID: UUID, channelIndex: UInt8) throws -> [MessageDTO] { diff --git a/MC1Services/Sources/MC1Services/Services/ReactionService.swift b/MC1Services/Sources/MC1Services/Services/ReactionService.swift index 534b19a947..9220f48a4d 100644 --- a/MC1Services/Sources/MC1Services/Services/ReactionService.swift +++ b/MC1Services/Sources/MC1Services/Services/ReactionService.swift @@ -110,8 +110,16 @@ public actor ReactionService { targetText: String, targetTimestamp: UInt32 ) -> String { - let hash = ReactionParser.generateMessageHash(text: targetText, timestamp: targetTimestamp) - return "@[\(targetSender)]\(emoji)\n\(hash)" + buildReactionText( + emoji: emoji, + targetSender: targetSender, + messageHash: ReactionParser.generateMessageHash(text: targetText, timestamp: targetTimestamp) + ) + } + + /// Channel reaction wire text for a hash the caller already computed. + public nonisolated func buildReactionText(emoji: String, targetSender: String, messageHash: String) -> String { + "@[\(targetSender)]\(emoji)\n\(messageHash)" } /// Builds DM reaction wire format (shorter, no sender) diff --git a/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift b/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift index 013f5f9913..22fd99d3b5 100644 --- a/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift +++ b/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift @@ -188,11 +188,16 @@ extension RxLogService { } if let heardRepeatsService, !datagramRegionUpdates.isEmpty { let byChannel = Dictionary(grouping: datagramRegionUpdates, by: \.channelIndex) + let receivedAtByID = Dictionary(entries.map { ($0.id, $0.receivedAt) }, uniquingKeysWith: { first, _ in first }) for (channelIndex, updates) in byChannel { + let receivedTimes = updates.compactMap { receivedAtByID[$0.id] } + guard let earliest = receivedTimes.min(), let latest = receivedTimes.max() else { continue } let raw = try await dataStore.fetchRxLogEntries( radioID: radioID, channelIndex: channelIndex, - payloadType: .groupData + payloadType: .groupData, + receivedWithin: MCOImageTransport.datagramReceiveWindow(around: earliest).lowerBound + ... MCOImageTransport.datagramReceiveWindow(around: latest).upperBound ) let decoded = decodedEntries(raw) for update in updates { diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index 935d3c2687..cfc4c0853f 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -167,7 +167,8 @@ extension SyncCoordinator { let raw = try await dependencies.dataStore.fetchRxLogEntries( radioID: messageDTO.radioID, channelIndex: channelIndex, - payloadType: .groupData + payloadType: .groupData, + receivedWithin: MCOImageTransport.datagramReceiveWindow(around: messageDTO.timestamp) ) let decoded = await dependencies.rxLogService.decodedEntries(raw) guard scope.isCurrent else { return messageDTO } @@ -205,7 +206,8 @@ extension SyncCoordinator { return true } - /// Outgoing MCOimg first, then any incoming MCOimg with the same data field. + /// Outgoing MCOimg first, then any incoming MCOimg with the same data field, among rows whose + /// `timestamp` is within `MCOImageTransport.datagramMatchWindowSeconds` of this push. /// A group-text row is not a hit. An MCOimg that cannot rebuild a data field is not a hit. private func existingDatagramPicture( _ message: MessageDTO, @@ -217,7 +219,8 @@ extension SyncCoordinator { do { let rows = try await dependencies.dataStore.fetchChannelMessages( radioID: message.radioID, - channelIndex: channelIndex + channelIndex: channelIndex, + timestampWindow: MCOImageTransport.datagramMatchWindow(around: message.timestamp) ) if let outgoing = rows.first(where: { $0.isOutgoing && $0.datagramDataField == blob }) { return outgoing @@ -412,10 +415,14 @@ extension SyncCoordinator { case .direct: !selfNodeName.isEmpty && MentionUtilities.containsSelfMention(in: text, selfName: selfNodeName) - case .channel, .mcoImage: + case .channel: + // Base91 includes `@`, `[`, and `]`, so a group-text picture is never a mention. !selfNodeName.isEmpty && senderNodeName != selfNodeName && + !MCOImageCodec.isMCOImageText(text) && MentionUtilities.containsSelfMention(in: text, selfName: selfNodeName) + case .mcoImage: + false } // Clamp an unknown wire textType to .plain. MessageDTO decodes textType @@ -507,7 +514,9 @@ extension SyncCoordinator { ) { return } - if await recordChannelArrivalAndSkipDuplicate( + // The `mcoimg` key has no clock, so a datagram picture's identity is only the windowed + // data-field match above; the key would merge a later identical drawing into an old row. + if message.datagramDataField == nil, await recordChannelArrivalAndSkipDuplicate( deduplicationKey: deduplicationKey, radioID: message.radioID, rxResult: rxResult, diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift index 224877da8a..b988b31651 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift @@ -11,6 +11,33 @@ public enum MCOImageTransport { private static let varintPayloadBits = 7 private static let maxVarintBytes = 5 + /// A datagram has no clock, so two copies with the same data field are one picture only + /// within this many seconds of each other. Flood repeats land well inside it; a later + /// identical drawing is a new picture. + public static let datagramMatchWindowSeconds: UInt32 = 300 + + /// Unix seconds within `datagramMatchWindowSeconds` either side of `anchor`, clamped to `UInt32`. + public static func datagramMatchWindow(around anchor: UInt32) -> ClosedRange { + let lower = anchor > datagramMatchWindowSeconds ? anchor - datagramMatchWindowSeconds : 0 + let upper = anchor > UInt32.max - datagramMatchWindowSeconds ? UInt32.max : anchor + datagramMatchWindowSeconds + return lower...upper + } + + public static func datagramMatchWindow(around date: Date) -> ClosedRange { + datagramMatchWindow(around: UInt32(clamping: Int64(date.timeIntervalSince1970))) + } + + /// RX receive times within `datagramMatchWindowSeconds` either side of `anchor`. + public static func datagramReceiveWindow(around anchor: Date) -> ClosedRange { + let span = TimeInterval(datagramMatchWindowSeconds) + return anchor.addingTimeInterval(-span)...anchor.addingTimeInterval(span) + } + + /// RX receive times within the window of a row's `timestamp` (Unix seconds). + public static func datagramReceiveWindow(around timestamp: UInt32) -> ClosedRange { + datagramReceiveWindow(around: Date(timeIntervalSince1970: TimeInterval(timestamp))) + } + public static func encode(text: String, senderName: String) throws -> Data { try framed(MCOImageCodec.channelAppPayload(fromText: text), senderName: senderName) } diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift index fbb81e876c..fad53af475 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift @@ -8,6 +8,11 @@ public enum MCOImageBase91 { private static let longMask = 16383 private static let shortThreshold = 88 + /// True when `text` is non-empty and every byte is in the alphabet. + static func isEncodedText(_ text: Substring) -> Bool { + !text.isEmpty && text.utf8.allSatisfy { decodeTable[$0] != nil } + } + public static func encode(_ data: Data) -> String { var output: [UInt8] = [] var queue = 0 diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift index 67d9ec429c..6d7cc52a32 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift @@ -16,6 +16,11 @@ public enum MCOImageCodec { version(in: text.trimmingCharacters(in: .whitespacesAndNewlines)) != nil } + /// `im4:` text, which a channel sends as group data. `im3:` goes out as group text. + public static func isChannelDataText(_ text: String) -> Bool { + version(in: text.trimmingCharacters(in: .whitespacesAndNewlines)) == v4Version + } + /// A channel row whose text is MCOimg. Group data and a channel text packet /// with an `im3:` or `im4:` body are the same stored shape. public static func isChannelMCOImage(channelIndex: UInt8?, text: String) -> Bool { @@ -67,7 +72,10 @@ public enum MCOImageCodec { public static func refreshNonce(in text: String) throws -> String { var payload = try appPayload(fromText: text) guard payload.count > 1 else { throw MCOImageCodecError.damaged } + let previous = payload[1] payload[1] = UInt8.random(in: .min ... .max) + // A repeated nonce would rebuild the replaced row's data field and merge into it. + if payload[1] == previous { payload[1] &+= 1 } return try self.text(fromAppPayload: payload) } @@ -83,8 +91,10 @@ public enum MCOImageCodec { } } + /// Nil unless the body after the colon is Base91, so prose like "im2: on my way" stays text. private static func version(in text: String) -> Int? { - guard text.hasPrefix("im"), let colon = text.firstIndex(of: ":") else { return nil } + guard text.hasPrefix("im"), let colon = text.firstIndex(of: ":"), + MCOImageBase91.isEncodedText(text[text.index(after: colon)...]) else { return nil } let digits = text[text.index(text.startIndex, offsetBy: textPrefixLength).. MessageDTO { var message = MessageDTO.testChannelMessage( id: id, radioID: radioID, channelIndex: channelIndex, text: text, - timestamp: 1_700_000_000, + timestamp: timestamp, direction: .incoming, pathLength: pathLength, senderNodeName: "Ada" diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift index d4d66bd9b7..8e38d4a437 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift @@ -18,8 +18,10 @@ struct MCOImageBinarySendTests { try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "救援隊", firmwareVersion: 12)) let channel = ChannelDTO.testChannel(radioID: radioID, floodScope: .region("Alpha")) try await store.saveChannel(channel) + // A stored outgoing row is already canonical `im4:`; `im3:` would mean group text. + let stored = try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: fixture)) let legacy = MessageDTO.testChannelMessage( - radioID: radioID, channelIndex: channel.index, text: fixture, senderNodeName: "救援隊" + radioID: radioID, channelIndex: channel.index, text: stored, senderNodeName: "救援隊" ) try await store.saveMessage(legacy) switch path { @@ -54,7 +56,7 @@ struct MCOImageBinarySendTests { let store = MockPersistenceStore() let session = MockMeshCoreSession() let service = MessageService(session: session, dataStore: store, contactService: nil) - try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio")) + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio", firmwareVersion: 11)) let message = try await service.createPendingChannelMessage(text: fixture, channelIndex: 0, radioID: radioID) try await service.sendPendingChannelMessage(messageID: message.id) try await service.sendPendingChannelMessage(messageID: message.id) @@ -80,7 +82,7 @@ struct MCOImageBinarySendTests { let session = MockMeshCoreSession() let service = MessageService(session: session, dataStore: store, contactService: nil) let name = "救援隊" - try await store.saveDevice(.testDevice(radioID: radioID, nodeName: name)) + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: name, firmwareVersion: 11)) let exact = try textWithPayloadSize(165, senderName: name) #expect(exact.utf8.count > ProtocolLimits.maxChannelMessageLength(nodeNameByteCount: name.utf8.count)) let message = try await service.createPendingChannelMessage(text: exact, channelIndex: 0, radioID: radioID) @@ -91,7 +93,7 @@ struct MCOImageBinarySendTests { try await service.createPendingChannelMessage(text: oversized, channelIndex: 0, radioID: radioID) } #expect(try await store.fetchMessages(radioID: radioID, channelIndex: 0, limit: 10, offset: 0).count == 1) - try await store.saveDevice(.testDevice(radioID: radioID, nodeName: name + "A")) + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: name + "A", firmwareVersion: 11)) try await service.sendPendingChannelMessage(messageID: message.id) let calls = await session.sendChannelDataInvocations #expect(calls.count == 2) @@ -107,7 +109,7 @@ struct MCOImageBinarySendTests { let store = MockPersistenceStore() let session = MockMeshCoreSession() let service = MessageService(session: session, dataStore: store, contactService: nil) - try await store.saveDevice(.testDevice(radioID: radioID)) + try await store.saveDevice(.testDevice(radioID: radioID, firmwareVersion: 11)) await #expect(throws: (any Error).self) { try await service.sendChannelMessage(text: text, channelIndex: 0, radioID: radioID) } @@ -115,13 +117,59 @@ struct MCOImageBinarySendTests { #expect(await session.sendChannelMessageInvocations.isEmpty) } + @Test + func `a radio without group data sends the drawing as im3 group text`() async throws { + let radioID = UUID() + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: store, contactService: nil) + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio", firmwareVersion: 10)) + let message = try await service.createPendingChannelMessage(text: fixture, channelIndex: 0, radioID: radioID) + #expect(message.text == fixture) + #expect(message.senderNodeName == "Radio") + #expect(!message.isDatagramMCOImage) + #expect(message.mcoImageReactionTarget() != nil) + try await service.sendPendingChannelMessage(messageID: message.id) + #expect(await session.sendChannelDataInvocations.isEmpty) + let call = try #require(await session.sendChannelMessageInvocations.first) + #expect(call.text == fixture) + } + + @Test + func `a radio without group data rejects im4 text`() async throws { + let radioID = UUID() + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: store, contactService: nil) + try await store.saveDevice(.testDevice(radioID: radioID, firmwareVersion: 10)) + let im4 = try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: fixture)) + await #expect(throws: MessageServiceError.self) { + try await service.sendChannelMessage(text: im4, channelIndex: 0, radioID: radioID) + } + #expect(await session.sendChannelDataInvocations.isEmpty) + #expect(await session.sendChannelMessageInvocations.isEmpty) + } + + @Test(arguments: ["im2: on my way", "im4:", "im3:ok then"]) + func `prose with an MCOimg-like prefix sends as channel text`(text: String) async throws { + let radioID = UUID() + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: store, contactService: nil) + try await store.saveDevice(.testDevice(radioID: radioID, firmwareVersion: 11)) + #expect(MCOImageCodec.content(from: text) == nil) + try await service.sendChannelMessage(text: text, channelIndex: 0, radioID: radioID) + #expect(await session.sendChannelDataInvocations.isEmpty) + #expect(await session.sendChannelMessageInvocations.count == 1) + } + @Test func `firmware rejection marks failed without a text fallback`() async throws { let radioID = UUID() let store = MockPersistenceStore() let session = MockMeshCoreSession() let service = MessageService(session: session, dataStore: store, contactService: nil) - try await store.saveDevice(.testDevice(radioID: radioID)) + try await store.saveDevice(.testDevice(radioID: radioID, firmwareVersion: 11)) let message = try await service.createPendingChannelMessage(text: fixture, channelIndex: 0, radioID: radioID) await session.setSendChannelDataError(MeshCoreError.deviceError(code: 1)) await #expect(throws: MessageServiceError.self) { @@ -146,9 +194,10 @@ struct MCOImageBinarySendTests { func `persisted legacy MCOimg replays as identical binary after disconnect`(failure: MeshCoreError) async throws { let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) let radioID = UUID() - try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio")) + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio", firmwareVersion: 11)) try await store.saveChannel(ChannelDTO.testChannel(radioID: radioID, index: 0)) - let message = MessageDTO.testChannelMessage(radioID: radioID, text: fixture, status: .pending) + let stored = try MCOImageCodec.text(fromAppPayload: MCOImageCodec.channelAppPayload(fromText: fixture)) + let message = MessageDTO.testChannelMessage(radioID: radioID, text: stored, status: .pending) try await store.saveMessage(message) let envelope = ChannelMessageEnvelope(messageID: message.id, channelIndex: 0, isResend: false, messageText: message.text, messageTimestamp: message.timestamp, localNodeName: "Radio") @@ -189,7 +238,7 @@ struct MCOImageBinarySendTests { let radioID = UUID() let store = MockPersistenceStore() let session = MockMeshCoreSession() - try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio")) + try await store.saveDevice(.testDevice(radioID: radioID, nodeName: "Radio", firmwareVersion: 11)) let service = MessageService(session: session, dataStore: store, contactService: nil, config: .init(poolBackoff: .init(baseDelay: 0, jitterRange: 1...1))) await session.setSendChannelDataErrors([.deviceError(code: 3), nil]) diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift index f56cbc84bc..ae766c3a8c 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift @@ -17,7 +17,7 @@ struct MCOImageReceiveIntegrationTests { ) async throws { let radioID = UUID() let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) - try await store.saveDevice(.testDevice(id: radioID)) + try await store.saveDevice(.testDevice(id: radioID, firmwareVersion: 11)) let channel = ChannelDTO.testChannel(radioID: radioID, index: 2) try await store.saveChannel(channel) let services = ServiceContainer( @@ -58,6 +58,7 @@ struct MCOImageReceiveIntegrationTests { #expect(message.senderNodeName == sender) #expect(message.timestampCorrected) #expect(message.senderTimestamp == 0) + #expect(!message.hasWireSendTime) #expect(message.createdAt >= before) #expect(message.snr == packet.snr) #expect(message.pathLength == packet.pathLength) @@ -87,7 +88,7 @@ struct MCOImageReceiveIntegrationTests { func `a recently blocked MCOimg is suppressed and an unblocked MCOimg is saved`() async throws { let radioID = UUID() let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) - try await store.saveDevice(.testDevice(id: radioID)) + try await store.saveDevice(.testDevice(id: radioID, firmwareVersion: 11)) let channel = ChannelDTO.testChannel(radioID: radioID, index: 2) try await store.saveChannel(channel) let savedChannel = try #require(try await store.fetchChannel(radioID: radioID, index: channel.index)) @@ -151,7 +152,7 @@ struct MCOImageReceiveIntegrationTests { let opened = try await openChannel() defer { Task { await opened.services.tearDown() } } let payload = try v3Payload() - let first = Date(timeIntervalSince1970: 1_700_000_000) + let first = Date() // Planted RX rows use the current receive time. try await push(opened, payload: payload, at: first) try await plantRX(opened, payload: payload, path: [0x21]) try await push(opened, payload: payload, at: first.addingTimeInterval(61)) @@ -167,6 +168,20 @@ struct MCOImageReceiveIntegrationTests { #expect(try await opened.store.fetchMessageRepeats(messageID: message.id).isEmpty) } + @Test + func `two identical MCOimg pushes outside the match window stay two rows`() async throws { + let opened = try await openChannel() + defer { Task { await opened.services.tearDown() } } + let payload = try v3Payload() + let first = Date(timeIntervalSince1970: 1_700_000_000) + let outside = TimeInterval(MCOImageTransport.datagramMatchWindowSeconds + 1) + try await push(opened, payload: payload, at: first) + try await push(opened, payload: payload, at: first.addingTimeInterval(outside)) + + let messages = try await opened.store.fetchMessages(radioID: opened.radioID, channelIndex: opened.channel.index) + #expect(messages.count == 2) + } + @Test func `two MCOimg pushes with no RX row keep the push path length`() async throws { let opened = try await openChannel() @@ -319,7 +334,7 @@ struct MCOImageReceiveIntegrationTests { private func openChannel(secret: Data = Data(repeating: 0x42, count: 16)) async throws -> OpenedChannel { let radioID = UUID() let store = try PersistenceStore(modelContainer: PersistenceStore.createContainer(inMemory: true)) - try await store.saveDevice(.testDevice(id: radioID)) + try await store.saveDevice(.testDevice(id: radioID, firmwareVersion: 11)) let channel = ChannelDTO.testChannel(radioID: radioID, index: 2, secret: secret) try await store.saveChannel(channel) let services = ServiceContainer( diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift index 34fb35dd2b..1094dc9271 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift @@ -24,10 +24,10 @@ struct MCOImageSendIntegrationTests { let store = MockPersistenceStore() let session = MockMeshCoreSession() let service = MessageService(session: session, dataStore: store, contactService: nil) - try await store.saveDevice(.testDevice(id: radioID, nodeName: "A")) + try await store.saveDevice(.testDevice(id: radioID, nodeName: "A", firmwareVersion: 11)) let text = String(repeating: "a", count: ProtocolLimits.maxChannelMessageLength(nodeNameByteCount: 1)) let message = try await service.createPendingChannelMessage(text: text, channelIndex: 0, radioID: radioID) - try await store.saveDevice(.testDevice(id: radioID, nodeName: "Longer")) + try await store.saveDevice(.testDevice(id: radioID, nodeName: "Longer", firmwareVersion: 11)) await #expect { try await service.sendPendingChannelMessage(messageID: message.id) } throws: { error in diff --git a/MC1Services/Tests/MC1ServicesTests/MECPNotificationTests.swift b/MC1Services/Tests/MC1ServicesTests/MECPNotificationTests.swift index 06baad2e10..f2f82aa91e 100644 --- a/MC1Services/Tests/MC1ServicesTests/MECPNotificationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MECPNotificationTests.swift @@ -20,6 +20,13 @@ struct MECPNotificationTests { #expect(!body.contains("Ada: MECP")) } + @Test + func `MCOimg arrival body names the drawing instead of showing Base91`() throws { + let text = try MCOImageCodec.text(fromAppPayload: #require(Data(base64Encoded: "E3oBjQBCvgE="))) + let body = NotificationService.arrivalBody(messageText: text, senderName: "Ada", bundle: .module) + #expect(body == "Ada: Pixel drawing") + } + @Test func `reaction quote truncates the space-joined reading`() { let reading = MECPCatalog.displayText(canonical, bundle: .module, preferredLocalizations: ["en"]) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift index 490dadd777..9cc5fe9764 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift @@ -1004,7 +1004,7 @@ struct ChatSendQueueServiceTests { func `enqueueReaction returns a row for a channel MCOimg and nil when the sender name is empty`() async throws { let store = try Self.makeStore() let radioID = UUID() - try await store.saveDevice(.testDevice(id: radioID, radioID: radioID, nodeName: "Painter")) + try await store.saveDevice(.testDevice(id: radioID, radioID: radioID, nodeName: "Painter", firmwareVersion: 11)) try await store.saveChannel(.testChannel(radioID: radioID, index: 0)) let text = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) let image = MessageDTO.testChannelMessage( diff --git a/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift index 2def917daa..2f4566d457 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift @@ -662,7 +662,10 @@ struct HeardRepeatsServiceTests { // MARK: - Datagram paths - private let imageText = "im3:g/5WjAL`NA" + /// Canonical `im4:` text: what a channel datagram row stores in both directions. + private let imageText = (try? MCOImageCodec.text( + fromAppPayload: MCOImageCodec.channelAppPayload(fromText: "im3:g/5WjAL`NA") + )) ?? "" private let imageSender = "Ada" private func imageBlob() throws -> Data { @@ -678,7 +681,8 @@ struct HeardRepeatsServiceTests { deduplicationKey: String?, pathLength: UInt8 = 4, snr: Double? = 9, - timestamp: UInt32 = 1_700_000_000 + // Near now: RX echoes are logged at the current time and must fall in the datagram match window. + timestamp: UInt32 = UInt32(Date().timeIntervalSince1970) ) -> MessageDTO { var message = MessageDTO.testChannelMessage( id: id, diff --git a/MC1Tests/Views/Chats/MCOImageMessageTests.swift b/MC1Tests/Views/Chats/MCOImageMessageTests.swift index 5d00c2e48a..eb17e3e8ae 100644 --- a/MC1Tests/Views/Chats/MCOImageMessageTests.swift +++ b/MC1Tests/Views/Chats/MCOImageMessageTests.swift @@ -26,7 +26,7 @@ struct MCOImageMessageTests { @Test func `terminal placeholders differ and participate in item identity`() { let id = UUID() let unsupported = MessageFragmentBuilderFixtures.makeMessage(id: id, text: "im5:anything") - let damaged = MessageFragmentBuilderFixtures.makeMessage(id: id, text: "im3:") + let damaged = MessageFragmentBuilderFixtures.makeMessage(id: id, text: "im3:!") let inputs = MessageFragmentBuilderFixtures.makeMinimalInputs(messageID: id) let environment = MessageFragmentBuilderFixtures.makeEnvInputs() let first = MessageFragmentBuilder.makeItem(for: unsupported, inputs: inputs, envInputs: environment) diff --git a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift index db85b1a24c..0a1ad5ee01 100644 --- a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift @@ -177,7 +177,7 @@ private final class AdmissionProbe { let task = Task { await draft.run( attempt, - isChannel: false, + transport: .direct, senderName: { "Radio" }, isReady: { self.ready }, onSend: { text in @@ -187,14 +187,14 @@ private final class AdmissionProbe { }, onWillSend: {}, onAdmitted: { self.admitted += 1 }, - encode: { image, isChannel in + encode: { image, transport in await MainActor.run { self.captured.append(image) } if pauseOnEncode { await pause.pause() } if failEncode { throw PixelEncodeFailure() } if oversized { return String(repeating: "a", count: ProtocolLimits.maxDirectMessageLength + 1) } - return try await encodePixelDrawing(image, channel: isChannel) + return try await encodePixelDrawing(image, transport: transport) } ) } @@ -234,3 +234,26 @@ final class SubmissionPause { release = nil } } + +@Suite("Pixel paint transport") +@MainActor +struct PixelPaintTransportTests { + @Test(arguments: [ + (isChannel: true, supportsChannelData: false, sendsGroupData: false), + (isChannel: true, supportsChannelData: true, sendsGroupData: true), + (isChannel: false, supportsChannelData: true, sendsGroupData: false), + ]) + func `only a channel on a radio with group data encodes im4`( + isChannel: Bool, supportsChannelData: Bool, sendsGroupData: Bool + ) async throws { + let side = PixelPaintDraft.side + let image = MCOImageRaster( + width: side, height: side, profile: PixelPaintDraft.profile, + pixels: Array(repeating: PixelPaintDraft.background, count: side * side) + ) + let transport = PixelPaintTransport(isChannel: isChannel, supportsChannelData: supportsChannelData) + let text = try await encodePixelDrawing(image, transport: transport) + #expect(MCOImageCodec.isChannelDataText(text) == sendsGroupData) + #expect(MCOImageCodec.content(from: text) != nil) + } +} diff --git a/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift index b6ec06ae74..bd13c64225 100644 --- a/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift @@ -157,7 +157,7 @@ struct PixelPaintPresentationTests { let task = Task { await draft.run( attempt, - isChannel: false, + transport: .direct, senderName: { "" }, isReady: { appState.connectionState == .ready }, onSend: { _ in @@ -166,9 +166,9 @@ struct PixelPaintPresentationTests { }, onWillSend: {}, onAdmitted: {}, - encode: { image, isChannel in + encode: { image, transport in await pause.pause() - return try await encodePixelDrawing(image, channel: isChannel) + return try await encodePixelDrawing(image, transport: transport) } ) } @@ -245,7 +245,7 @@ struct PixelPaintPresentationTests { let task = Task { await draft.run( attempt, - isChannel: false, + transport: .direct, senderName: { "" }, isReady: { model.ready }, onSend: { text in diff --git a/MeshCore/Sources/MeshCore/Protocol/PacketBuilder.swift b/MeshCore/Sources/MeshCore/Protocol/PacketBuilder.swift index 657bd023cb..3244d4b515 100644 --- a/MeshCore/Sources/MeshCore/Protocol/PacketBuilder.swift +++ b/MeshCore/Sources/MeshCore/Protocol/PacketBuilder.swift @@ -41,7 +41,7 @@ public enum PacketBuilder: Sendable { /// Flood sentinel for `path_len` fields: firmware treats `0xFF` as "route via flood". public static let floodPathSentinel: UInt8 = 0xFF /// RF payload limit for `CMD_SEND_CHANNEL_DATA`, matching firmware `MAX_GROUP_DATA_LENGTH` (165). - static let channelDataMaxPayloadBytes = 165 + public static let channelDataMaxPayloadBytes = 165 static let channelNameFieldBytes = 32 static let channelMaxNameBytes = channelNameFieldBytes - 1 /// Host-frame cap (`MAX_FRAME_SIZE` in firmware). diff --git a/docs/Reactions.md b/docs/Reactions.md index 047ab57f3a..a55dbf9550 100644 --- a/docs/Reactions.md +++ b/docs/Reactions.md @@ -28,7 +28,7 @@ SHA-256( 0x01 + bytes ) - **Room post.** `bytes` are the post text after the 4-byte sender pubkey prefix (`txt_type` `0x02`). - **Group datagram.** `bytes` are the `data` field. -Two copies with the same hash and sender: attach to the newest copy stored at or before the reaction. +Two copies with the same hash and sender: attach to the newest stored copy. A reaction that arrives before any copy attaches to the first copy that arrives; later copies don't take it. ### Why Crockford Base32? From 56cab980c4750831fbb2a243596ad39a701e24c2 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:15:07 -0800 Subject: [PATCH 09/13] feat: make MCOimg reactions and receipt native - One ChannelReactionTarget on MessageDTO drives reaction indexing, lookup, sending, and admission for group text, outgoing rows, and datagram pictures - findChannelMessageForReaction falls back to the newest datagram copy in the channel, so the separate datagram query is gone - A datagram arrives as a .datagram kind framed as the group text it stands for, so sender Text Rules now match it like an im3 group-text picture - One datagram predicate replaces two; an im3 group-text picture sent at wire time 0 now takes the timed hash its sender uses - HeardRepeatsService shares one datagram observation step and takes the RX row in place of four context parameters - Incoming channel text with no sender no longer offers reactions it cannot send --- .../Reactions/MessageActionAvailability.swift | 4 +- .../ViewModel/ChatTimelinePopulator.swift | 20 +- .../Persistence/MessagePersisting.swift | 16 -- .../Services/ChannelReactionTarget.swift | 32 +++ .../ChatSendQueueService+ChannelDrain.swift | 28 +-- .../Services/ChatSendQueueService.swift | 15 +- .../Services/HeardRepeatsService.swift | 82 +++---- .../Services/MessageDTO+MCOImage.swift | 43 +--- .../Services/MessageLRUCache.swift | 24 +- .../Services/MessageService+SendChannel.swift | 2 +- .../PersistenceStore+Diagnostics.swift | 2 +- .../Services/PersistenceStore+Messages.swift | 66 +---- .../PersistenceStore+OutgoingReactions.swift | 9 +- .../Services/ReactionService.swift | 31 +-- .../SyncCoordinator+MessageHandlers.swift | 231 +++++++----------- .../SyncCoordinator+ReactionHandlers.swift | 137 +++-------- .../Utilities/MCOimg/MCOImageCodec.swift | 6 - .../MCOImageBinarySendTests.swift | 2 +- .../MCOImageReceiveIntegrationTests.swift | 25 +- .../Mocks/MockPersistenceStore.swift | 45 +--- .../PersistenceStoreTests.swift | 74 ++---- .../Services/MessageLRUCacheTests.swift | 38 +-- .../Services/ReactionServiceTests.swift | 93 +------ ...rdinatorChannelMCOImageReactionTests.swift | 8 +- 24 files changed, 324 insertions(+), 709 deletions(-) create mode 100644 MC1Services/Sources/MC1Services/Services/ChannelReactionTarget.swift diff --git a/MC1/Views/Chats/Reactions/MessageActionAvailability.swift b/MC1/Views/Chats/Reactions/MessageActionAvailability.swift index bf1687091f..320c133d2a 100644 --- a/MC1/Views/Chats/Reactions/MessageActionAvailability.swift +++ b/MC1/Views/Chats/Reactions/MessageActionAvailability.swift @@ -26,7 +26,9 @@ struct MessageActionAvailability { && message.isFloodRouted && !(message.pathNodes?.isEmpty ?? true) canDelete = true - canReact = message.mcoImageReactionTarget() != nil || !message.isChannelMCOImage + // An outgoing channel row resolves its sender from the connected node when the sheet sends. + canReact = !message.isChannelMessage || message.isOutgoing + || message.channelReactionTarget(localNodeName: nil) != nil showsPathDetail = canViewPath || canShowRepeatDetails || (!message.isOutgoing && message.heardRepeats > 0) } } diff --git a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift index 02d2f93353..dc3cc5c8e8 100644 --- a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift +++ b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift @@ -151,28 +151,12 @@ enum ChatTimelinePopulator { // disconnect would otherwise mint a fresh UUID into persisted rows. let radioID = channel.radioID for message in fetchedMessages { - let indexed = message.mcoImageReactionTarget() - let reactionSender: String? - let messageHash: String? - if message.isChannelMCOImage { - reactionSender = indexed?.senderName - messageHash = indexed?.messageHash - } else if message.isOutgoing { - reactionSender = localNodeName - messageHash = nil - } else { - reactionSender = message.senderNodeName - messageHash = nil - } - guard let reactionSender else { continue } + guard let target = message.channelReactionTarget(localNodeName: localNodeName) else { continue } let pendingMatches = await reactionService.indexMessage( id: message.id, channelIndex: channel.index, - senderName: reactionSender, - text: message.text, - timestamp: message.reactionTimestamp, - messageHash: messageHash + target: target ) for pending in pendingMatches { diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index 4a0f226b04..6cf42ac67a 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -97,14 +97,6 @@ public protocol MessagePersisting: Actor { limit: Int ) async throws -> MessageDTO? - /// Newest saved channel MCOimg with no packet sender timestamp that matches this reaction. - /// No timestamp window and no row cap. - func findChannelDatagramForReaction( - radioID: UUID, - channelIndex: UInt8, - parsedReaction: ParsedReaction - ) async throws -> MessageDTO? - /// Fetches channel message candidates for meshcore-open reaction matching func fetchChannelMessageCandidates( radioID: UUID, @@ -292,14 +284,6 @@ extension MessagePersisting { } public extension MessagePersisting { - func findChannelDatagramForReaction( - radioID _: UUID, - channelIndex _: UInt8, - parsedReaction _: ParsedReaction - ) async throws -> MessageDTO? { - nil - } - func admitOutgoingReaction(_ message: MessageDTO) async throws -> MessageDTO? { nil } diff --git a/MC1Services/Sources/MC1Services/Services/ChannelReactionTarget.swift b/MC1Services/Sources/MC1Services/Services/ChannelReactionTarget.swift new file mode 100644 index 0000000000..7d6b906c67 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/ChannelReactionTarget.swift @@ -0,0 +1,32 @@ +import Foundation + +/// The sender name and message hash a channel reaction carries to reach one message. +public struct ChannelReactionTarget: Sendable, Hashable { + public let senderName: String + public let messageHash: String + + public init(senderName: String, messageHash: String) { + self.senderName = senderName + self.messageHash = messageHash + } + + /// Group text: the hash covers the body and the sender timestamp. + public init(senderName: String, text: String, timestamp: UInt32) { + self.init(senderName: senderName, messageHash: ReactionParser.generateMessageHash(text: text, timestamp: timestamp)) + } +} + +public extension MessageDTO { + /// Nil for a direct message or an unknown sender. An outgoing row uses its stored sender, else + /// `localNodeName`. A group datagram has no sender clock, so its hash covers the data field. + func channelReactionTarget(localNodeName: String?) -> ChannelReactionTarget? { + guard channelIndex != nil else { return nil } + let sender = isOutgoing ? senderNodeName ?? localNodeName : senderNodeName + guard let sender, !sender.isEmpty else { return nil } + guard isDatagramMCOImage else { + return ChannelReactionTarget(senderName: sender, text: text, timestamp: reactionTimestamp) + } + guard let datagramDataField else { return nil } + return ChannelReactionTarget(senderName: sender, messageHash: ReactionParser.generateUntimedHash(datagramDataField)) + } +} diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift index 67f6f7ecb8..4fc42f65d0 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift @@ -43,8 +43,7 @@ extension ChatSendQueueService { ) else { return } try cancelSendIfRetired(dependencies.sendsRetired) - let capturedText = envelope.messageText - let sentDatagram = MCOImageCodec.isChannelDataText(capturedText) + let sentDatagram = MCOImageCodec.isChannelDataText(envelope.messageText) switch try await transmitQueuedChannel(envelope: envelope, dependencies: dependencies) { case .dropped: return @@ -62,25 +61,20 @@ extension ChatSendQueueService { timeout: dependencies.config.transportWaitTimeout ) case let .sent(indexTimestamp): - if sentDatagram { - if let saved = try? await dependencies.dataStore.fetchMessage(id: envelope.messageID), - let target = saved.mcoImageReactionTarget() { - _ = await dependencies.reactionService.indexMessage( - id: saved.id, - channelIndex: envelope.channelIndex, - senderName: target.senderName, - text: saved.text, - timestamp: saved.reactionTimestamp, - messageHash: target.messageHash - ) + // A datagram's hash covers the sender name stored on the row, which a resend keeps. + let target: ChannelReactionTarget? = if sentDatagram { + try? await dependencies.dataStore.fetchMessage(id: envelope.messageID)? + .channelReactionTarget(localNodeName: envelope.localNodeName) + } else { + envelope.localNodeName.map { + ChannelReactionTarget(senderName: $0, text: envelope.messageText, timestamp: indexTimestamp) } - } else if let nodeName = envelope.localNodeName { + } + if let target { _ = await dependencies.reactionService.indexMessage( id: envelope.messageID, channelIndex: envelope.channelIndex, - senderName: nodeName, - text: capturedText, - timestamp: indexTimestamp + target: target ) } try? await dependencies.dataStore.deletePendingSendsForMessage(messageID: envelope.messageID) diff --git a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift index 9b3ad5362a..507aa93577 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -284,18 +284,11 @@ public final class ChatSendQueueService { guard target.radioID == radioID else { throw ChatSendQueueServiceError.notConnected } guard beginAdmission() else { throw CancellationError() } defer { finishAdmission() } + let text: String - if let indexed = target.mcoImageReactionTarget() { - text = reactionService.buildReactionText( - emoji: emoji, targetSender: indexed.senderName, messageHash: indexed.messageHash - ) - } else if target.isChannelMCOImage { - return nil - } else if target.channelIndex != nil { - guard let targetSender = target.isOutgoing ? senderName : target.senderNodeName else { return nil } - text = reactionService.buildReactionText( - emoji: emoji, targetSender: targetSender, targetText: target.text, targetTimestamp: target.reactionTimestamp - ) + if target.channelIndex != nil { + guard let reactionTarget = target.channelReactionTarget(localNodeName: senderName) else { return nil } + text = reactionService.buildReactionText(emoji: emoji, target: reactionTarget) } else { text = reactionService.buildDMReactionText( emoji: emoji, targetText: target.text, targetTimestamp: target.reactionTimestamp diff --git a/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift index 39ba5304c5..ad73fb440b 100644 --- a/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift +++ b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift @@ -148,6 +148,7 @@ public actor HeardRepeatsService { /// Records a distinct extra incoming path. The store reads the current canonical: /// nil adopts the path, and a stale nil DTO still records a later distinct path. + /// An adopted path also takes the route and region of `contextSource`, when given. @discardableResult func recordDistinctPathIfNeeded( message: MessageDTO, @@ -157,10 +158,7 @@ public actor HeardRepeatsService { rssi: Int?, receivedAt: Date, rxLogEntryID: UUID?, - canonicalRoute: RouteType? = nil, - canonicalRegion: String? = nil, - canonicalRegionMatches: [String] = [], - applyCanonicalContext: Bool = false + adoptingContextOf contextSource: RxLogEntryDTO? = nil ) async -> Int? { #if DEBUG if let hold = admissionHoldForTesting { @@ -177,12 +175,12 @@ public actor HeardRepeatsService { receivedAt: receivedAt, rxLogEntryID: rxLogEntryID ) - if case .adoptedCanonical = admission, applyCanonicalContext { + if case .adoptedCanonical = admission, let contextSource { try await dataStore.applyDatagramCanonicalContext( messageID: message.id, - routeType: canonicalRoute, - regionScope: canonicalRegion, - regionScopeMatches: canonicalRegionMatches + routeType: contextSource.routeType, + regionScope: contextSource.regionScope, + regionScopeMatches: contextSource.regionScopeMatches ) } guard case let .recordedExtra(count) = admission else { return nil } @@ -195,13 +193,12 @@ public actor HeardRepeatsService { } } - /// Outgoing rows count echoes. Incoming rows adopt the earliest path, then extras. + /// Attaches stored RX rows with this message's data field, oldest first. /// A nil service radio skips an outgoing row. func harvestDatagramPaths( for message: MessageDTO, decodedCandidates: [RxLogEntryDTO] ) async { - guard message.isDatagramPathMCOImage else { return } if message.isOutgoing, message.radioID != radioID { return } guard let blob = message.datagramDataField, let channelIndex = message.channelIndex else { return } @@ -212,23 +209,7 @@ public actor HeardRepeatsService { channelIndex: channelIndex ) for entry in matching { - if message.isOutgoing { - _ = try? await recordSentEcho(message: message, entry: entry) - } else { - _ = await recordDistinctPathIfNeeded( - message: message, - pathNodes: entry.pathNodes, - pathLength: entry.pathLength, - snr: entry.snr, - rssi: entry.rssi, - receivedAt: entry.receivedAt, - rxLogEntryID: entry.id, - canonicalRoute: entry.routeType, - canonicalRegion: entry.regionScope, - canonicalRegionMatches: entry.regionScopeMatches, - applyCanonicalContext: true - ) - } + _ = await recordDatagramObservation(entry, on: message) } } @@ -322,29 +303,9 @@ public actor HeardRepeatsService { channelIndex: channelIndex, timestampWindow: MCOImageTransport.datagramMatchWindow(around: entry.receivedAt) ) - let matches = messages.filter { $0.datagramDataField == blob } var lastCount: Int? - for message in matches where message.isOutgoing { - if let count = try await recordSentEcho(message: message, entry: entry) { - lastCount = count - } - } - for message in matches where !message.isOutgoing { - if let count = await recordDistinctPathIfNeeded( - message: message, - pathNodes: entry.pathNodes, - pathLength: entry.pathLength, - snr: entry.snr, - rssi: entry.rssi, - receivedAt: entry.receivedAt, - rxLogEntryID: entry.id, - canonicalRoute: entry.routeType, - canonicalRegion: entry.regionScope, - canonicalRegionMatches: entry.regionScopeMatches, - applyCanonicalContext: true - ) { - lastCount = count - } + for message in messages where message.datagramDataField == blob { + lastCount = await recordDatagramObservation(entry, on: message) ?? lastCount } return lastCount } catch { @@ -352,4 +313,27 @@ public actor HeardRepeatsService { return nil } } + + /// An outgoing row counts the echo. An incoming row records the path, and the path it adopts + /// brings the RX row's route and region, which a datagram push does not carry. + private func recordDatagramObservation(_ entry: RxLogEntryDTO, on message: MessageDTO) async -> Int? { + guard !message.isOutgoing else { + do { + return try await recordSentEcho(message: message, entry: entry) + } catch { + logger.error("Failed to record datagram echo: \(error.localizedDescription)") + return nil + } + } + return await recordDistinctPathIfNeeded( + message: message, + pathNodes: entry.pathNodes, + pathLength: entry.pathLength, + snr: entry.snr, + rssi: entry.rssi, + receivedAt: entry.receivedAt, + rxLogEntryID: entry.id, + adoptingContextOf: entry + ) + } } diff --git a/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift index 4cc31672e5..74bde2b947 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift @@ -9,51 +9,30 @@ public extension MessageDTO { channelIndex != nil && MCOImageCodec.isMCOImageText(text) } - /// A channel MCOimg with no packet sender timestamp. - /// Incoming `senderTimestamp` nil is an accepted packet time. Zero is the datagram tuple. - /// An outgoing `im4:` row went out as group data; an outgoing `im3:` row went out as group text. + /// A channel MCOimg sent as group data, which has no sender clock. An outgoing row stores `im4:`. + /// An incoming row stores sender time 0 and a key that is not the group-text key at wire time 0. var isDatagramMCOImage: Bool { - guard isChannelMCOImage else { return false } - if isOutgoing { return MCOImageCodec.isChannelDataText(text) } - return senderTimestamp == 0 - } - - /// False for an incoming datagram MCOimg: the packet carries no send time, so only receipt is known. - var hasWireSendTime: Bool { - isOutgoing || !isDatagramMCOImage - } - - /// Path join for a channel MCOimg. Group text keeps the content key, including wire time 0. - /// Reactions use `isDatagramMCOImage`, which still includes that group-text row. - var isDatagramPathMCOImage: Bool { guard isChannelMCOImage, let channelIndex else { return false } if isOutgoing { return MCOImageCodec.isChannelDataText(text) } guard senderTimestamp == 0 else { return false } - let contentKey = DeduplicationKey.contentBased( + let groupTextKey = DeduplicationKey.contentBased( contactID: nil, channelIndex: channelIndex, senderNodeName: senderNodeName, timestamp: 0, content: text ) - return deduplicationKey != contentKey + return deduplicationKey != groupTextKey } - /// Nil unless this row is a path MCOimg and the data field can be rebuilt. - var datagramDataField: Data? { - guard isDatagramPathMCOImage, - let name = senderNodeName, !name.isEmpty else { return nil } - return try? MCOImageTransport.dataField(text: text, senderName: name) + /// False for an incoming datagram MCOimg: the packet carries no send time, so only receipt is known. + var hasWireSendTime: Bool { + isOutgoing || !isDatagramMCOImage } - /// Nil when the name is missing or the datagram bytes cannot be rebuilt. - func mcoImageReactionTarget() -> (senderName: String, messageHash: String)? { - guard isChannelMCOImage else { return nil } - guard let senderNodeName, !senderNodeName.isEmpty else { return nil } - if isDatagramMCOImage { - guard let data = try? MCOImageTransport.dataField(text: text, senderName: senderNodeName) else { return nil } - return (senderNodeName, ReactionParser.generateUntimedHash(data)) - } - return (senderNodeName, ReactionParser.generateMessageHash(text: text, timestamp: reactionTimestamp)) + /// The group-datagram data field this row went out or arrived as. Nil for any other row. + var datagramDataField: Data? { + guard isDatagramMCOImage, let name = senderNodeName, !name.isEmpty else { return nil } + return try? MCOImageTransport.dataField(text: text, senderName: name) } } diff --git a/MC1Services/Sources/MC1Services/Services/MessageLRUCache.swift b/MC1Services/Sources/MC1Services/Services/MessageLRUCache.swift index b617e86a9f..1b00df88c8 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageLRUCache.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageLRUCache.swift @@ -16,14 +16,10 @@ struct DirectMessageCacheKey: Hashable { /// Candidate message for reaction matching struct MessageCandidate: Equatable { let messageID: UUID - let text: String - let timestamp: UInt32 let indexedAt: Date - init(messageID: UUID, text: String, timestamp: UInt32, indexedAt: Date = Date()) { + init(messageID: UUID, indexedAt: Date = Date()) { self.messageID = messageID - self.text = text - self.timestamp = timestamp self.indexedAt = indexedAt } } @@ -44,18 +40,10 @@ actor MessageLRUCache { self.maxCandidatesPerKey = maxCandidatesPerKey } - /// A supplied hash replaces the timed hash. - func index( - messageID: UUID, - channelIndex: UInt8, - senderName: String, - text: String, - timestamp: UInt32, - messageHash: String? = nil - ) { - let hash = messageHash ?? ReactionParser.generateMessageHash(text: text, timestamp: timestamp) - let key = MessageCacheKey(channelIndex: channelIndex, senderName: senderName, messageHash: hash) - let candidate = MessageCandidate(messageID: messageID, text: text, timestamp: timestamp) + /// Indexes a message for later lookup + func index(messageID: UUID, channelIndex: UInt8, target: ChannelReactionTarget) { + let key = MessageCacheKey(channelIndex: channelIndex, senderName: target.senderName, messageHash: target.messageHash) + let candidate = MessageCandidate(messageID: messageID) // Update LRU order if let existingIndex = order.firstIndex(of: key) { @@ -96,7 +84,7 @@ actor MessageLRUCache { func indexDM(messageID: UUID, contactID: UUID, text: String, timestamp: UInt32) { let hash = ReactionParser.generateMessageHash(text: text, timestamp: timestamp) let key = DirectMessageCacheKey(contactID: contactID, messageHash: hash) - let candidate = MessageCandidate(messageID: messageID, text: text, timestamp: timestamp) + let candidate = MessageCandidate(messageID: messageID) // Update LRU order if let existingIndex = dmOrder.firstIndex(of: key) { diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index 599ce7d632..a125b25bdc 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -127,7 +127,7 @@ public extension MessageService { /// An RX row saved before the message is attached here. A later row is attached by `processForRepeats`. /// The harvest writes only while `HeardRepeatsService` still owns this radio. private func harvestOutgoingDatagramPathsIfNeeded(_ message: MessageDTO) async { - guard message.isOutgoing, message.isDatagramPathMCOImage else { return } + guard message.isOutgoing, message.isDatagramMCOImage else { return } await datagramPathHarvest?(message) } diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift index 6b5118e4f9..50f6270db0 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift @@ -464,7 +464,7 @@ public extension PersistenceStore { ) for message in try modelContext.fetch(descriptor) { // senderTimestamp 0 on an MCOimg is a missing clock, so a wire-time region write must not land here. - if MessageDTO(from: message).isDatagramPathMCOImage { continue } + if MessageDTO(from: message).isDatagramMCOImage { continue } message.regionScope = update.regionScope message.regionScopeMatches = update.regionScopeMatches touchedIDs.append(message.id) diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift index fc35b0fdec..4917fc4bc4 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Messages.swift @@ -199,7 +199,8 @@ public extension PersistenceStore { return (MessageDTO.reorderSameSenderClusters(dtos), hasMore) } - /// Finds a channel message matching a parsed reaction within a timestamp window. + /// Finds the channel message a parsed reaction names. Group text matches within `timestampWindow`. + /// A group datagram has no sender clock, so its newest copy anywhere in the channel matches. func findChannelMessageForReaction( radioID: UUID, channelIndex: UInt8, @@ -210,6 +211,8 @@ public extension PersistenceStore { ) throws -> MessageDTO? { let logger = Logger(subsystem: "com.mc1", category: "PersistenceStore") logger.debug("[REACTION-MATCH] Looking for message: targetSender=\(parsedReaction.targetSender), hash=\(parsedReaction.messageHash), localNodeName=\(localNodeName ?? "nil"), window=\(timestampWindow.lowerBound)...\(timestampWindow.upperBound)") + let wanted = ChannelReactionTarget(senderName: parsedReaction.targetSender, messageHash: parsedReaction.messageHash) + let isWanted = { (candidate: MessageDTO) in candidate.channelReactionTarget(localNodeName: localNodeName) == wanted } let candidates = try fetchChannelMessageCandidates( radioID: radioID, @@ -218,65 +221,26 @@ public extension PersistenceStore { limit: limit ) logger.debug("[REACTION-MATCH] Found \(candidates.count) candidates in window") - guard !candidates.isEmpty else { return nil } - - for candidate in candidates { - let direction = candidate.direction == .outgoing ? "outgoing" : "incoming" - let candidateHash = ReactionParser.generateMessageHash(text: candidate.text, timestamp: candidate.reactionTimestamp) - logger.debug("[REACTION-MATCH] Candidate: direction=\(direction), senderNodeName=\(candidate.senderNodeName ?? "nil"), hash=\(candidateHash), text=\(candidate.text.prefix(30))") - - if candidate.direction == .outgoing { - guard let localNodeName, parsedReaction.targetSender == localNodeName else { - logger.debug("[REACTION-MATCH] Skip outgoing: localNodeName=\(localNodeName ?? "nil"), targetSender=\(parsedReaction.targetSender)") - continue - } - } else { - guard candidate.senderNodeName == parsedReaction.targetSender else { - logger.debug("[REACTION-MATCH] Skip incoming: senderNodeName=\(candidate.senderNodeName ?? "nil") != targetSender=\(parsedReaction.targetSender)") - continue - } - } - - guard candidateHash == parsedReaction.messageHash else { - logger.debug("[REACTION-MATCH] Hash mismatch: \(candidateHash) != \(parsedReaction.messageHash)") - continue - } - - guard !candidate.isDatagramMCOImage else { - logger.debug("[REACTION-MATCH] Skip datagram image") - continue - } - + if let match = candidates.first(where: isWanted) { logger.debug("[REACTION-MATCH] Found match!") - return candidate + return match } - logger.debug("[REACTION-MATCH] No match found") - return nil - } - - func findChannelDatagramForReaction( - radioID: UUID, - channelIndex: UInt8, - parsedReaction: ParsedReaction - ) async throws -> MessageDTO? { let targetRadioID = radioID let targetChannelIndex: UInt8? = channelIndex let predicate = #Predicate { message in message.radioID == targetRadioID && message.channelIndex == targetChannelIndex } - let descriptor = FetchDescriptor( - predicate: predicate, - sortBy: [SortDescriptor(\Message.createdAt, order: .reverse)] - ) + let descriptor = FetchDescriptor(predicate: predicate, sortBy: [SortDescriptor(\Message.createdAt, order: .reverse)]) for message in try modelContext.fetch(descriptor) { let candidate = MessageDTO(from: message) - guard let target = candidate.mcoImageReactionTarget(), - candidate.isDatagramMCOImage, - target.senderName == parsedReaction.targetSender, - target.messageHash == parsedReaction.messageHash else { continue } - return candidate + if candidate.isDatagramMCOImage, isWanted(candidate) { + logger.debug("[REACTION-MATCH] Found datagram match") + return candidate + } } + + logger.debug("[REACTION-MATCH] No match found") return nil } @@ -1135,10 +1099,6 @@ public extension PersistenceStore { var messageDescriptor = FetchDescriptor(predicate: messagePredicate) messageDescriptor.fetchLimit = 1 guard let message = try modelContext.fetch(messageDescriptor).first else { return nil } - let messageDTO = MessageDTO(from: message) - if messageDTO.isChannelMCOImage, messageDTO.mcoImageReactionTarget() == nil { - return nil - } let senderName = dto.senderName let emoji = dto.emoji diff --git a/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift index 377786abcb..e1b0fbe853 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift @@ -8,10 +8,11 @@ public extension PersistenceStore { let details = outgoingReactionDetails(message), let target = try outgoingReactionTarget(message) else { return nil } let targetDTO = MessageDTO(from: target) - let expectedHash = targetDTO.mcoImageReactionTarget()?.messageHash - ?? ReactionParser.generateMessageHash( - text: target.text, timestamp: target.senderTimestamp ?? target.timestamp - ) + let expectedHash = if targetDTO.channelIndex != nil { + targetDTO.channelReactionTarget(localNodeName: senderName)?.messageHash + } else { + ReactionParser.generateMessageHash(text: target.text, timestamp: targetDTO.reactionTimestamp) + } guard details.messageHash == expectedHash else { return nil } guard try !reactionExists(messageID: target.id, senderName: senderName, emoji: details.emoji) else { return nil diff --git a/MC1Services/Sources/MC1Services/Services/ReactionService.swift b/MC1Services/Sources/MC1Services/Services/ReactionService.swift index 9220f48a4d..1198280088 100644 --- a/MC1Services/Sources/MC1Services/Services/ReactionService.swift +++ b/MC1Services/Sources/MC1Services/Services/ReactionService.swift @@ -71,25 +71,15 @@ public actor ReactionService { public func indexMessage( id: UUID, channelIndex: UInt8, - senderName: String, - text: String, - timestamp: UInt32, - messageHash: String? = nil + target: ChannelReactionTarget ) async -> [PendingReaction] { - let hash = messageHash ?? ReactionParser.generateMessageHash(text: text, timestamp: timestamp) - let key = PendingReactionKey( - channelIndex: channelIndex, - targetSender: senderName, - messageHash: hash - ) + await messageCache.index(messageID: id, channelIndex: channelIndex, target: target) - await messageCache.index( - messageID: id, + // Check pending queue for matching reactions + let key = PendingReactionKey( channelIndex: channelIndex, - senderName: senderName, - text: text, - timestamp: timestamp, - messageHash: hash + targetSender: target.senderName, + messageHash: target.messageHash ) guard let matched = pendingReactions.removeValue(forKey: key) else { @@ -112,14 +102,13 @@ public actor ReactionService { ) -> String { buildReactionText( emoji: emoji, - targetSender: targetSender, - messageHash: ReactionParser.generateMessageHash(text: targetText, timestamp: targetTimestamp) + target: ChannelReactionTarget(senderName: targetSender, text: targetText, timestamp: targetTimestamp) ) } - /// Channel reaction wire text for a hash the caller already computed. - public nonisolated func buildReactionText(emoji: String, targetSender: String, messageHash: String) -> String { - "@[\(targetSender)]\(emoji)\n\(messageHash)" + /// Channel reaction wire text that names `target`. + public nonisolated func buildReactionText(emoji: String, target: ChannelReactionTarget) -> String { + "@[\(target.senderName)]\(emoji)\n\(target.messageHash)" } /// Builds DM reaction wire format (shorter, no sender) diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift index cfc4c0853f..89e4f92cf0 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+MessageHandlers.swift @@ -62,15 +62,17 @@ extension SyncCoordinator { private func wireChannelDatagramHandler(dependencies: SyncDependencies, radioID: UUID, selfNodeName: String) async { await dependencies.messagePollingService.setChannelDatagramHandler { [weak self] datagram, channel, context, scope, preference, arrivedAt in guard let self, scope.radioID == radioID, scope.isCurrent, let decoded = MCOImageTransport.decode(datagram) else { return } + // The group text this picture would have been. Sender time 0 marks that group data has no clock. + let frame = ChannelMessage( + channelIndex: datagram.channelIndex, + pathLength: datagram.pathLength, + textType: MeshTextType.plain.rawValue, + senderTimestamp: Date(timeIntervalSince1970: 0), + text: "\(decoded.senderName): \(decoded.text)", + snr: datagram.snr + ) await handleIncomingMessage( - kind: .mcoImage( - channelIndex: datagram.channelIndex, - text: decoded.text, - senderName: decoded.senderName, - pathLength: datagram.pathLength, - snr: datagram.snr, - channel: channel - ), + kind: .datagram(frame, senderName: decoded.senderName, text: decoded.text, channel: channel), receivedAt: arrivedAt, context: context, dependencies: dependencies, @@ -83,25 +85,26 @@ extension SyncCoordinator { // MARK: - Incoming Message Pipeline + /// Discriminates the text-message ingestion paths, carrying the wire + /// message and the resolved conversation for each. private enum IncomingMessageKind { case direct(ContactMessage, contact: ContactDTO?) case channel(ChannelMessage, channel: ChannelDTO?) - case mcoImage( - channelIndex: UInt8, - text: String, - senderName: String, - pathLength: UInt8, - snr: Double, - channel: ChannelDTO? - ) + /// A group-datagram picture with its length-prefixed sender, which the frame text cannot carry exactly. + case datagram(ChannelMessage, senderName: String, text: String, channel: ChannelDTO?) - /// Channel text and an MCOimg share one log noun. + /// Log noun distinguishing the paths in shared diagnostics. var logLabel: String { switch self { case .direct: "direct" - case .channel, .mcoImage: "channel" + case .channel, .datagram: "channel" } } + + /// Group data carries no sender timestamp. + var hasSenderClock: Bool { + if case .datagram = self { false } else { true } + } } /// When a DM arrives with no local contact, try to create the row from a @@ -291,20 +294,17 @@ extension SyncCoordinator { kind, dependencies: dependencies, scope: scope ) - // Channel text embeds the sender as a "NodeName: text" prefix. - // An MCOimg already has its name. A direct message carries the key prefix. + // Per-kind wire fields. Channel messages embed the sender as a + // "NodeName: text" prefix; direct messages carry the sender key prefix. let text: String let senderNodeName: String? + let senderTimestampDate: Date let textTypeRaw: UInt8 let snr: Double? let reportedPathLength: UInt8 let contactID: UUID? let channelIndex: UInt8? let senderKeyPrefix: Data? - let conversation: ChannelDTO? - let wireTimestamp: UInt32? - let harvestIncomingPaths: Bool - let suppressionFrame: ChannelMessage? switch resolvedKind { case let .direct(message, contact): // The firmware cannot surface a self-DM here: decrypt runs against a @@ -312,75 +312,43 @@ extension SyncCoordinator { // contacts[], so an echo of the user's own DM never reaches this arm. text = message.text senderNodeName = nil + senderTimestampDate = message.senderTimestamp textTypeRaw = message.textType snr = message.snr reportedPathLength = message.pathLength contactID = contact?.id channelIndex = nil senderKeyPrefix = message.senderPublicKeyPrefix - conversation = nil - wireTimestamp = UInt32(message.senderTimestamp.timeIntervalSince1970) - harvestIncomingPaths = false - suppressionFrame = nil - case let .channel(message, channel): + case let .channel(message, _): + // Parse "NodeName: text" format for sender name (senderNodeName, text) = Self.parseChannelMessage(message.text) + senderTimestampDate = message.senderTimestamp textTypeRaw = message.textType snr = message.snr reportedPathLength = message.pathLength contactID = nil channelIndex = message.channelIndex senderKeyPrefix = nil - conversation = channel - wireTimestamp = UInt32(message.senderTimestamp.timeIntervalSince1970) - harvestIncomingPaths = true - suppressionFrame = message - case let .mcoImage(index, mcoImageText, senderName, pathLength, mcoImageSNR, channel): - text = mcoImageText - senderNodeName = senderName - textTypeRaw = MeshTextType.plain.rawValue - snr = mcoImageSNR - reportedPathLength = pathLength + case let .datagram(message, datagramSender, datagramText, _): + text = datagramText + senderNodeName = datagramSender + senderTimestampDate = message.senderTimestamp + textTypeRaw = message.textType + snr = message.snr + reportedPathLength = message.pathLength contactID = nil - channelIndex = index + channelIndex = message.channelIndex senderKeyPrefix = nil - conversation = channel - wireTimestamp = nil - harvestIncomingPaths = false - // Text Rules identify an MCOimg by its stored text, plain type, and sender time 0. - suppressionFrame = ChannelMessage( - channelIndex: index, - pathLength: pathLength, - textType: MeshTextType.plain.rawValue, - senderTimestamp: Date(timeIntervalSince1970: 0), - text: mcoImageText, - snr: mcoImageSNR - ) } + let timestamp = UInt32(senderTimestampDate.timeIntervalSince1970) + + // Correct invalid timestamps (sender clock wrong). A datagram's sender time 0 is always + // corrected to receipt and stored as 0, which marks the missing clock. let receiveTime = receivedAt - let finalTimestamp: UInt32 - let timestampCorrected: Bool - let storedSenderTimestamp: UInt32? - let dedupTimestamp: UInt32 - let rxSenderTimestamp: UInt32? - if let wireTimestamp { - let corrected = Self.correctTimestampIfNeeded(wireTimestamp, receiveTime: receiveTime) - finalTimestamp = corrected.correctedTimestamp - timestampCorrected = corrected.wasCorrected - storedSenderTimestamp = timestampCorrected ? wireTimestamp : nil - dedupTimestamp = wireTimestamp - rxSenderTimestamp = wireTimestamp - if timestampCorrected { - logger.debug("Corrected invalid \(resolvedKind.logLabel) message timestamp from \(Date(timeIntervalSince1970: TimeInterval(wireTimestamp))) to \(receiveTime)") - } - } else { - // An MCOimg has no wire time. senderTimestamp 0 is that absence. - // A rebuilt data field dedups the row. Otherwise the receive second does. - finalTimestamp = UInt32(receiveTime.timeIntervalSince1970) - timestampCorrected = true - storedSenderTimestamp = 0 - dedupTimestamp = finalTimestamp - rxSenderTimestamp = nil + let (finalTimestamp, timestampCorrected) = Self.correctTimestampIfNeeded(timestamp, receiveTime: receiveTime) + if timestampCorrected { + logger.debug("Corrected invalid \(resolvedKind.logLabel) message timestamp from \(Date(timeIntervalSince1970: TimeInterval(timestamp))) to \(receiveTime)") } let sortDate = Self.sortDate(for: context, receiveTime: receiveTime) @@ -388,22 +356,23 @@ extension SyncCoordinator { // Use content-based key for dedup (stable across retry attempts). // The RX log packetHash is per-encrypted-packet and differs between // retries with different attempt counters, so it must not drive dedup. + // A datagram that cannot rebuild its data field keys on the receive second instead. let deduplicationKey = Self.channelDeduplicationKey( kind: resolvedKind, contactID: contactID, channelIndex: channelIndex, senderNodeName: senderNodeName, - timestamp: dedupTimestamp, + timestamp: resolvedKind.hasSenderClock ? timestamp : finalTimestamp, content: text ) // Channel lookup joins decrypted 0x88 rows by DeduplicationKey; DMs still - // match timestamp then sender-prefix. An MCOimg has no sender timestamp. + // match timestamp then sender-prefix. A datagram has no sender timestamp to join on. let rxResult = await lookupRxLogEntry( dependencies: dependencies, radioID: radioID, channelIndex: channelIndex, - senderTimestamp: rxSenderTimestamp, + senderTimestamp: resolvedKind.hasSenderClock ? timestamp : nil, senderPublicKeyPrefix: senderKeyPrefix, defaultPathLength: reportedPathLength, channelDeduplicationKey: channelIndex != nil ? deduplicationKey : nil @@ -415,14 +384,12 @@ extension SyncCoordinator { case .direct: !selfNodeName.isEmpty && MentionUtilities.containsSelfMention(in: text, selfName: selfNodeName) - case .channel: - // Base91 includes `@`, `[`, and `]`, so a group-text picture is never a mention. + case .channel, .datagram: + // Base91 includes `@`, `[`, and `]`, so a picture is never a mention. !selfNodeName.isEmpty && senderNodeName != selfNodeName && !MCOImageCodec.isMCOImageText(text) && MentionUtilities.containsSelfMention(in: text, selfName: selfNodeName) - case .mcoImage: - false } // Clamp an unknown wire textType to .plain. MessageDTO decodes textType @@ -467,7 +434,7 @@ extension SyncCoordinator { containsSelfMention: hasSelfMention, mentionSeen: false, timestampCorrected: timestampCorrected, - senderTimestamp: storedSenderTimestamp, + senderTimestamp: timestampCorrected ? timestamp : nil, routeType: rxResult.routeType, regionScope: rxResult.regionScope, regionScopeMatches: rxResult.regionScopeMatches @@ -480,15 +447,13 @@ extension SyncCoordinator { scope: scope, preference: preference, dependencies: dependencies ) - case .channel, .mcoImage: - guard let suppressionFrame else { return } + case let .channel(frame, channel), let .datagram(frame, _, _, channel): await receiveChannelMessage( messageDTO, - frame: suppressionFrame, + frame: frame, deduplicationKey: deduplicationKey, rxResult: rxResult, - conversation: conversation, - harvestIncomingPaths: harvestIncomingPaths, + channel: channel, selfNodeName: selfNodeName, scope: scope, preference: preference, @@ -502,8 +467,7 @@ extension SyncCoordinator { frame: ChannelMessage, deduplicationKey: String, rxResult: RxLogLookupResult, - conversation: ChannelDTO?, - harvestIncomingPaths: Bool, + channel: ChannelDTO?, selfNodeName: String, scope: ReceiveScope, preference: TextRulesPreference?, @@ -532,8 +496,8 @@ extension SyncCoordinator { return } do { - if let conversation, try await dependencies.dataStore.shouldSuppressChannelMessage( - message, frame: frame, channel: conversation, scope: scope, preference: preference + if let channel, try await dependencies.dataStore.shouldSuppressChannelMessage( + message, frame: frame, channel: channel, scope: scope, preference: preference ) { return } } catch { logger.error("Failed to evaluate channel Text Rules: \(error)") @@ -554,28 +518,26 @@ extension SyncCoordinator { do { await runTestBeforeMessageSave(message) guard try await dependencies.dataStore.saveReceivedChannelMessage( - message, scope: scope, conversationID: conversation?.textRulesID + message, scope: scope, conversationID: channel?.textRulesID ), scope.isCurrent else { return } - let savedDTO: MessageDTO = if harvestIncomingPaths { - try await harvestAndRefreshChannelMessage( + let savedDTO = if message.isDatagramMCOImage { + try await harvestDatagramAndRefresh( messageDTO: message, - radioID: message.radioID, dependencies: dependencies, scope: scope ) - } else if message.isDatagramPathMCOImage { - try await harvestDatagramAndRefresh( + } else { + try await harvestAndRefreshChannelMessage( messageDTO: message, + radioID: message.radioID, dependencies: dependencies, scope: scope ) - } else { - message } try await indexAndNotifyChannelMessage( messageDTO: savedDTO, - channel: conversation, + channel: channel, dependencies: dependencies, scope: scope ) @@ -694,23 +656,27 @@ extension SyncCoordinator { scope: ReceiveScope ) async throws { guard scope.isCurrent, let channelIndex = messageDTO.channelIndex else { return } - let pendingMatches = await pendingChannelReactions( - for: messageDTO, - channelIndex: channelIndex, - dependencies: dependencies - ) - for pending in pendingMatches { - guard scope.isCurrent else { return } - let reactionDTO = ReactionDTO( - messageID: messageDTO.id, - emoji: pending.parsed.emoji, - senderName: pending.senderNodeName, - messageHash: pending.parsed.messageHash, - rawText: pending.rawText, - channelIndex: pending.channelIndex, - radioID: pending.radioID + // Use the sender timestamp so pending reactions match corrected-clock messages. + if let target = messageDTO.channelReactionTarget(localNodeName: nil) { + let pendingMatches = await dependencies.reactionService.indexMessage( + id: messageDTO.id, + channelIndex: channelIndex, + target: target ) - await persistReactionIfNew(reactionDTO, dependencies: dependencies) + + for pending in pendingMatches { + guard scope.isCurrent else { return } + let reactionDTO = ReactionDTO( + messageID: messageDTO.id, + emoji: pending.parsed.emoji, + senderName: pending.senderNodeName, + messageHash: pending.parsed.messageHash, + rawText: pending.rawText, + channelIndex: pending.channelIndex, + radioID: pending.radioID + ) + await persistReactionIfNew(reactionDTO, dependencies: dependencies) + } } guard scope.isCurrent else { return } @@ -728,35 +694,6 @@ extension SyncCoordinator { } } - /// A channel MCOimg with no reaction target is not indexed. - private func pendingChannelReactions( - for messageDTO: MessageDTO, - channelIndex: UInt8, - dependencies: SyncDependencies - ) async -> [PendingReaction] { - if let target = messageDTO.mcoImageReactionTarget() { - return await dependencies.reactionService.indexMessage( - id: messageDTO.id, - channelIndex: channelIndex, - senderName: target.senderName, - text: messageDTO.text, - timestamp: messageDTO.reactionTimestamp, - messageHash: target.messageHash - ) - } - if MCOImageCodec.isChannelMCOImage(channelIndex: channelIndex, text: messageDTO.text) { - return [] - } - guard let senderName = messageDTO.senderNodeName else { return [] } - return await dependencies.reactionService.indexMessage( - id: messageDTO.id, - channelIndex: channelIndex, - senderName: senderName, - text: messageDTO.text, - timestamp: messageDTO.reactionTimestamp - ) - } - // MARK: - Signed Message Handler private func wireSignedMessageHandler(dependencies: SyncDependencies) async { @@ -949,7 +886,7 @@ extension SyncCoordinator { timestamp: UInt32, content: String ) -> String { - if case .mcoImage = kind, + if case .datagram = kind, let channelIndex, let senderNodeName, !senderNodeName.isEmpty, diff --git a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift index 8eea1bdb22..722d7203f7 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift @@ -209,119 +209,50 @@ extension SyncCoordinator { logger.debug("DB lookup: selfNodeName='\(selfNodeName)', targetSender=\(parsed.targetSender), hash=\(parsed.messageHash)") - func queuePending() async { - await dependencies.reactionService.queuePendingReaction( - parsed: parsed, - channelIndex: channelIndex, - senderNodeName: senderName, + if let targetMessage = try? await dependencies.dataStore.findChannelMessageForReaction( + radioID: radioID, + channelIndex: channelIndex, + parsedReaction: parsed, + localNodeName: selfNodeName.isEmpty ? nil : selfNodeName, + timestampWindow: timestampWindow, + limit: 200 + ) { + let targetMessageID = targetMessage.id + let reactionDTO = ReactionDTO( + messageID: targetMessageID, + emoji: parsed.emoji, + senderName: senderName, + messageHash: parsed.messageHash, rawText: text, - radioID: radioID - ) - } - - let windowedMatch: MessageDTO? - do { - windowedMatch = try await dependencies.dataStore.findChannelMessageForReaction( - radioID: radioID, - channelIndex: channelIndex, - parsedReaction: parsed, - localNodeName: selfNodeName.isEmpty ? nil : selfNodeName, - timestampWindow: timestampWindow, - limit: 200 - ) - } catch { - await queuePending() - return true - } - if let windowedMatch { - await attachChannelReaction( - to: windowedMatch, - parsed: parsed, - text: text, channelIndex: channelIndex, - senderName: senderName, - selfNodeName: selfNodeName, - radioID: radioID, - dependencies: dependencies + radioID: radioID ) - return true - } + if await persistReactionIfNew(reactionDTO, dependencies: dependencies) { + if let target = targetMessage.channelReactionTarget(localNodeName: selfNodeName.isEmpty ? nil : selfNodeName) { + // Index for future reactions (pending matches not needed here since + // message exists in DB, so pending reactions would also match via DB fallback) + _ = await dependencies.reactionService.indexMessage( + id: targetMessageID, + channelIndex: channelIndex, + target: target + ) + } + + logger.debug("Saved reaction \(parsed.emoji) to message \(targetMessageID) via DB lookup") + } - let datagramMatch: MessageDTO? - do { - datagramMatch = try await dependencies.dataStore.findChannelDatagramForReaction( - radioID: radioID, - channelIndex: channelIndex, - parsedReaction: parsed - ) - } catch { - await queuePending() - return true - } - if let datagramMatch { - await attachChannelReaction( - to: datagramMatch, - parsed: parsed, - text: text, - channelIndex: channelIndex, - senderName: senderName, - selfNodeName: selfNodeName, - radioID: radioID, - dependencies: dependencies - ) return true } - await queuePending() - return true - } - - private func attachChannelReaction( - to targetMessage: MessageDTO, - parsed: ParsedReaction, - text: String, - channelIndex: UInt8, - senderName: String, - selfNodeName: String, - radioID: UUID, - dependencies: SyncDependencies - ) async { - let reactionDTO = ReactionDTO( - messageID: targetMessage.id, - emoji: parsed.emoji, - senderName: senderName, - messageHash: parsed.messageHash, - rawText: text, + // Queue reaction for later matching when target message arrives + await dependencies.reactionService.queuePendingReaction( + parsed: parsed, channelIndex: channelIndex, + senderNodeName: senderName, + rawText: text, radioID: radioID ) - guard await persistReactionIfNew(reactionDTO, dependencies: dependencies) else { return } - if let target = targetMessage.mcoImageReactionTarget() { - _ = await dependencies.reactionService.indexMessage( - id: targetMessage.id, - channelIndex: channelIndex, - senderName: target.senderName, - text: targetMessage.text, - timestamp: targetMessage.reactionTimestamp, - messageHash: target.messageHash - ) - } else { - let targetSenderName: String? = if targetMessage.direction == .outgoing { - selfNodeName.isEmpty ? nil : selfNodeName - } else { - targetMessage.senderNodeName - } - if let targetSenderName { - _ = await dependencies.reactionService.indexMessage( - id: targetMessage.id, - channelIndex: channelIndex, - senderName: targetSenderName, - text: targetMessage.text, - timestamp: targetMessage.reactionTimestamp - ) - } - } - logger.debug("Saved reaction \(parsed.emoji) to message \(targetMessage.id) via DB lookup") + return true } /// Computes a bounded timestamp window around the given time for reaction matching. diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift index 6d7cc52a32..c0a665d273 100644 --- a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift @@ -21,12 +21,6 @@ public enum MCOImageCodec { version(in: text.trimmingCharacters(in: .whitespacesAndNewlines)) == v4Version } - /// A channel row whose text is MCOimg. Group data and a channel text packet - /// with an `im3:` or `im4:` body are the same stored shape. - public static func isChannelMCOImage(channelIndex: UInt8?, text: String) -> Bool { - channelIndex != nil && isMCOImageText(text) - } - public static func content(from text: String) -> MCOImageContent? { let text = text.trimmingCharacters(in: .whitespacesAndNewlines) guard let version = version(in: text) else { return nil } diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift index 8e38d4a437..252dfbc9b3 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift @@ -128,7 +128,7 @@ struct MCOImageBinarySendTests { #expect(message.text == fixture) #expect(message.senderNodeName == "Radio") #expect(!message.isDatagramMCOImage) - #expect(message.mcoImageReactionTarget() != nil) + #expect(message.channelReactionTarget(localNodeName: nil) != nil) try await service.sendPendingChannelMessage(messageID: message.id) #expect(await session.sendChannelDataInvocations.isEmpty) let call = try #require(await session.sendChannelMessageInvocations.first) diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift index ae766c3a8c..1f1d49736a 100644 --- a/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift @@ -121,7 +121,7 @@ struct MCOImageReceiveIntegrationTests { senderPrefix: nil, senderTimestamp: 0, textType: MeshTextType.plain.rawValue, - wireText: Data(blockedText.utf8) + wireText: Data("\(sender): \(blockedText)".utf8) ), arrivedAt: Date(), body: "blocked", @@ -147,6 +147,25 @@ struct MCOImageReceiveIntegrationTests { #expect(messages.first?.senderNodeName == sender) } + @Test + func `a sender Text Rule blocks a datagram MCOimg from that sender`() async throws { + let opened = try await openChannel() + defer { Task { await opened.services.tearDown() } } + let channel = try #require(try await opened.store.fetchChannel(radioID: opened.radioID, index: opened.channel.index)) + var preference = TextRulesPreference() + preference.setSelection(.all, for: TextRulesPreference.channelKind(isPublic: channel.isPublicChannel, name: channel.name)) + preference.append(.init(phrase: "Peer", lookIn: .sender, match: .wholeField)) + + for sender in ["Peer", "Other"] { + let packet = datagram(channel: channel, sender: sender, payload: Data([0x14, 0, 0, 0, 0])) + await opened.handler(packet, channel, .live, opened.scope, preference, Date()) + } + + let messages = try await opened.store.fetchMessages(radioID: opened.radioID, channelIndex: channel.index) + #expect(messages.map(\.senderNodeName) == ["Other"]) + #expect(try await opened.store.recentlyBlockedMessages().map(\.sender) == ["Peer"]) + } + @Test func `two MCOimg pushes more than a minute apart stay one row and take the later RX path`() async throws { let opened = try await openChannel() @@ -288,9 +307,9 @@ struct MCOImageReceiveIntegrationTests { let datagram = try #require(messages.first { $0.id != textRow.id }) #expect(kept.pathNodes == Data([0x31])) #expect(kept.pathLength == 1) - #expect(kept.isDatagramPathMCOImage == false) + #expect(kept.isDatagramMCOImage == false) #expect(datagram.senderTimestamp == 0) - #expect(datagram.isDatagramPathMCOImage) + #expect(datagram.isDatagramMCOImage) } @Test diff --git a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift index 3f35e2d528..31f02b186b 100644 --- a/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift +++ b/MC1Services/Tests/MC1ServicesTests/Mocks/MockPersistenceStore.swift @@ -226,54 +226,21 @@ public actor MockPersistenceStore: PersistenceStoreProtocol { timestampWindow: ClosedRange, limit: Int ) async throws -> MessageDTO? { + let wanted = ChannelReactionTarget(senderName: parsedReaction.targetSender, messageHash: parsedReaction.messageHash) + let isWanted = { (candidate: MessageDTO) in candidate.channelReactionTarget(localNodeName: localNodeName) == wanted } let candidates = try await fetchChannelMessageCandidates( radioID: radioID, channelIndex: channelIndex, timestampWindow: timestampWindow, limit: limit ) - - for candidate in candidates { - guard !candidate.isDatagramMCOImage else { continue } - if candidate.direction == .outgoing { - guard let localNodeName, parsedReaction.targetSender == localNodeName else { - continue - } - } else { - guard candidate.senderNodeName == parsedReaction.targetSender else { - continue - } - } - - let hash = ReactionParser.generateMessageHash( - text: candidate.text, - timestamp: candidate.reactionTimestamp - ) - guard hash == parsedReaction.messageHash else { continue } - - return candidate - } - - return nil - } - - public func findChannelDatagramForReaction( - radioID: UUID, - channelIndex: UInt8, - parsedReaction: ParsedReaction - ) async throws -> MessageDTO? { - if let error = stubbedFetchMessageError { - throw error + if let match = candidates.first(where: isWanted) { + return match } return messages.values - .filter { $0.radioID == radioID && $0.channelIndex == channelIndex } + .filter { $0.radioID == radioID && $0.channelIndex == channelIndex && $0.isDatagramMCOImage } .sorted { $0.createdAt > $1.createdAt } - .first { candidate in - guard candidate.isDatagramMCOImage, - let target = candidate.mcoImageReactionTarget() else { return false } - return target.senderName == parsedReaction.targetSender - && target.messageHash == parsedReaction.messageHash - } + .first(where: isWanted) } public func fetchChannelMessageCandidates( diff --git a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift index 06461c967c..5e5525b9ab 100644 --- a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift @@ -1110,12 +1110,8 @@ struct PersistenceStoreTests { try await store.saveMessage(older) try await store.saveMessage(newer) - let found = try await store.findChannelDatagramForReaction( - radioID: device.id, channelIndex: 0, parsedReaction: parsed - ) - #expect(found?.id == newer.id) let now = UInt32(Date().timeIntervalSince1970) - let missed = try await store.findChannelMessageForReaction( + let found = try await store.findChannelMessageForReaction( radioID: device.id, channelIndex: 0, parsedReaction: parsed, @@ -1123,11 +1119,11 @@ struct PersistenceStoreTests { timestampWindow: (now - 300)...(now + 300), limit: 200 ) - #expect(missed == nil) + #expect(found?.id == newer.id) } @Test - func `Timed channel MCOimg matches in the window and a zero sender timestamp uses the untimed hash`() async throws { + func `Group-text MCOimg takes the timed hash and datagram MCOimg the untimed hash`() async throws { let store = try await createTestStore() let device = createTestDevice() try await store.saveDevice(device) @@ -1146,11 +1142,10 @@ struct PersistenceStoreTests { ) timed.senderTimestamp = nil timed.timestampCorrected = false - var datagram = datagramImage( + let datagram = datagramImage( radioID: device.id, channelIndex: 2, text: text, sender: sender, createdAt: Date(timeIntervalSince1970: TimeInterval(timestamp)) ) - datagram.timestamp = timestamp try await store.saveMessage(timed) try await store.saveMessage(datagram) @@ -1168,28 +1163,24 @@ struct PersistenceStoreTests { radioID: device.id, channelIndex: 1, parsedReaction: untimedParsed, localNodeName: "Local", timestampWindow: window, limit: 200 ) - let missedDatagram = try await store.findChannelDatagramForReaction( - radioID: device.id, channelIndex: 1, parsedReaction: untimedParsed - ) - #expect(foundTimed?.id == timed.id) - #expect(missedUntimed == nil) - #expect(missedDatagram == nil) - - let windowedDatagram = try await store.findChannelMessageForReaction( + let foundDatagram = try await store.findChannelMessageForReaction( radioID: device.id, channelIndex: 2, parsedReaction: untimedParsed, localNodeName: "Local", timestampWindow: window, limit: 200 ) - let foundDatagram = try await store.findChannelDatagramForReaction( - radioID: device.id, channelIndex: 2, parsedReaction: untimedParsed + let missedTimed = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 2, parsedReaction: timedParsed, + localNodeName: "Local", timestampWindow: window, limit: 200 ) - #expect(windowedDatagram == nil) + #expect(foundTimed?.id == timed.id) + #expect(missedUntimed == nil) #expect(foundDatagram?.id == datagram.id) + #expect(missedTimed == nil) } @Test func `Outgoing datagram MCOimg keeps the stored sender name after a rename`() async throws { let store = try await createTestStore() - var device = createTestDevice().copy { $0.nodeName = "Painter" } + let device = createTestDevice() try await store.saveDevice(device) let text = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) let image = MessageDTO.testChannelMessage( @@ -1203,25 +1194,25 @@ struct PersistenceStoreTests { senderNodeName: "Painter" ) try await store.saveMessage(image) - device = device.copy { $0.nodeName = "Other" } - try await store.saveDevice(device) let hash = try ReactionParser.generateUntimedHash(MCOImageTransport.dataField(text: text, senderName: "Painter")) let parsed = try #require(ReactionParser.parse("@[Painter]👍\n\(hash)")) let renamed = try #require(ReactionParser.parse("@[Other]👍\n\(hash)")) - let found = try await store.findChannelDatagramForReaction( - radioID: device.id, channelIndex: 0, parsedReaction: parsed + let window = UInt32(1_000_000 - 300)...UInt32(1_000_000 + 300) + let found = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 0, parsedReaction: parsed, + localNodeName: "Other", timestampWindow: window, limit: 200 ) - let missed = try await store.findChannelDatagramForReaction( - radioID: device.id, channelIndex: 0, parsedReaction: renamed + let missed = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 0, parsedReaction: renamed, + localNodeName: "Other", timestampWindow: window, limit: 200 ) #expect(found?.id == image.id) #expect(missed == nil) - #expect(try await store.fetchDevice(radioID: device.radioID)?.nodeName == "Other") } @Test - func `Group text outside the window does not match and an empty sender does not admit`() async throws { + func `Group text outside the window does not match`() async throws { let store = try await createTestStore() let device = createTestDevice() try await store.saveDevice(device) @@ -1235,16 +1226,7 @@ struct PersistenceStoreTests { status: .delivered, senderNodeName: "Ada" ) - var empty = try datagramImage( - radioID: device.id, - channelIndex: 0, - text: MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])), - sender: "", - createdAt: Date(timeIntervalSince1970: 100) - ) - empty.senderNodeName = "" try await store.saveMessage(text) - try await store.saveMessage(empty) let parsed = try #require(ReactionParser.parse( ReactionService().buildReactionText( @@ -1257,17 +1239,6 @@ struct PersistenceStoreTests { localNodeName: "Local", timestampWindow: (now - 300)...(now + 300), limit: 200 ) #expect(found == nil) - let admission = try await store.admitReaction(ReactionDTO( - messageID: empty.id, - emoji: "👍", - senderName: "Bea", - messageHash: "aaaaa", - rawText: "@[]👍\naaaaa", - channelIndex: empty.channelIndex, - radioID: device.id - )) - #expect(admission == nil) - #expect(try await store.fetchReactions(for: empty.id).isEmpty) } @Test @@ -1316,6 +1287,11 @@ struct PersistenceStoreTests { senderNodeName: sender ) message.senderTimestamp = 0 + message.timestampCorrected = true + message.deduplicationKey = try? DeduplicationKey.channelMCOImage( + channelIndex: channelIndex, + dataField: MCOImageTransport.dataField(text: text, senderName: sender) + ) return message } diff --git a/MC1Services/Tests/MC1ServicesTests/Services/MessageLRUCacheTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/MessageLRUCacheTests.swift index 4607286c96..116c72c307 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/MessageLRUCacheTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/MessageLRUCacheTests.swift @@ -12,9 +12,7 @@ struct MessageLRUCacheTests { await cache.index( messageID: messageID, channelIndex: 0, - senderName: "Node", - text: "Hello", - timestamp: 1_704_067_200 + target: ChannelReactionTarget(senderName: "Node", text: "Hello", timestamp: 1_704_067_200) ) let hash = ReactionParser.generateMessageHash(text: "Hello", timestamp: 1_704_067_200) @@ -22,8 +20,6 @@ struct MessageLRUCacheTests { #expect(candidates.count == 1) #expect(candidates.first?.messageID == messageID) - #expect(candidates.first?.text == "Hello") - #expect(candidates.first?.timestamp == 1_704_067_200) } @Test @@ -44,9 +40,7 @@ struct MessageLRUCacheTests { await cache.index( messageID: UUID(), channelIndex: 0, - senderName: "Node\(i)", - text: "Message \(i)", - timestamp: UInt32(i) + target: ChannelReactionTarget(senderName: "Node\(i)", text: "Message \(i)", timestamp: UInt32(i)) ) } @@ -58,9 +52,7 @@ struct MessageLRUCacheTests { await cache.index( messageID: UUID(), channelIndex: 0, - senderName: "Node3", - text: "Message 3", - timestamp: 3 + target: ChannelReactionTarget(senderName: "Node3", text: "Message 3", timestamp: 3) ) let after = await cache.lookup(channelIndex: 0, senderName: "Node0", messageHash: hash0) @@ -75,9 +67,7 @@ struct MessageLRUCacheTests { await cache.index( messageID: messageID, channelIndex: 0, - senderName: "Node", - text: "Hello", - timestamp: 1_704_067_200 + target: ChannelReactionTarget(senderName: "Node", text: "Hello", timestamp: 1_704_067_200) ) let hash = ReactionParser.generateMessageHash(text: "Hello", timestamp: 1_704_067_200) @@ -102,17 +92,13 @@ struct MessageLRUCacheTests { await cache.index( messageID: id1, channelIndex: 0, - senderName: "Node", - text: "Hello", - timestamp: 1_704_067_200 + target: ChannelReactionTarget(senderName: "Node", text: "Hello", timestamp: 1_704_067_200) ) await cache.index( messageID: id2, channelIndex: 0, - senderName: "Node", - text: "Hello", - timestamp: 1_704_067_200 + target: ChannelReactionTarget(senderName: "Node", text: "Hello", timestamp: 1_704_067_200) ) let hash = ReactionParser.generateMessageHash(text: "Hello", timestamp: 1_704_067_200) @@ -136,9 +122,7 @@ struct MessageLRUCacheTests { await cache.index( messageID: id, channelIndex: 0, - senderName: "Node", - text: "Hello", - timestamp: 1_704_067_200 + target: ChannelReactionTarget(senderName: "Node", text: "Hello", timestamp: 1_704_067_200) ) } @@ -164,18 +148,14 @@ struct MessageLRUCacheTests { await cache.index( messageID: messageID, channelIndex: 0, - senderName: "Node", - text: "Hello", - timestamp: 1_704_067_200 + target: ChannelReactionTarget(senderName: "Node", text: "Hello", timestamp: 1_704_067_200) ) // Re-index same message await cache.index( messageID: messageID, channelIndex: 0, - senderName: "Node", - text: "Hello", - timestamp: 1_704_067_200 + target: ChannelReactionTarget(senderName: "Node", text: "Hello", timestamp: 1_704_067_200) ) let hash = ReactionParser.generateMessageHash(text: "Hello", timestamp: 1_704_067_200) diff --git a/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift index 2e5c5a81c9..74bd6892da 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/ReactionServiceTests.swift @@ -95,9 +95,7 @@ struct ReactionServiceTests { await service.indexMessage( id: messageID, channelIndex: 0, - senderName: "Node", - text: "Hello world", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "Node", text: "Hello world", timestamp: timestamp) ) let reactionText = service.buildReactionText( @@ -139,9 +137,7 @@ struct ReactionServiceTests { _ = await service.indexMessage( id: id1, channelIndex: 0, - senderName: "Node", - text: "Same message", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "Node", text: "Same message", timestamp: timestamp) ) // Small delay to ensure different indexedAt times @@ -150,9 +146,7 @@ struct ReactionServiceTests { _ = await service.indexMessage( id: id2, channelIndex: 0, - senderName: "Node", - text: "Same message", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "Node", text: "Same message", timestamp: timestamp) ) // Build reaction for the message @@ -202,9 +196,7 @@ struct ReactionServiceTests { let matches = await service.indexMessage( id: messageID, channelIndex: 0, - senderName: "AlphaNode", - text: "Hello world", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "AlphaNode", text: "Hello world", timestamp: timestamp) ) #expect(matches.count == 1) @@ -242,9 +234,7 @@ struct ReactionServiceTests { let matches = await service.indexMessage( id: messageID, channelIndex: 0, - senderName: "AlphaNode", - text: "Hello world", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "AlphaNode", text: "Hello world", timestamp: timestamp) ) #expect(matches.count == 3) @@ -280,9 +270,7 @@ struct ReactionServiceTests { let matches = await service.indexMessage( id: messageID, channelIndex: 0, - senderName: "AlphaNode", - text: "Different text", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "AlphaNode", text: "Different text", timestamp: timestamp) ) // Should NOT match because hash is different @@ -320,9 +308,7 @@ struct ReactionServiceTests { let matches = await service.indexMessage( id: messageID, channelIndex: 0, - senderName: "AlphaNode", - text: "Hello world", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "AlphaNode", text: "Hello world", timestamp: timestamp) ) #expect(matches.isEmpty) @@ -356,9 +342,7 @@ struct ReactionServiceTests { let matchesChannel1 = await service.indexMessage( id: messageID, channelIndex: 1, - senderName: "AlphaNode", - text: "Hello world", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "AlphaNode", text: "Hello world", timestamp: timestamp) ) #expect(matchesChannel1.isEmpty) @@ -367,9 +351,7 @@ struct ReactionServiceTests { let matchesChannel0 = await service.indexMessage( id: messageID, channelIndex: 0, - senderName: "AlphaNode", - text: "Hello world", - timestamp: timestamp + target: ChannelReactionTarget(senderName: "AlphaNode", text: "Hello world", timestamp: timestamp) ) #expect(matchesChannel0.count == 1) @@ -578,61 +560,4 @@ struct ReactionServiceTests { #expect(matches.isEmpty) } - - @Test - func `Indexing a datagram hash returns that pending reaction and leaves the text reaction`() async throws { - let service = ReactionService() - let radioID = UUID() - let timestamp: UInt32 = 1_704_067_200 - let imageText = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) - let sender = "Ada" - let hash = try ReactionParser.generateUntimedHash( - MCOImageTransport.dataField(text: imageText, senderName: sender) - ) - let imageReactionText = "@[\(sender)]👍\n\(hash)" - let imageParsed = try #require(ReactionParser.parse(imageReactionText)) - await service.queuePendingReaction( - parsed: imageParsed, - channelIndex: 0, - senderNodeName: "Bea", - rawText: imageReactionText, - radioID: radioID - ) - - let textReactionText = service.buildReactionText( - emoji: "🔥", - targetSender: sender, - targetText: "Hello world", - targetTimestamp: timestamp - ) - let textParsed = try #require(ReactionParser.parse(textReactionText)) - await service.queuePendingReaction( - parsed: textParsed, - channelIndex: 0, - senderNodeName: "Bea", - rawText: textReactionText, - radioID: radioID - ) - - let imageMatches = await service.indexMessage( - id: UUID(), - channelIndex: 0, - senderName: sender, - text: imageText, - timestamp: 0, - messageHash: hash - ) - #expect(imageMatches.count == 1) - #expect(imageMatches.first?.parsed.emoji == "👍") - - let textMatches = await service.indexMessage( - id: UUID(), - channelIndex: 0, - senderName: sender, - text: "Hello world", - timestamp: timestamp - ) - #expect(textMatches.count == 1) - #expect(textMatches.first?.parsed.emoji == "🔥") - } } diff --git a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift index 3fb6a51efc..ed4db0eed2 100644 --- a/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift @@ -65,9 +65,7 @@ struct SyncCoordinatorChannelMCOImageReactionTests { let matches = await services.reactionService.indexMessage( id: UUID(), channelIndex: channelIndex, - senderName: "Ada", - text: "Plain channel text", - timestamp: textTimestamp + target: ChannelReactionTarget(senderName: "Ada", text: "Plain channel text", timestamp: textTimestamp) ) #expect(matches.count == 1) #expect(matches.first?.parsed.emoji == "🔥") @@ -137,9 +135,7 @@ struct SyncCoordinatorChannelMCOImageReactionTests { let matches = await services.reactionService.indexMessage( id: UUID(), channelIndex: channel.index, - senderName: sender, - text: "Plain channel text", - timestamp: 1_700_000_100 + target: ChannelReactionTarget(senderName: sender, text: "Plain channel text", timestamp: 1_700_000_100) ) #expect(matches.count == 1) } From 751a2830396e4014d9fe82f894b2d06915f32e8f Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:49:12 -0800 Subject: [PATCH 10/13] fix: skip MCOimg bodies in Text Rules matching - A picture's body is Base91 text, so a message rule could match random characters and block an unrelated picture - Sender rules still match a picture's sender in channels, DMs, and room posts - Add a test that covers both cases --- .../MC1Services/Models/TextRulesPreference.swift | 2 ++ .../TextRulesPreferenceTests.swift | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift index 92790d5879..09acaa0bec 100644 --- a/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift +++ b/MC1Services/Sources/MC1Services/Models/TextRulesPreference.swift @@ -184,7 +184,9 @@ public struct TextRulesPreference: Sendable, Codable, Equatable { } } + /// An MCOimg body is Base91, not words, so a picture matches on its sender only. public func firstMatch(body: String?, sender: String?) -> RuleMatch? { + let body = body.flatMap { MCOImageCodec.isMCOImageText($0) ? nil : $0 } for rule in rules { let bodyHighlights = rule.lookIn == .sender ? [] : Self.highlights(in: body, for: rule) let senderHighlights = rule.lookIn == .message ? [] : Self.highlights(in: sender, for: rule) diff --git a/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift index fc7a61e21a..351e0b316f 100644 --- a/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/TextRulesPreferenceTests.swift @@ -50,6 +50,21 @@ struct TextRulesPreferenceTests { #expect(preference.firstMatch(body: nil, sender: sender)?.rule == first) } + @Test + func `an MCOimg body never matches a message rule but its sender still does`() throws { + var preference = TextRulesPreference() + let picture = try MCOImageCodec.text(fromAppPayload: Data([0x14, 0, 0, 0, 0])) + let phrase = String(picture.dropFirst("im4:".count).prefix(3)) + let bodyRule = TextRulesPreference.Rule(phrase: phrase, lookIn: .messageOrSender, match: .contains) + preference.append(bodyRule) + #expect(preference.firstMatch(body: "text \(phrase) text", sender: nil)?.rule == bodyRule) + #expect(preference.firstMatch(body: picture, sender: nil) == nil) + + let senderRule = TextRulesPreference.Rule(phrase: "Peer", lookIn: .sender, match: .wholeField) + preference.append(senderRule) + #expect(preference.firstMatch(body: picture, sender: "Peer")?.rule == senderRule) + } + @Test func `whole field keeps significant spaces and substring highlights expand to characters`() throws { var preference = TextRulesPreference() From 8bb9ee44cd74dd8eb8055b8edb9f3af28c1d1a38 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:19:03 -0800 Subject: [PATCH 11/13] bump marketing version to 1.7.3 --- project.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/project.yml b/project.yml index 89440c7060..26069ad0ce 100644 --- a/project.yml +++ b/project.yml @@ -75,7 +75,7 @@ targets: base: SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD: YES ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon - MARKETING_VERSION: 1.7.2 + MARKETING_VERSION: 1.7.3 CURRENT_PROJECT_VERSION: 1 VERSIONING_SYSTEM: apple-generic TARGETED_DEVICE_FAMILY: "1,2" @@ -113,7 +113,7 @@ targets: settings: base: INFOPLIST_FILE: MC1Tests/Info.plist - MARKETING_VERSION: 1.7.2 + MARKETING_VERSION: 1.7.3 CURRENT_PROJECT_VERSION: 1 VERSIONING_SYSTEM: apple-generic TEST_HOST: "$(BUILT_PRODUCTS_DIR)/MC1.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/MC1" @@ -127,7 +127,7 @@ targets: - path: Shared settings: base: - MARKETING_VERSION: 1.7.2 + MARKETING_VERSION: 1.7.3 CURRENT_PROJECT_VERSION: 1 VERSIONING_SYSTEM: apple-generic TARGETED_DEVICE_FAMILY: "1,2" From a30abf4fdd12c8823f357b77466951083544ad92 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:17:46 -0800 Subject: [PATCH 12/13] fix: do not mark a datagram MCOimg as corrected - An incoming datagram MCOimg stores the receipt time and sets timestampCorrected, because the packet has no sender clock - The footer used that flag and showed the time as adjusted - Show the correction only when the message has a wire send time --- .../Services/MessageFragmentBuilder.swift | 2 +- .../Chats/Models/MessageFragmentBuilderTests.swift | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift index 2cc203270d..854011a5cc 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift @@ -252,7 +252,7 @@ public enum MessageFragmentBuilder { regionToShow: regionToShow, regionMatchNames: regionMatchNames, sendTimeToShow: sendTimeToShow, - sendTimeWasCorrected: message.timestampCorrected, + sendTimeWasCorrected: message.timestampCorrected && message.hasWireSendTime, showStatusRow: message.isOutgoing, status: message.status, isChannelMessage: message.isChannelMessage, diff --git a/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift b/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift index 8e4d9cefbb..cdccfd1eff 100644 --- a/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift +++ b/MC1Tests/Views/Chats/Models/MessageFragmentBuilderTests.swift @@ -461,6 +461,19 @@ struct MessageFragmentBuilderTests { #expect(item.footer.sendTimeWasCorrected == true) } + @Test + func `footer does not flag correction on an incoming datagram MCOimg`() { + var message = makeIncomingMessage( + timestamp: 1_700_000_000, senderTimestamp: 0, timestampCorrected: true + ) + message.channelIndex = 0 + message.text = "im4:pixel" + let item = MessageFragmentBuilder.makeItem( + for: message, inputs: makeInputs(messageID: message.id), envInputs: makeEnvInputs() + ) + #expect(item.footer.sendTimeWasCorrected == false) + } + // MARK: - Hash propagation regression @Test From a7ffef6a1612ac855f3947512ef7043629a74470 Mon Sep 17 00:00:00 2001 From: Avi0n <14863961+Avi0n@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:28:50 -0800 Subject: [PATCH 13/13] feat: improve the pixel paint editor Drawings could be lost to a stray tap, and a drawing that was too large was only reported after Send. - Show the encoded size against the limit under the canvas and disable Send when the drawing is too large - Add undo and redo, and make Clear undoable - Ask before Cancel discards a drawing that is not blank - Add eraser and fill tools, a grid toggle, and a preview - Replace the scroll view with a layout that fits the screen - Stop a stroke that leaves the canvas from joining the re-entry point - Make the canvas one VoiceOver element with a movable cursor --- MC1/Resources/Generated/L10n.swift | 44 ++++- .../Localization/de.lproj/Chats.strings | 53 ++++- .../Localization/en.lproj/Chats.strings | 53 ++++- .../Localization/es.lproj/Chats.strings | 53 ++++- .../Localization/fr.lproj/Chats.strings | 53 ++++- .../Localization/it.lproj/Chats.strings | 53 ++++- .../Localization/ko.lproj/Chats.strings | 53 ++++- .../Localization/nl.lproj/Chats.strings | 53 ++++- .../Localization/pl.lproj/Chats.strings | 53 ++++- .../Localization/pt.lproj/Chats.strings | 53 ++++- .../Localization/ru.lproj/Chats.strings | 53 ++++- .../Localization/uk.lproj/Chats.strings | 53 ++++- .../Localization/zh-Hans.lproj/Chats.strings | 53 ++++- .../Chats/ChatConversationInputBar.swift | 16 +- MC1/Views/Chats/MCOimg/PixelPaintCanvas.swift | 108 ++++++++++ .../Chats/MCOimg/PixelPaintControls.swift | 82 ++++++++ .../MCOimg/PixelPaintDraft+Editing.swift | 144 ++++++++++++++ MC1/Views/Chats/MCOimg/PixelPaintDraft.swift | 51 ++--- MC1/Views/Chats/MCOimg/PixelPaintEditor.swift | 185 +++++++----------- .../Chats/MCOimg/PixelPaintStatusRow.swift | 74 +++++++ MC1/Views/Chats/MCOimg/PixelPaintTool.swift | 21 ++ .../MC1Services/Services/AppStorageKey.swift | 3 + .../Views/Chats/PixelPaintDraftTests.swift | 130 ++++++++++++ .../Chats/PixelPaintPresentationTests.swift | 142 +++++++++++++- 24 files changed, 1447 insertions(+), 189 deletions(-) create mode 100644 MC1/Views/Chats/MCOimg/PixelPaintCanvas.swift create mode 100644 MC1/Views/Chats/MCOimg/PixelPaintControls.swift create mode 100644 MC1/Views/Chats/MCOimg/PixelPaintDraft+Editing.swift create mode 100644 MC1/Views/Chats/MCOimg/PixelPaintStatusRow.swift create mode 100644 MC1/Views/Chats/MCOimg/PixelPaintTool.swift diff --git a/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index ae613290e0..2e2bf2a48c 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -559,12 +559,26 @@ public enum L10n { public static let title = L10n.tr("Chats", "chats.malwareWarning.title", fallback: "Link flagged as suspicious") } public enum Mcoimg { + /// VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit + public static func budget(_ p1: Int, _ p2: Int) -> String { + return L10n.tr("Chats", "chats.mcoimg.budget", p1, p2, fallback: "Drawing size %1$d of %2$d bytes") + } /// VoiceOver name for the pixel drawing canvas public static let canvas = L10n.tr("Chats", "chats.mcoimg.canvas", fallback: "Pixel canvas") + /// VoiceOver hint for the pixel canvas + public static let canvasHint = L10n.tr("Chats", "chats.mcoimg.canvasHint", fallback: "Swipe up or down to move. Double-tap to paint.") /// Erases every pixel in the editor public static let clear = L10n.tr("Chats", "chats.mcoimg.clear", fallback: "Clear Drawing") + /// VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name + public static func cursorPosition(_ p1: Int, _ p2: Int, _ p3: Any) -> String { + return L10n.tr("Chats", "chats.mcoimg.cursorPosition", p1, p2, String(describing: p3), fallback: "Column %1$d, row %2$d, %3$@") + } /// Placeholder when an MCOimg payload cannot be decoded public static let damaged = L10n.tr("Chats", "chats.mcoimg.damaged", fallback: "Damaged image") + /// Destructive button that throws the pixel drawing away + public static let discard = L10n.tr("Chats", "chats.mcoimg.discard", fallback: "Discard Drawing") + /// Title of the confirmation shown when cancelling a pixel drawing that is not blank + public static let discardTitle = L10n.tr("Chats", "chats.mcoimg.discardTitle", fallback: "Discard Drawing?") /// Progress label while a pixel drawing is encoded public static let encoding = L10n.tr("Chats", "chats.mcoimg.encoding", fallback: "Encoding drawing") /// Error when a pixel drawing cannot be encoded @@ -573,14 +587,22 @@ public enum L10n { public static let encodingFailedTitle = L10n.tr("Chats", "chats.mcoimg.encodingFailedTitle", fallback: "Unable to Encode") /// Name for an MCOimg in VoiceOver, notifications, and the chat list public static let image = L10n.tr("Chats", "chats.mcoimg.image", fallback: "Pixel drawing") - /// VoiceOver name for one cell; arguments are 1-based column and row - public static func pixel(_ p1: Int, _ p2: Int) -> String { - return L10n.tr("Chats", "chats.mcoimg.pixel", p1, p2, fallback: "Pixel %d, %d") - } + /// VoiceOver action that moves the canvas cursor down one cell + public static let moveDown = L10n.tr("Chats", "chats.mcoimg.moveDown", fallback: "Move down") + /// VoiceOver action that moves the canvas cursor left one cell + public static let moveLeft = L10n.tr("Chats", "chats.mcoimg.moveLeft", fallback: "Move left") + /// VoiceOver action that moves the canvas cursor right one cell + public static let moveRight = L10n.tr("Chats", "chats.mcoimg.moveRight", fallback: "Move right") + /// VoiceOver action that moves the canvas cursor up one cell + public static let moveUp = L10n.tr("Chats", "chats.mcoimg.moveUp", fallback: "Move up") + /// Reapplies the last undone stroke, fill, or clear + public static let redo = L10n.tr("Chats", "chats.mcoimg.redo", fallback: "Redo") /// Sends the open pixel drawing public static let send = L10n.tr("Chats", "chats.mcoimg.send", fallback: "Send") /// Progress label once a pixel drawing has been handed to the conversation public static let sending = L10n.tr("Chats", "chats.mcoimg.sending", fallback: "Sending drawing") + /// Toggle that shows or hides the pixel grid lines + public static let showGrid = L10n.tr("Chats", "chats.mcoimg.showGrid", fallback: "Show Grid") /// Editor title and the compose-menu action for a pixel drawing public static let title = L10n.tr("Chats", "chats.mcoimg.title", fallback: "Pixel Paint") /// Error when a pixel drawing exceeds the conversation limit; arguments are size then limit @@ -591,8 +613,14 @@ public enum L10n { public static func tooLargeChannel(_ p1: Int, _ p2: Int) -> String { return L10n.tr("Chats", "chats.mcoimg.tooLargeChannel", p1, p2, fallback: "Drawing is %d bytes, including your node name; this channel allows %d. Simplify the drawing and try again.") } + /// Shown under the canvas when the encoded drawing exceeds the conversation's limit + public static let tooLargeInline = L10n.tr("Chats", "chats.mcoimg.tooLargeInline", fallback: "Too large to send") /// Alert title when a pixel drawing exceeds the conversation limit public static let tooLargeTitle = L10n.tr("Chats", "chats.mcoimg.tooLargeTitle", fallback: "Drawing Too Large") + /// Label for the pixel editor's tool picker + public static let toolPicker = L10n.tr("Chats", "chats.mcoimg.toolPicker", fallback: "Tool") + /// Restores the pixel drawing to its state before the last stroke, fill, or clear + public static let undo = L10n.tr("Chats", "chats.mcoimg.undo", fallback: "Undo") /// Placeholder when an MCOimg version cannot be shown public static let unsupported = L10n.tr("Chats", "chats.mcoimg.unsupported", fallback: "Unsupported image format") public enum ColorName { @@ -613,6 +641,14 @@ public enum L10n { /// VoiceOver name for a Pixel Paint palette color public static let yellow = L10n.tr("Chats", "chats.mcoimg.colorName.yellow", fallback: "Yellow") } + public enum Tool { + /// Pixel editor tool that paints with the selected colour + public static let brush = L10n.tr("Chats", "chats.mcoimg.tool.brush", fallback: "Brush") + /// Pixel editor tool that paints the background colour + public static let eraser = L10n.tr("Chats", "chats.mcoimg.tool.eraser", fallback: "Eraser") + /// Pixel editor tool that fills a connected area with the selected colour + public static let fill = L10n.tr("Chats", "chats.mcoimg.tool.fill", fallback: "Fill") + } } public enum Mention { public enum Accessibility { diff --git a/MC1/Resources/Localization/de.lproj/Chats.strings b/MC1/Resources/Localization/de.lproj/Chats.strings index 4e5a26bcb2..0bdf554fe0 100644 --- a/MC1/Resources/Localization/de.lproj/Chats.strings +++ b/MC1/Resources/Localization/de.lproj/Chats.strings @@ -1106,8 +1106,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Pixel-Leinwand"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Zeichnung zu groß"; @@ -1130,6 +1128,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Zeichnung wird gesendet"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Bild"; diff --git a/MC1/Resources/Localization/en.lproj/Chats.strings b/MC1/Resources/Localization/en.lproj/Chats.strings index 2a474ac609..f4d659d4d1 100644 --- a/MC1/Resources/Localization/en.lproj/Chats.strings +++ b/MC1/Resources/Localization/en.lproj/Chats.strings @@ -1116,8 +1116,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Pixel canvas"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Drawing Too Large"; @@ -1140,6 +1138,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Sending drawing"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + // MARK: - Image Viewer /* Location: FullScreenImageViewer.swift - Close button label */ diff --git a/MC1/Resources/Localization/es.lproj/Chats.strings b/MC1/Resources/Localization/es.lproj/Chats.strings index ade7c9697b..40ea4b5914 100644 --- a/MC1/Resources/Localization/es.lproj/Chats.strings +++ b/MC1/Resources/Localization/es.lproj/Chats.strings @@ -1106,8 +1106,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Lienzo de píxeles"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Píxel %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Dibujo demasiado grande"; @@ -1130,6 +1128,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Enviando el dibujo"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Imagen"; diff --git a/MC1/Resources/Localization/fr.lproj/Chats.strings b/MC1/Resources/Localization/fr.lproj/Chats.strings index a507ad16f3..30d5b25786 100644 --- a/MC1/Resources/Localization/fr.lproj/Chats.strings +++ b/MC1/Resources/Localization/fr.lproj/Chats.strings @@ -1106,8 +1106,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Canevas de pixels"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Dessin trop volumineux"; @@ -1130,6 +1128,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Envoi du dessin"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Image"; diff --git a/MC1/Resources/Localization/it.lproj/Chats.strings b/MC1/Resources/Localization/it.lproj/Chats.strings index 456ac59f6a..8804b365b4 100644 --- a/MC1/Resources/Localization/it.lproj/Chats.strings +++ b/MC1/Resources/Localization/it.lproj/Chats.strings @@ -1099,8 +1099,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Area di disegno a pixel"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Disegno troppo grande"; @@ -1123,6 +1121,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Invio del disegno"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Immagine"; diff --git a/MC1/Resources/Localization/ko.lproj/Chats.strings b/MC1/Resources/Localization/ko.lproj/Chats.strings index 7b1da445a2..66e68b7fdd 100644 --- a/MC1/Resources/Localization/ko.lproj/Chats.strings +++ b/MC1/Resources/Localization/ko.lproj/Chats.strings @@ -1099,8 +1099,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "픽셀 캔버스"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "픽셀 %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "그림이 너무 큼"; @@ -1123,6 +1121,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "그림 보내는 중..."; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "이미지"; diff --git a/MC1/Resources/Localization/nl.lproj/Chats.strings b/MC1/Resources/Localization/nl.lproj/Chats.strings index 973478c473..35d7730f69 100644 --- a/MC1/Resources/Localization/nl.lproj/Chats.strings +++ b/MC1/Resources/Localization/nl.lproj/Chats.strings @@ -1106,8 +1106,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Pixelcanvas"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Pixel %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Tekening te groot"; @@ -1130,6 +1128,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Tekening wordt verzonden"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Afbeelding"; diff --git a/MC1/Resources/Localization/pl.lproj/Chats.strings b/MC1/Resources/Localization/pl.lproj/Chats.strings index 8101733fd1..ec8e26318e 100644 --- a/MC1/Resources/Localization/pl.lproj/Chats.strings +++ b/MC1/Resources/Localization/pl.lproj/Chats.strings @@ -1098,8 +1098,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Płótno pikseli"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Piksel %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Rysunek za duży"; @@ -1122,6 +1120,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Wysyłanie rysunku"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Obraz"; diff --git a/MC1/Resources/Localization/pt.lproj/Chats.strings b/MC1/Resources/Localization/pt.lproj/Chats.strings index 8a48344818..989518c2e6 100644 --- a/MC1/Resources/Localization/pt.lproj/Chats.strings +++ b/MC1/Resources/Localization/pt.lproj/Chats.strings @@ -1099,8 +1099,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Área de píxeis"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Píxel %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Desenho demasiado grande"; @@ -1123,6 +1121,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "A enviar o desenho..."; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Imagem"; diff --git a/MC1/Resources/Localization/ru.lproj/Chats.strings b/MC1/Resources/Localization/ru.lproj/Chats.strings index c32d5164bc..676d7494d4 100644 --- a/MC1/Resources/Localization/ru.lproj/Chats.strings +++ b/MC1/Resources/Localization/ru.lproj/Chats.strings @@ -1097,8 +1097,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Пиксельный холст"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Пиксель %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Рисунок слишком большой"; @@ -1121,6 +1119,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Отправка рисунка"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Изображение"; diff --git a/MC1/Resources/Localization/uk.lproj/Chats.strings b/MC1/Resources/Localization/uk.lproj/Chats.strings index dfeb8d8c00..42fde080bc 100644 --- a/MC1/Resources/Localization/uk.lproj/Chats.strings +++ b/MC1/Resources/Localization/uk.lproj/Chats.strings @@ -1097,8 +1097,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "Піксельне полотно"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "Піксель %d, %d"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "Малюнок занадто великий"; @@ -1121,6 +1119,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "Надсилання малюнка"; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "Зображення"; diff --git a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings index 6fb88cc3c4..8e0dcf1d41 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings @@ -1163,8 +1163,6 @@ /* VoiceOver name for the pixel drawing canvas */ "chats.mcoimg.canvas" = "像素画布"; -/* VoiceOver name for one cell; arguments are 1-based column and row */ -"chats.mcoimg.pixel" = "像素,第 %d 列,第 %d 行"; /* Alert title when a pixel drawing exceeds the conversation limit */ "chats.mcoimg.tooLargeTitle" = "绘图过大"; @@ -1187,6 +1185,57 @@ /* Progress label once a pixel drawing has been handed to the conversation */ "chats.mcoimg.sending" = "正在发送绘图..."; +/* Title of the confirmation shown when cancelling a pixel drawing that is not blank */ +"chats.mcoimg.discardTitle" = "Discard Drawing?"; + +/* Destructive button that throws the pixel drawing away */ +"chats.mcoimg.discard" = "Discard Drawing"; + +/* Restores the pixel drawing to its state before the last stroke, fill, or clear */ +"chats.mcoimg.undo" = "Undo"; + +/* Reapplies the last undone stroke, fill, or clear */ +"chats.mcoimg.redo" = "Redo"; + +/* Label for the pixel editor's tool picker */ +"chats.mcoimg.toolPicker" = "Tool"; + +/* Pixel editor tool that paints with the selected colour */ +"chats.mcoimg.tool.brush" = "Brush"; + +/* Pixel editor tool that paints the background colour */ +"chats.mcoimg.tool.eraser" = "Eraser"; + +/* Pixel editor tool that fills a connected area with the selected colour */ +"chats.mcoimg.tool.fill" = "Fill"; + +/* Toggle that shows or hides the pixel grid lines */ +"chats.mcoimg.showGrid" = "Show Grid"; + +/* VoiceOver label for the drawing size gauge; arguments are the encoded size and the conversation's limit */ +"chats.mcoimg.budget" = "Drawing size %1$d of %2$d bytes"; + +/* Shown under the canvas when the encoded drawing exceeds the conversation's limit */ +"chats.mcoimg.tooLargeInline" = "Too large to send"; + +/* VoiceOver value for the canvas cursor; arguments are 1-based column, 1-based row, and the colour name */ +"chats.mcoimg.cursorPosition" = "Column %1$d, row %2$d, %3$@"; + +/* VoiceOver hint for the pixel canvas */ +"chats.mcoimg.canvasHint" = "Swipe up or down to move. Double-tap to paint."; + +/* VoiceOver action that moves the canvas cursor up one cell */ +"chats.mcoimg.moveUp" = "Move up"; + +/* VoiceOver action that moves the canvas cursor down one cell */ +"chats.mcoimg.moveDown" = "Move down"; + +/* VoiceOver action that moves the canvas cursor left one cell */ +"chats.mcoimg.moveLeft" = "Move left"; + +/* VoiceOver action that moves the canvas cursor right one cell */ +"chats.mcoimg.moveRight" = "Move right"; + /* Location: InlineImageView.swift - Accessibility label for static image */ "chats.inlineImage.imageAccessibility" = "图片"; diff --git a/MC1/Views/Chats/ChatConversationInputBar.swift b/MC1/Views/Chats/ChatConversationInputBar.swift index b2c4320286..9b81f83978 100644 --- a/MC1/Views/Chats/ChatConversationInputBar.swift +++ b/MC1/Views/Chats/ChatConversationInputBar.swift @@ -18,7 +18,7 @@ struct ChatConversationInputBar: View { var body: some View { inputBar .fullScreenCover(isPresented: $isShowingPainter) { - PixelPaintEditor(draft: drawing, onSend: sendDrawing) + PixelPaintEditor(draft: drawing, transport: drawingTransport, senderName: senderName, onSend: sendDrawing) } .onChange(of: conversationType.coordinatorID) { drawing.remove() @@ -65,12 +65,20 @@ struct ChatConversationInputBar: View { isShowingPainter = true } - private func sendDrawing() { + private var drawingTransport: PixelPaintTransport { let isChannel = if case .channel = conversationType { true } else { false } - let transport = PixelPaintTransport( + return PixelPaintTransport( isChannel: isChannel, supportsChannelData: appState.connectedDevice?.supportsChannelData == true ) + } + + private var senderName: String { + appState.connectedDevice?.nodeName ?? "" + } + + private func sendDrawing() { + let transport = drawingTransport let radioID = conversationType.radioID let ready = { appState.connectionState == .ready && appState.connectedDevice?.radioID == radioID @@ -80,7 +88,7 @@ struct ChatConversationInputBar: View { await drawing.run( attempt, transport: transport, - senderName: { appState.connectedDevice?.nodeName ?? "" }, + senderName: { senderName }, isReady: ready, onSend: onSend, onWillSend: onWillSend, diff --git a/MC1/Views/Chats/MCOimg/PixelPaintCanvas.swift b/MC1/Views/Chats/MCOimg/PixelPaintCanvas.swift new file mode 100644 index 0000000000..ad8c7263d8 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/PixelPaintCanvas.swift @@ -0,0 +1,108 @@ +import MC1Services +import SwiftUI + +struct PixelPaintCanvas: View { + let draft: PixelPaintDraft + let showsGrid: Bool + @Environment(\.accessibilityVoiceOverEnabled) private var voiceOverEnabled + @State private var canvasWidth: CGFloat = 0 + @State private var cursorColumn = PixelPaintDraft.side / 2 + @State private var cursorRow = PixelPaintDraft.side / 2 + @State private var hasFilledThisGesture = false + private static let gridOpacity = 0.25 + private static let gridLineWidth: CGFloat = 0.5 + private static let cursorOutlineWidth: CGFloat = 2 + private static let side = PixelPaintDraft.side + + var body: some View { + Canvas { context, size in + let cell = size.width / CGFloat(Self.side) + var pixels = context + pixels.scaleBy(x: cell, y: cell) + MCOImageRenderer.raster(draft.image, origin: .zero, context: &pixels) + if showsGrid { + context.stroke(Self.grid(cell: cell, length: size.width), + with: .color(.primary.opacity(Self.gridOpacity)), lineWidth: Self.gridLineWidth) + } + if voiceOverEnabled { + let cursor = CGRect(x: CGFloat(cursorColumn) * cell, y: CGFloat(cursorRow) * cell, width: cell, height: cell) + context.stroke(Path(cursor), with: .color(.accentColor), lineWidth: Self.cursorOutlineWidth) + } + } + .aspectRatio(1, contentMode: .fit) + .gesture(DragGesture(minimumDistance: 0).onChanged { value in + // Hit testing uses cell edges, matching `MCOImageRenderer` raster origins. + guard canvasWidth > 0 else { return } + apply(x: Int(floor(value.location.x / canvasWidth * Double(Self.side))), + y: Int(floor(value.location.y / canvasWidth * Double(Self.side)))) + }.onEnded { _ in + hasFilledThisGesture = false + draft.endStroke() + }) + .allowsHitTesting(!draft.isSubmitting) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { canvasWidth = $0 } + .sensoryFeedback(.impact(weight: .light), trigger: draft.paintedCellRevision) + .accessibilityElement(children: .ignore) + .accessibilityLabel(L10n.Chats.Chats.Mcoimg.canvas) + .accessibilityValue(L10n.Chats.Chats.Mcoimg.cursorPosition( + cursorColumn + 1, cursorRow + 1, + PixelPaintDraft.colorName(draft.pixels[cursorRow * Self.side + cursorColumn]) + )) + .accessibilityHint(L10n.Chats.Chats.Mcoimg.canvasHint) + .accessibilityIdentifier("pixelPaintCanvas") + .accessibilityAdjustableAction { direction in + switch direction { + case .increment: stepCursor(by: 1) + case .decrement: stepCursor(by: -1) + @unknown default: break + } + } + .accessibilityAction(named: L10n.Chats.Chats.Mcoimg.moveUp) { moveCursor(columns: 0, rows: -1) } + .accessibilityAction(named: L10n.Chats.Chats.Mcoimg.moveDown) { moveCursor(columns: 0, rows: 1) } + .accessibilityAction(named: L10n.Chats.Chats.Mcoimg.moveLeft) { moveCursor(columns: -1, rows: 0) } + .accessibilityAction(named: L10n.Chats.Chats.Mcoimg.moveRight) { moveCursor(columns: 1, rows: 0) } + .accessibilityAction { paintAtCursor() } + } + + private func apply(x: Int, y: Int) { + if draft.tool == .fill { + guard !hasFilledThisGesture else { return } + hasFilledThisGesture = true + draft.fill(x: x, y: y) + } else { + draft.paint(x: x, y: y) + } + } + + private func stepCursor(by delta: Int) { + let last = Self.side * Self.side - 1 + let index = min(max(cursorRow * Self.side + cursorColumn + delta, 0), last) + cursorRow = index / Self.side + cursorColumn = index % Self.side + } + + private func moveCursor(columns: Int, rows: Int) { + cursorColumn = min(max(cursorColumn + columns, 0), Self.side - 1) + cursorRow = min(max(cursorRow + rows, 0), Self.side - 1) + } + + private func paintAtCursor() { + guard !draft.isSubmitting else { return } + draft.endStroke() + apply(x: cursorColumn, y: cursorRow) + hasFilledThisGesture = false + draft.endStroke() + } + + private static func grid(cell: CGFloat, length: CGFloat) -> Path { + var path = Path() + for line in 0...side { + let offset = CGFloat(line) * cell + path.move(to: CGPoint(x: offset, y: 0)) + path.addLine(to: CGPoint(x: offset, y: length)) + path.move(to: CGPoint(x: 0, y: offset)) + path.addLine(to: CGPoint(x: length, y: offset)) + } + return path + } +} diff --git a/MC1/Views/Chats/MCOimg/PixelPaintControls.swift b/MC1/Views/Chats/MCOimg/PixelPaintControls.swift new file mode 100644 index 0000000000..d298e2d4b1 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/PixelPaintControls.swift @@ -0,0 +1,82 @@ +import MC1Services +import SwiftUI + +struct PixelPaintControls: View { + @Bindable var draft: PixelPaintDraft + private static let swatchSize: CGFloat = 44 + private static let ringWidth: CGFloat = 3 + private static let swatchBorderWidth: CGFloat = 1 + private static let paletteColumns = 4 + private static let spacing: CGFloat = 16 + + var body: some View { + VStack(spacing: Self.spacing) { + Picker(L10n.Chats.Chats.Mcoimg.toolPicker, selection: $draft.tool) { + ForEach(PixelPaintTool.allCases, id: \.self) { tool in + Label(tool.title, systemImage: tool.systemImage).tag(tool) + } + } + .pickerStyle(.segmented) + history + palette + } + .disabled(draft.isSubmitting) + .sensoryFeedback(.selection, trigger: draft.selectedColor) + .sensoryFeedback(.selection, trigger: draft.tool) + } + + private var history: some View { + HStack { + Button(L10n.Chats.Chats.Mcoimg.undo, systemImage: "arrow.uturn.backward") { draft.undo() } + .labelStyle(.iconOnly) + .keyboardShortcut("z", modifiers: .command) + .disabled(!draft.canUndo) + .accessibilityIdentifier("pixelPaintUndo") + Button(L10n.Chats.Chats.Mcoimg.redo, systemImage: "arrow.uturn.forward") { draft.redo() } + .labelStyle(.iconOnly) + .keyboardShortcut("z", modifiers: [.command, .shift]) + .disabled(!draft.canRedo) + .accessibilityIdentifier("pixelPaintRedo") + Spacer() + Button(L10n.Chats.Chats.Mcoimg.clear, systemImage: "trash") { draft.clear() } + .disabled(draft.isBlank) + .accessibilityIdentifier("pixelPaintClear") + } + .buttonStyle(.bordered) + .controlSize(.large) + } + + private var palette: some View { + LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: Self.paletteColumns)) { + ForEach(0.. some View { + ZStack { + if isSelected { + Circle().fill(.primary) + Circle().fill(.background).padding(Self.ringWidth) + } + Circle() + .fill(MCOImageRenderer.color(index, profile: PixelPaintDraft.profile)) + .overlay { Circle().strokeBorder(.gray, lineWidth: Self.swatchBorderWidth) } + .padding(Self.ringWidth * 2) + } + .frame(width: Self.swatchSize, height: Self.swatchSize) + .contentShape(Circle()) + } +} diff --git a/MC1/Views/Chats/MCOimg/PixelPaintDraft+Editing.swift b/MC1/Views/Chats/MCOimg/PixelPaintDraft+Editing.swift new file mode 100644 index 0000000000..254f7af16a --- /dev/null +++ b/MC1/Views/Chats/MCOimg/PixelPaintDraft+Editing.swift @@ -0,0 +1,144 @@ +import MC1Services + +extension PixelPaintDraft { + static let historyLimit = 100 + private static let neighborOffsets = [(0, -1), (0, 1), (-1, 0), (1, 0)] + + private static var blank: [Int] { + Array(repeating: background, count: side * side) + } + + var canUndo: Bool { + !undoStack.isEmpty + } + + var canRedo: Bool { + !redoStack.isEmpty + } + + var isBlank: Bool { + pixels.allSatisfy { $0 == Self.background } + } + + func isOverBudget(for transport: PixelPaintTransport) -> Bool { + encodedByteCount.map { $0 > transport.byteLimit } ?? false + } + + func paint(x: Int, y: Int) { + guard !isSubmitting else { return } + guard Self.contains(x: x, y: y) else { + // Re-entering the canvas starts a new segment instead of joining the exit point. + previousCell = nil + return + } + if strokeStart == nil { strokeStart = pixels } + let color = tool == .eraser ? Self.background : selectedColor + let start = previousCell ?? (x, y) + let steps = max(abs(x - start.x), abs(y - start.y)) + var changed = false + for step in 0...steps { + let fraction = steps == 0 ? 0 : Double(step) / Double(steps) + let column = start.x + Int((Double(x - start.x) * fraction).rounded()) + let row = start.y + Int((Double(y - start.y) * fraction).rounded()) + let index = row * Self.side + column + // Equal-value writes still notify every `pixels` observer. + if pixels[index] != color { + pixels[index] = color + changed = true + } + } + if changed { paintedCellRevision &+= 1 } + previousCell = (x, y) + } + + func endStroke() { + if let strokeStart, strokeStart != pixels { + record(strokeStart) + } + previousCell = nil + strokeStart = nil + } + + func fill(x: Int, y: Int) { + guard !isSubmitting, Self.contains(x: x, y: y) else { return } + endStroke() + let target = pixels[y * Self.side + x] + guard target != selectedColor else { return } + var filled = pixels + var pending = [(x, y)] + while let (column, row) = pending.popLast() { + let index = row * Self.side + column + guard filled[index] == target else { continue } + filled[index] = selectedColor + for (dx, dy) in Self.neighborOffsets where Self.contains(x: column + dx, y: row + dy) { + pending.append((column + dx, row + dy)) + } + } + record(pixels) + pixels = filled + } + + func undo() { + guard !isSubmitting else { return } + endStroke() + guard let previous = undoStack.popLast() else { return } + redoStack.append(pixels) + pixels = previous + } + + func redo() { + guard !isSubmitting else { return } + endStroke() + guard let next = redoStack.popLast() else { return } + undoStack.append(pixels) + pixels = next + } + + func clear() { + guard !isSubmitting else { return } + endStroke() + guard !isBlank else { return } + record(pixels) + pixels = Self.blank + } + + /// Drops the open stroke without committing it, so a retired drawing never reaches the history. + func resetPixels() { + previousCell = nil + strokeStart = nil + pixels = Self.blank + undoStack.removeAll() + redoStack.removeAll() + tool = .brush + encodedByteCount = nil + } + + func measure( + transport: PixelPaintTransport, + senderName: String, + encode: @Sendable (MCOImageRaster, PixelPaintTransport) async throws -> String = encodePixelDrawing + ) async { + let measured = pixels + let count: Int? + do { + let text = try await encode(image, transport) + count = try transport.encodedByteCount(text: text, senderName: senderName) + } catch { + count = nil + } + guard !Task.isCancelled, measured == pixels else { return } + encodedByteCount = count + } + + private func record(_ previous: [Int]) { + undoStack.append(previous) + if undoStack.count > Self.historyLimit { + undoStack.removeFirst(undoStack.count - Self.historyLimit) + } + redoStack.removeAll() + } + + private static func contains(x: Int, y: Int) -> Bool { + (0.. String { + colorNames.indices.contains(index) ? colorNames[index] : "" + } var pixels = Array(repeating: background, count: side * side) var selectedColor = initialBrush + var tool = PixelPaintTool.brush + var undoStack: [[Int]] = [] + var redoStack: [[Int]] = [] + /// Changes only when `paint` changes a cell, so the stroke haptic stays silent on undo, fill, and clear. + var paintedCellRevision = 0 + var encodedByteCount: Int? var isSubmitting = false /// True once this submission has called `onSend`. Cancel stays enabled until then. var isAdmitting = false var errorTitle: String? var errorMessage: String? + /// `strokeStart` becomes one undo entry when `endStroke` runs. + var previousCell: (x: Int, y: Int)? + var strokeStart: [Int]? private var submissionGeneration: UInt = 0 - private var previousCell: (x: Int, y: Int)? private var submissionTask: Task? var image: MCOImageRaster { MCOImageRaster(width: Self.side, height: Self.side, profile: Self.profile, pixels: pixels) } - func paint(x: Int, y: Int) { - guard !isSubmitting, (0.. Void @Environment(\.dismiss) private var dismiss @Environment(\.appState) private var appState - private static let swatchSize: CGFloat = 36 + @AppStorage(AppStorageKey.pixelPaintShowsGrid.rawValue) + private var showsGrid = AppStorageKey.defaultPixelPaintShowsGrid + @State private var isWide = false + @State private var isConfirmingDiscard = false private static let maximumCanvasSize: CGFloat = 480 - private static let gridWidth: CGFloat = 0.5 private static let contentSpacing: CGFloat = 24 - private static let paletteColumns = 4 - private static let swatchPadding: CGFloat = 4 - /// Spoken names in `PixelPaintDraft.profile` palette order. - private static let colorNames = [ - L10n.Chats.Chats.Mcoimg.ColorName.white, L10n.Chats.Chats.Mcoimg.ColorName.gray, - L10n.Chats.Chats.Mcoimg.ColorName.black, L10n.Chats.Chats.Mcoimg.ColorName.red, - L10n.Chats.Chats.Mcoimg.ColorName.yellow, L10n.Chats.Chats.Mcoimg.ColorName.green, - L10n.Chats.Chats.Mcoimg.ColorName.blue, L10n.Chats.Chats.Mcoimg.ColorName.purple, - ] - - private static func colorName(_ index: Int) -> String { - colorNames.indices.contains(index) ? colorNames[index] : "" - } var body: some View { NavigationStack { - ScrollView { + // `AnyLayout` keeps the canvas identity, and its VoiceOver cursor, across a rotation. + let layout = isWide + ? AnyLayout(HStackLayout(spacing: Self.contentSpacing)) + : AnyLayout(VStackLayout(spacing: Self.contentSpacing)) + layout { + PixelPaintCanvas(draft: draft, showsGrid: showsGrid) + .frame(maxWidth: Self.maximumCanvasSize, maxHeight: Self.maximumCanvasSize) VStack(spacing: Self.contentSpacing) { - coverStatus - canvas - .aspectRatio(1, contentMode: .fit) - .frame(maxWidth: Self.maximumCanvasSize) - LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: Self.paletteColumns)) { - ForEach(0.. $0.size.height } action: { isWide = $0 } .navigationTitle(L10n.Chats.Chats.Mcoimg.title) .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button(L10n.Localizable.Common.cancel, systemImage: "xmark") { - draft.endStroke() - draft.remove() - dismiss() - } - .disabled(draft.isAdmitting) - .accessibilityHint(draft.isAdmitting ? L10n.Chats.Chats.Mcoimg.sending : "") - .accessibilityIdentifier("pixelPaintCancel") - } - ToolbarItem(placement: .confirmationAction) { - Button(L10n.Chats.Chats.Mcoimg.send, systemImage: "arrow.up") { - draft.endStroke() - onSend() - } - .disabled(!canSend) - .accessibilityHint(sendAccessibilityHint) - .accessibilityIdentifier("pixelPaintSend") - } - } + .toolbar { toolbar } } .interactiveDismissDisabled() .errorAlert($draft.errorMessage, title: draft.errorTitle) .accessibilityIdentifier("pixelPaintEditor") } + @ToolbarContentBuilder + private var toolbar: some ToolbarContent { + ToolbarItem(placement: .cancellationAction) { + Button(L10n.Localizable.Common.cancel, systemImage: "xmark", action: cancel) + .disabled(draft.isAdmitting) + .accessibilityHint(draft.isAdmitting ? L10n.Chats.Chats.Mcoimg.sending : "") + .accessibilityIdentifier("pixelPaintCancel") + .confirmationDialog( + L10n.Chats.Chats.Mcoimg.discardTitle, + isPresented: $isConfirmingDiscard, + titleVisibility: .visible + ) { + Button(L10n.Chats.Chats.Mcoimg.discard, role: .destructive, action: discard) + } + } + ToolbarItem(placement: .topBarTrailing) { + Toggle(L10n.Chats.Chats.Mcoimg.showGrid, systemImage: "grid", isOn: $showsGrid) + .toggleStyle(.button) + .accessibilityIdentifier("pixelPaintGrid") + } + ToolbarItem(placement: .confirmationAction) { + Button(L10n.Chats.Chats.Mcoimg.send, systemImage: "arrow.up") { + draft.endStroke() + onSend() + } + .disabled(!canSend) + .accessibilityHint(sendAccessibilityHint) + .accessibilityIdentifier("pixelPaintSend") + } + } + private var canSend: Bool { - appState.connectionState == .ready && !draft.isSubmitting + appState.connectionState == .ready && !draft.isSubmitting && !draft.isOverBudget(for: transport) } private var sendAccessibilityHint: String { @@ -98,64 +84,25 @@ struct PixelPaintEditor: View { if appState.connectionState != .ready { return L10n.Chats.Chats.Input.requiresConnection } + if draft.isOverBudget(for: transport) { + return L10n.Chats.Chats.Mcoimg.tooLargeInline + } return "" } - @ViewBuilder - private var coverStatus: some View { - if draft.isSubmitting { - ProgressView(draft.isAdmitting ? L10n.Chats.Chats.Mcoimg.sending : L10n.Chats.Chats.Mcoimg.encoding) - } else if appState.connectionState != .ready { - Text(L10n.Chats.Chats.Input.requiresConnection) - .font(.footnote) - .foregroundStyle(.secondary) + /// A submission that hasn't been admitted is retired at once, so it can't send behind a dialog. + private func cancel() { + draft.endStroke() + if draft.isSubmitting || draft.isBlank { + discard() + } else { + isConfirmingDiscard = true } } - private var canvas: some View { - Canvas { context, size in - let cellSize = size.width / Double(PixelPaintDraft.side) - for row in 0.. 0 else { return } - draft.paint(x: Int(floor(value.location.x / side * Double(PixelPaintDraft.side))), - y: Int(floor(value.location.y / side * Double(PixelPaintDraft.side)))) - }.onEnded { _ in draft.endStroke() }) - .allowsHitTesting(!draft.isSubmitting) - .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { canvasWidth = $0 } - .accessibilityLabel(L10n.Chats.Chats.Mcoimg.canvas) - .accessibilityIdentifier("pixelPaintCanvas") - .accessibilityRepresentation { accessiblePixels.disabled(draft.isSubmitting) } - } - - @State private var canvasWidth: CGFloat = 0 - - private var accessiblePixels: some View { - VStack { - ForEach(0.. some View { + VStack(alignment: .leading) { + Gauge(value: Double(min(bytes, limit)), in: 0...Double(limit)) { + Text(L10n.Chats.Chats.Mcoimg.budget(bytes, limit)) + } + .gaugeStyle(.accessoryLinearCapacity) + .labelsHidden() + .tint(isOverBudget ? .red : .secondary) + HStack { + Text("\(bytes)/\(limit)") + .monospacedDigit() + if isOverBudget { + Text(L10n.Chats.Chats.Mcoimg.tooLargeInline) + } + } + .font(.caption2) + .foregroundStyle(isOverBudget ? .red : .secondary) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(L10n.Chats.Chats.Mcoimg.budget(bytes, limit)) + .accessibilityValue(isOverBudget ? L10n.Chats.Chats.Mcoimg.tooLargeInline : "") + } +} + +private struct MeasurementKey: Equatable { + let pixels: [Int] + let transport: PixelPaintTransport + let senderName: String +} diff --git a/MC1/Views/Chats/MCOimg/PixelPaintTool.swift b/MC1/Views/Chats/MCOimg/PixelPaintTool.swift new file mode 100644 index 0000000000..a7279584d2 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/PixelPaintTool.swift @@ -0,0 +1,21 @@ +enum PixelPaintTool: CaseIterable, Hashable { + case brush + case eraser + case fill + + var title: String { + switch self { + case .brush: L10n.Chats.Chats.Mcoimg.Tool.brush + case .eraser: L10n.Chats.Chats.Mcoimg.Tool.eraser + case .fill: L10n.Chats.Chats.Mcoimg.Tool.fill + } + } + + var systemImage: String { + switch self { + case .brush: "paintbrush.pointed" + case .eraser: "eraser" + case .fill: "drop.fill" + } + } +} diff --git a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift index 6aaf0087b5..7006258907 100644 --- a/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift +++ b/MC1Services/Sources/MC1Services/Services/AppStorageKey.swift @@ -71,6 +71,8 @@ public enum AppStorageKey: String { case lastShownWhatsNewVersion /// Left out of `BackupUserDefaults`, so a restored on value cannot enable collection. A missing key stays off. case collectDebugLogs + /// Intentionally device-local: a display preference for the Pixel Paint canvas, not registered in `BackupUserDefaults`. + case pixelPaintShowsGrid // Notification toggles read by NotificationPreferences and // NotificationPreferencesStore; all share defaultNotificationEnabled. @@ -109,6 +111,7 @@ public enum AppStorageKey: String { public static let defaultUseDefaultTranslationApp: Bool = false public static let defaultTranslationOffersEnabled: Bool = true public static let defaultLiveActivityEnabled: Bool = true + public static let defaultPixelPaintShowsGrid: Bool = true /// Days before a non-favorite node is auto-deleted; 0 disables cleanup. public static let defaultAutoDeleteStaleNodesDays: Int = 0 public static let defaultDMDirectAttempts: Int = DMSendBudget.defaultDirectAttempts diff --git a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift index 0a1ad5ee01..20ad31791e 100644 --- a/MC1Tests/Views/Chats/PixelPaintDraftTests.swift +++ b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift @@ -37,8 +37,12 @@ struct PixelPaintDraftTests { let task = probe.submit(draft) await probe.pause.untilPaused() let second = probe.submit(draft) + let couldUndo = draft.canUndo draft.paint(x: 3, y: 4) draft.clear() + draft.fill(x: 10, y: 10) + draft.undo() + #expect(draft.canUndo == couldUndo) #expect(second == nil) #expect(probe.payloads.count == 1) #expect(probe.captured == [snapshot]) @@ -151,6 +155,132 @@ struct PixelPaintDraftTests { draft.paint(x: 0, y: PixelPaintDraft.side) #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) } + + @Test func `a stroke that leaves and re-enters the canvas does not join the exit and entry cells`() { + let draft = PixelPaintDraft() + let side = PixelPaintDraft.side + let entryRow = 10 + draft.paint(x: 0, y: 0) + draft.paint(x: -1, y: 0) + draft.paint(x: 0, y: entryRow) + draft.endStroke() + #expect(draft.pixels[0] == PixelPaintDraft.initialBrush) + #expect(draft.pixels[entryRow * side] == PixelPaintDraft.initialBrush) + for row in 1..? let pause = SubmissionPause() } + private struct TransportHarness: View { + let draft: PixelPaintDraft + @Bindable var model: TransportModel + var body: some View { + Color.clear + .fullScreenCover(isPresented: $model.isPresented) { + PixelPaintEditor(draft: draft, transport: model.transport, senderName: model.senderName, onSend: {}) + } + .onAppear { model.isReady = true } + } + } + + @Observable + @MainActor + final class TransportModel { + /// A long node name is what pushes a 16×16 drawing past the channel text limit. + static let nodeName = String(repeating: "N", count: 32) + var transport = PixelPaintTransport.channelText + var senderName = nodeName + var isPresented = false + var isReady = false + } + + /// The margin absorbs the encoded size's variance across random nonces. + private func drawingOverTextLimitButWithinDataLimit() async throws -> [Int] { + let side = PixelPaintDraft.side + let margin = 2 + let colors = MCOImagePalette.count(profile: PixelPaintDraft.profile) + var state: UInt32 = 0x2545_F491 + let sequence = (0..<(side * side)).map { _ in + state = state &* 1_664_525 &+ 1_013_904_223 + return Int(state >> 16) % colors + } + for count in stride(from: side, through: side * side, by: side) { + var pixels = Array(repeating: PixelPaintDraft.background, count: side * side) + pixels.replaceSubrange(0.. PixelPaintTransport.channelText.byteLimit + margin else { continue } + let data = try await encodePixelDrawing(image, transport: .channelData) + let dataBytes = try PixelPaintTransport.channelData.encodedByteCount(text: data, senderName: TransportModel.nodeName) + try #require(dataBytes + margin <= PixelPaintTransport.channelData.byteLimit) + return pixels + } + throw NoDrawingOverflowsTextLimit() + } + + private struct NoDrawingOverflowsTextLimit: Error {} + @Observable @MainActor final class InputModel { @@ -452,6 +573,13 @@ struct PixelPaintPresentationTests { return controller.children.contains { alertTitled(title, message: message, from: $0) } } + private func alertTitled(_ title: String, from controller: UIViewController?) -> Bool { + guard let controller else { return false } + if let alert = controller as? UIAlertController, alert.title == title { return true } + if alertTitled(title, from: controller.presentedViewController) { return true } + return controller.children.contains { alertTitled(title, from: $0) } + } + private func alertMessage(_ text: String, from controller: UIViewController?) -> Bool { guard let controller else { return false } if let alert = controller as? UIAlertController, alert.message == text { return true }