diff --git a/.gitignore b/.gitignore index 73fd52cab3..6e2268e151 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,9 @@ tmp/ 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/MC1/Resources/Generated/L10n.swift b/MC1/Resources/Generated/L10n.swift index f6fa9b5bcc..2e2bf2a48c 100644 --- a/MC1/Resources/Generated/L10n.swift +++ b/MC1/Resources/Generated/L10n.swift @@ -558,6 +558,98 @@ 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 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 + 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") + /// 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 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 + 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.") + } + /// 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 { + /// 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 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 { /// 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 e2538d4991..0bdf554fe0 100644 --- a/MC1/Resources/Localization/de.lproj/Chats.strings +++ b/MC1/Resources/Localization/de.lproj/Chats.strings @@ -1059,6 +1059,126 @@ /* 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 + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixel malen"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Nicht unterstütztes Bildformat"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Beschädigtes 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"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Senden"; + +/* 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"; + + +/* 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."; + +/* 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"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Die Zeichnung konnte nicht kodiert werden."; + +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Zeichnung wird kodiert"; + +/* 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 29171bf39e..f4d659d4d1 100644 --- a/MC1/Resources/Localization/en.lproj/Chats.strings +++ b/MC1/Resources/Localization/en.lproj/Chats.strings @@ -1069,6 +1069,126 @@ /* 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"; + +/* 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"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Send"; + +/* 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"; + + +/* 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."; + +/* 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"; + +/* 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"; + +/* 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 7269a62cb8..40ea4b5914 100644 --- a/MC1/Resources/Localization/es.lproj/Chats.strings +++ b/MC1/Resources/Localization/es.lproj/Chats.strings @@ -1059,6 +1059,126 @@ /* 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 + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pintura de píxeles"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Formato de imagen no compatible"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Imagen dañada"; + +/* 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"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Enviar"; + +/* 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"; + + +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Dibujo demasiado grande"; + +/* 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"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "No se puede codificar el dibujo."; + +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Codificando el dibujo"; + +/* 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 7e11dd3078..30d5b25786 100644 --- a/MC1/Resources/Localization/fr.lproj/Chats.strings +++ b/MC1/Resources/Localization/fr.lproj/Chats.strings @@ -1059,6 +1059,126 @@ /* 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 + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Peinture pixel"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Format d'image non pris en charge"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Image endommagée"; + +/* 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"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Envoyer"; + +/* 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"; + + +/* 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."; + +/* 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"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Impossible d'encoder le dessin."; + +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Encodage du dessin"; + +/* 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 107a24f83a..8804b365b4 100644 --- a/MC1/Resources/Localization/it.lproj/Chats.strings +++ b/MC1/Resources/Localization/it.lproj/Chats.strings @@ -1052,6 +1052,126 @@ // MARK: - Inline Image +// MARK: - MCOimg + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Disegno a pixel"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Formato immagine non supportato"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Immagine danneggiata"; + +/* 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"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Invia"; + +/* 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"; + + +/* 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."; + +/* 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"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Impossibile codificare il disegno."; + +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Codifica del disegno"; + +/* 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 ceb0999fa5..66e68b7fdd 100644 --- a/MC1/Resources/Localization/ko.lproj/Chats.strings +++ b/MC1/Resources/Localization/ko.lproj/Chats.strings @@ -1052,6 +1052,126 @@ // MARK: - Inline Image +// MARK: - MCOimg + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "픽셀 그리기"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "지원되지 않는 이미지 형식"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "손상된 이미지"; + +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "픽셀 그림"; + +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "그림 지우기"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "보내기"; + +/* 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" = "픽셀 캔버스"; + + +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "그림이 너무 큼"; + +/* 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" = "인코딩할 수 없음"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "그림을 인코딩할 수 없습니다."; + +/* 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" = "그림 보내는 중..."; + +/* 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 5df9aa44fc..35d7730f69 100644 --- a/MC1/Resources/Localization/nl.lproj/Chats.strings +++ b/MC1/Resources/Localization/nl.lproj/Chats.strings @@ -1059,6 +1059,126 @@ /* 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 + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pixeltekenen"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Niet-ondersteund afbeeldingsformaat"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Beschadigde 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"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Verzenden"; + +/* 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"; + + +/* 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."; + +/* 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"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Kan de tekening niet coderen."; + +/* Progress label while a pixel drawing is encoded */ +"chats.mcoimg.encoding" = "Tekening wordt gecodeerd"; + +/* 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 eeecc55c77..ec8e26318e 100644 --- a/MC1/Resources/Localization/pl.lproj/Chats.strings +++ b/MC1/Resources/Localization/pl.lproj/Chats.strings @@ -1051,6 +1051,126 @@ /* 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 + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Malowanie pikseli"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Nieobsługiwany format obrazu"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Uszkodzony obraz"; + +/* 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"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Wyślij"; + +/* 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"; + + +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Rysunek za duży"; + +/* 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ć"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Nie można zakodować rysunku."; + +/* 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"; + +/* 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 f9d629686d..989518c2e6 100644 --- a/MC1/Resources/Localization/pt.lproj/Chats.strings +++ b/MC1/Resources/Localization/pt.lproj/Chats.strings @@ -1052,6 +1052,126 @@ // MARK: - Inline Image +// MARK: - MCOimg + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Pintura de píxeis"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Formato de imagem não suportado"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Imagem danificada"; + +/* 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"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Enviar"; + +/* 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"; + + +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Desenho demasiado grande"; + +/* 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"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Não foi possível codificar o desenho."; + +/* 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..."; + +/* 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 f59643d5b6..676d7494d4 100644 --- a/MC1/Resources/Localization/ru.lproj/Chats.strings +++ b/MC1/Resources/Localization/ru.lproj/Chats.strings @@ -1050,6 +1050,126 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Управляйте подключением, отправляйте объявления и проверяйте заряд батареи. Радио остаётся подключённым даже после принудительного закрытия приложения. Нажмите «Отключить», чтобы разорвать связь."; +// MARK: - MCOimg + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Пиксель-арт"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Неподдерживаемый формат изображения"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Повреждённое изображение"; + +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Пиксельный рисунок"; + +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Очистить рисунок"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Отправить"; + +/* 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" = "Пиксельный холст"; + + +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Рисунок слишком большой"; + +/* 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" = "Не удалось закодировать"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Не удалось закодировать рисунок."; + +/* 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" = "Отправка рисунка"; + +/* 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 617b189330..42fde080bc 100644 --- a/MC1/Resources/Localization/uk.lproj/Chats.strings +++ b/MC1/Resources/Localization/uk.lproj/Chats.strings @@ -1050,6 +1050,126 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "Керуйте з'єднанням, надсилайте оголошення та перевіряйте заряд. Радіо залишається підключеним навіть після примусового закриття застосунку. Натисніть «Відключити», щоб розірвати зв'язок."; +// MARK: - MCOimg + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "Піксельний малюнок"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "Непідтримуваний формат зображення"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "Пошкоджене зображення"; + +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "Піксельний малюнок"; + +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "Очистити малюнок"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "Надіслати"; + +/* 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" = "Піксельне полотно"; + + +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "Малюнок занадто великий"; + +/* 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" = "Не вдалося закодувати"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "Не вдалося закодувати малюнок."; + +/* 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" = "Надсилання малюнка"; + +/* 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 b6f3f663bd..8e0dcf1d41 100644 --- a/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings +++ b/MC1/Resources/Localization/zh-Hans.lproj/Chats.strings @@ -1116,6 +1116,126 @@ /* Location: DeviceMenuTip.swift - Purpose: Tip message explaining device menu features */ "chats.tip.deviceMenu.message" = "管理您的连接、发送广播并查看电池电量。即使在强制退出应用后,无线电仍保持连接。点击断开连接以关闭链路。"; +// MARK: - MCOimg + +/* Editor title and the compose-menu action for a pixel drawing */ +"chats.mcoimg.title" = "像素画"; + +/* Placeholder when an MCOimg version cannot be shown */ +"chats.mcoimg.unsupported" = "不支持的图片格式"; + +/* Placeholder when an MCOimg payload cannot be decoded */ +"chats.mcoimg.damaged" = "图片已损坏"; + +/* Name for an MCOimg in VoiceOver, notifications, and the chat list */ +"chats.mcoimg.image" = "像素画"; + +/* Erases every pixel in the editor */ +"chats.mcoimg.clear" = "清除绘图"; + +/* Sends the open pixel drawing */ +"chats.mcoimg.send" = "发送"; + +/* 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" = "像素画布"; + + +/* Alert title when a pixel drawing exceeds the conversation limit */ +"chats.mcoimg.tooLargeTitle" = "绘图过大"; + +/* 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" = "无法编码"; + +/* Error when a pixel drawing cannot be encoded */ +"chats.mcoimg.encodingFailed" = "无法编码此绘图。"; + +/* 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" = "正在发送绘图..."; + +/* 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 581861979e..9b81f83978 100644 --- a/MC1/Views/Chats/ChatConversationInputBar.swift +++ b/MC1/Views/Chats/ChatConversationInputBar.swift @@ -9,8 +9,26 @@ struct ChatConversationInputBar: View { let nodeNameByteCount: Int let onSend: (String) async -> Bool let onWillSend: () -> Void + let onNotAdmitted: () -> Void + + @Environment(\.appState) private var appState + @State private var drawing = PixelPaintDraft() + @State private var isShowingPainter = false var body: some View { + inputBar + .fullScreenCover(isPresented: $isShowingPainter) { + PixelPaintEditor(draft: drawing, transport: drawingTransport, senderName: senderName, onSend: sendDrawing) + } + .onChange(of: conversationType.coordinatorID) { + drawing.remove() + isShowingPainter = false + } + .onDisappear { drawing.remove() } + } + + @ViewBuilder + private var inputBar: some View { switch conversationType { case .dm: ChatInputBar( @@ -19,7 +37,7 @@ struct ChatConversationInputBar: View { placeholder: L10n.Chats.Chats.Input.Placeholder.directMessage, maxBytes: ProtocolLimits.maxDirectMessageLength, isEncrypted: true, - leading: { ChatShareMenu(onInsert: insertShared) }, + leading: { ChatShareMenu(onInsert: insertShared, onPaint: openPainter) }, onSend: send ) @@ -35,12 +53,51 @@ struct ChatConversationInputBar: View { : L10n.Chats.Chats.Channel.typePrivate, maxBytes: maxBytes, isEncrypted: channel.isEncryptedChannel, - leading: { ChatShareMenu(onInsert: insertShared) }, + leading: { ChatShareMenu(onInsert: insertShared, onPaint: openPainter) }, onSend: send ) } } + private func openPainter() { + guard !drawing.isSubmitting else { return } + ChatKeyboardLift.resignFirstResponder() + isShowingPainter = true + } + + private var drawingTransport: PixelPaintTransport { + let isChannel = if case .channel = conversationType { true } else { false } + 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 + } + guard let attempt = drawing.begin(isReady: ready) else { return } + let task = Task { + await drawing.run( + attempt, + transport: transport, + senderName: { senderName }, + isReady: ready, + onSend: onSend, + onWillSend: onWillSend, + onAdmitted: { isShowingPainter = false } + ) + } + drawing.track(task) + } + private func send(_ text: String) { let draft = $composingText onWillSend() @@ -48,6 +105,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 9f905e7658..d4e7e9ccb9 100644 --- a/MC1/Views/Chats/ChatConversationView.swift +++ b/MC1/Views/Chats/ChatConversationView.swift @@ -200,7 +200,10 @@ struct ChatConversationView: View { await chatViewModel.sendChannelMessage(text: text) } }, - onWillSend: { scrollToBottomRequest += 1 } + onWillSend: { scrollToBottomRequest += 1 }, + onNotAdmitted: { + chatViewModel.sendErrorMessage = L10n.Chats.Chats.Alert.UnableToSend.message + } ) } .navigationHeader( 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..2fa05b2e50 100644 --- a/MC1/Views/Chats/Components/ChatInputBar.swift +++ b/MC1/Views/Chats/Components/ChatInputBar.swift @@ -118,7 +118,8 @@ struct ChatInputBar: View { private var canSend: Bool { !isCoolingDown && appState.connectionState == .ready && - !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 diff --git a/MC1/Views/Chats/Components/ChatShareMenu.swift b/MC1/Views/Chats/Components/ChatShareMenu.swift index 804354e084..504da578cd 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 + let onPaint: () -> Void @Environment(\.appState) private var appState @@ -84,6 +81,11 @@ struct ChatShareMenu: View { } .disabled(!canShareLocation) + Button(action: onPaint) { + Label(L10n.Chats.Chats.Mcoimg.title, systemImage: "paintpalette") + } + .accessibilityIdentifier("pixelPaintAction") + Button { isShowingContactPicker = true } label: { @@ -155,6 +157,6 @@ private extension View { } #Preview { - ChatShareMenu(onInsert: { _ in }) + ChatShareMenu(onInsert: { _ in }, onPaint: {}) .padding() } 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..0756a881c2 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/MCOImageRenderer.swift @@ -0,0 +1,147 @@ +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) + } + + 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) { + guard let bitmap = bitmap(image) else { return } + context.draw( + Image(decorative: bitmap, scale: 1).interpolation(.none), + in: CGRect(x: origin.x, y: origin.y, width: CGFloat(image.width), height: CGFloat(image.height)) + ) + } + + /// Premultiplied RGBA; a transparent reference stays all zero. + static func bitmap(_ image: MCOImageRaster) -> 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) { + switch figure { + case let .dot(point, style): + guard let stroke = style.strokeColor else { return } + 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))) + case let .line(start, end, style): + var path = Path() + path.move(to: MCOImageGeometry.point(start)) + path.addLine(to: MCOImageGeometry.point(end)) + // Lines and dots use stroke only, even when the current style has a fill. + stroke(path, style: style, profile: profile, context: &context) + case let .rectangle(first, second, third, style): + paint(MCOImageGeometry.rectangle(first, second, third), closed: true, style: style, profile: profile, context: &context) + case let .ellipse(first, second, third, style): + let geometry = MCOImageGeometry.ellipse(first, second, third) + guard let geometry else { return } + paint(geometry.path, closed: geometry.closed, style: style, profile: profile, context: &context) + case let .path(points, closed, style): + 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)) + } + 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 } + paint(path, closed: closed, style: style, profile: profile, context: &context) + case let .text(origin, width, alignment, fontSize, text, style): + 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) + } + case let .raster(origin, image): + raster(image, origin: CGPoint(x: origin.x, y: origin.y), context: &context) + } + } + + private static func paint(_ path: Path, closed: Bool, style: MCOImageV4Style, + profile: Int, context: inout GraphicsContext) { + if let fill = style.fillColor { + var fillPath = path + fillPath.closeSubpath() + context.fill(fillPath, with: .color(color(fill, profile: profile)), style: FillStyle(eoFill: false)) + } + var strokePath = path + if closed { strokePath.closeSubpath() } + stroke(strokePath, style: style, profile: profile, context: &context) + } + + private static func stroke(_ path: Path, style: MCOImageV4Style, profile: Int, context: inout GraphicsContext) { + guard let stroke = style.strokeColor else { return } + context.stroke(path, with: .color(color(stroke, profile: profile)), + style: StrokeStyle(lineWidth: CGFloat(style.strokeWidth), lineCap: .square, lineJoin: .miter, miterLimit: strokeMiterLimit)) + } +} diff --git a/MC1/Views/Chats/MCOimg/MCOImageView.swift b/MC1/Views/Chats/MCOimg/MCOImageView.swift new file mode 100644 index 0000000000..d8ef9115e0 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/MCOImageView.swift @@ -0,0 +1,42 @@ +import MC1Services +import SwiftUI + +struct MCOImageView: View { + let content: MCOImageContent + private static let maximumSide: CGFloat = 220 + + var body: some View { + switch content { + case .raster, .document: + MCOImageRenderer(content: content) + .frame(width: displaySize.width, height: displaySize.height) + .accessibilityLabel(L10n.Chats.Chats.Mcoimg.image) + case .unsupported: + Label(L10n.Chats.Chats.Mcoimg.unsupported, systemImage: "photo.badge.exclamationmark") + case .damaged: + Label(L10n.Chats.Chats.Mcoimg.damaged, systemImage: "photo.badge.exclamationmark") + } + } + + private var displaySize: CGSize { + let width: Int + let height: Int + switch content { + case let .raster(image): (width, height) = (image.width, image.height) + case let .document(document): (width, height) = (document.width, document.height) + case .unsupported, .damaged: return .zero + } + let scale = Self.maximumSide / CGFloat(max(width, height)) + return CGSize(width: CGFloat(width) * scale, height: CGFloat(height) * scale) + } +} + +extension MCOImageContent { + var accessibilityLabel: String { + switch self { + case .raster, .document: L10n.Chats.Chats.Mcoimg.image + case .unsupported: L10n.Chats.Chats.Mcoimg.unsupported + case .damaged: L10n.Chats.Chats.Mcoimg.damaged + } + } +} 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 submissionTask: Task? + + var image: MCOImageRaster { + MCOImageRaster(width: Self.side, height: Self.side, profile: Self.profile, pixels: pixels) + } + + /// Drops the current pixels and retires the in-flight submission. + func remove() { + 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, + transport: PixelPaintTransport, + senderName: @escaping () -> String, + isReady: @escaping () -> Bool, + onSend: @escaping (String) async -> Bool, + onWillSend: @escaping () -> Void, + onAdmitted: @escaping () -> Void, + encode: @escaping @Sendable (MCOImageRaster, PixelPaintTransport) async throws -> String = encodePixelDrawing + ) async { + guard isCurrent(attempt.generation) else { return } + let result = await outcome( + snapshot: attempt.snapshot, + transport: transport, + generation: attempt.generation, + senderName: senderName, + isReady: isReady, + onSend: onSend, + onWillSend: onWillSend, + encode: encode + ) + settle(result, generation: attempt.generation, onAdmitted: onAdmitted) + } + + private func outcome( + snapshot: MCOImageRaster, + transport: PixelPaintTransport, + generation: UInt, + senderName: @escaping () -> String, + isReady: @escaping () -> Bool, + onSend: @escaping (String) async -> Bool, + onWillSend: @escaping () -> Void, + encode: @escaping @Sendable (MCOImageRaster, PixelPaintTransport) async throws -> String + ) async -> SubmissionResult { + let text: String + do { + text = try await encode(snapshot, transport) + } 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 transport.encodedByteCount(text: text, senderName: senderName()) + } catch { + guard isCurrent(generation) else { return .retired } + return Self.encodeFailed + } + guard isCurrent(generation) else { return .retired } + let limit = transport.byteLimit + guard bytes <= limit else { + return .failed( + title: L10n.Chats.Chats.Mcoimg.tooLargeTitle, + message: transport.isChannel + ? L10n.Chats.Chats.Mcoimg.tooLargeChannel(bytes, limit) + : 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, + onAdmitted: () -> Void + ) { + guard isCurrent(generation) else { return } + switch result { + case .admitted: + remove() + onAdmitted() + case .rejected: + 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 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, transport: PixelPaintTransport) async throws -> String { + let body = try MCOImageV3Codec.encode(image, nonce: UInt8.random(in: .min ... .max)) + 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 new file mode 100644 index 0000000000..aa867cf1c3 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/PixelPaintEditor.swift @@ -0,0 +1,108 @@ +import MC1Services +import SwiftUI + +struct PixelPaintEditor: View { + @Bindable var draft: PixelPaintDraft + let transport: PixelPaintTransport + let senderName: String + let onSend: () -> Void + @Environment(\.dismiss) private var dismiss + @Environment(\.appState) private var appState + @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 contentSpacing: CGFloat = 24 + + var body: some View { + NavigationStack { + // `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) { + PixelPaintStatusRow(draft: draft, transport: transport, senderName: senderName) + PixelPaintControls(draft: draft) + } + .frame(maxWidth: Self.maximumCanvasSize) + } + .padding() + .frame(maxWidth: .infinity, maxHeight: .infinity) + .onGeometryChange(for: Bool.self) { $0.size.width > $0.size.height } action: { isWide = $0 } + .navigationTitle(L10n.Chats.Chats.Mcoimg.title) + .navigationBarTitleDisplayMode(.inline) + .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 && !draft.isOverBudget(for: transport) + } + + 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 + } + if draft.isOverBudget(for: transport) { + return L10n.Chats.Chats.Mcoimg.tooLargeInline + } + return "" + } + + /// 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 func discard() { + guard !draft.isAdmitting else { return } + draft.remove() + dismiss() + } +} diff --git a/MC1/Views/Chats/MCOimg/PixelPaintStatusRow.swift b/MC1/Views/Chats/MCOimg/PixelPaintStatusRow.swift new file mode 100644 index 0000000000..fbb541c4e2 --- /dev/null +++ b/MC1/Views/Chats/MCOimg/PixelPaintStatusRow.swift @@ -0,0 +1,74 @@ +import MC1Services +import SwiftUI + +struct PixelPaintStatusRow: View { + let draft: PixelPaintDraft + let transport: PixelPaintTransport + let senderName: String + @Environment(\.appState) private var appState + private static let previewSize: CGFloat = 44 + private static let previewBorderWidth: CGFloat = 1 + private static let spacing: CGFloat = 12 + + var body: some View { + HStack(spacing: Self.spacing) { + MCOImageRenderer(content: .raster(draft.image)) + .frame(width: Self.previewSize, height: Self.previewSize) + .overlay { Rectangle().strokeBorder(.secondary, lineWidth: Self.previewBorderWidth) } + .accessibilityLabel(L10n.Chats.Chats.Mcoimg.image) + status + .frame(maxWidth: .infinity, alignment: .leading) + } + // Lives here rather than on the editor so a paint only invalidates the views that show pixels. + .task(id: MeasurementKey(pixels: draft.pixels, transport: transport, senderName: senderName)) { + await draft.measure(transport: transport, senderName: senderName) + } + .sensoryFeedback(.warning, trigger: isOverBudget) { wasOver, isOver in !wasOver && isOver } + } + + private var isOverBudget: Bool { + draft.isOverBudget(for: transport) + } + + @ViewBuilder + private var status: some View { + if draft.isAdmitting { + ProgressView(L10n.Chats.Chats.Mcoimg.sending) + } else if appState.connectionState != .ready { + Text(L10n.Chats.Chats.Input.requiresConnection) + .font(.footnote) + .foregroundStyle(.secondary) + } else if let bytes = draft.encodedByteCount { + budget(bytes: bytes, limit: transport.byteLimit) + } + } + + private func budget(bytes: Int, limit: Int) -> 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/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/MessageActionAvailability.swift b/MC1/Views/Chats/Reactions/MessageActionAvailability.swift index eec98cd7e4..320c133d2a 100644 --- a/MC1/Views/Chats/Reactions/MessageActionAvailability.swift +++ b/MC1/Views/Chats/Reactions/MessageActionAvailability.swift @@ -10,6 +10,7 @@ struct MessageActionAvailability { let canShowRepeatDetails: Bool let canViewPath: Bool let canDelete: Bool + let canReact: Bool /// True when the actions sheet shows the path disclosure. let showsPathDetail: Bool @@ -25,6 +26,9 @@ struct MessageActionAvailability { && message.isFloodRouted && !(message.pathNodes?.isEmpty ?? true) canDelete = true + // 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/Reactions/MessageActionsSheet.swift b/MC1/Views/Chats/Reactions/MessageActionsSheet.swift index f7f27d42cb..f3891a90ee 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/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 797f4f6f80..fe54eb36fc 100644 --- a/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift +++ b/MC1/Views/Chats/ViewModel/ChatMessageBakeState+ItemBuild.swift @@ -112,8 +112,12 @@ extension ChatMessageBakeState { envInputs: EnvInputs, senderTables: ChatSenderTables ) -> MessageBuildInputs { - seedPreviewStateIfNeeded(for: message, envInputs: envInputs) - if envInputs.translationOffersEnabled { + // 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, !isMCOImage { 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..dc3cc5c8e8 100644 --- a/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift +++ b/MC1/Views/Chats/ViewModel/ChatTimelinePopulator.swift @@ -151,19 +151,12 @@ 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 - } else { - message.senderNodeName - } - guard let senderName else { continue } + guard let target = message.channelReactionTarget(localNodeName: localNodeName) else { continue } let pendingMatches = await reactionService.indexMessage( id: message.id, channelIndex: channel.index, - senderName: senderName, - text: message.text, - timestamp: message.reactionTimestamp + target: target ) for pending in pendingMatches { diff --git a/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+Channels.swift index 3dd07fc6dd..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,6 +152,8 @@ extension ChatViewModel { errorMessage = nil errorBannerMessage = nil + 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. let dataStore = dataStore 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/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift b/MC1/Views/Chats/ViewModel/ChatViewModel+MessageActions.swift index 63be19ec1e..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,6 +40,8 @@ extension ChatViewModel { errorMessage = nil errorBannerMessage = nil + guard await messagePreparedForResend(message) != nil else { return } + let envelope = DirectMessageEnvelope( messageID: message.id, contactID: contact.id, isSingleAttempt: message.reactionTargetMessageID != nil @@ -61,11 +73,10 @@ 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 { + guard let message = await messagePreparedForResend(message) else { 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/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 93a61ae0cc..3dde7b6f08 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 = 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,7 +249,9 @@ private struct BubbleContent: View { @ViewBuilder private var messageBody: some View { - if let plainText = visibleBody.plainText { + if let mcoImage { + MCOImageView(content: mcoImage) + } 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..2b9c8a22b4 100644 --- a/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift +++ b/MC1Services/Sources/MC1Services/Models/ChannelMessageEnvelope.swift @@ -2,19 +2,13 @@ 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. +/// `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 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. +/// `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/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/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/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/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/HeardRepeatPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/HeardRepeatPersisting.swift index 3f9f508668..923b4d85bc 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,10 @@ 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. + /// 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 @@ -46,6 +51,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 +77,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, timestampWindow: ClosedRange) 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/MessagePersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift index 896bef9a4a..6cf42ac67a 100644 --- a/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift +++ b/MC1Services/Sources/MC1Services/Protocols/Persistence/MessagePersisting.swift @@ -158,6 +158,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 MCOimg resend. + func updateMessageText(id: UUID, text: String) async throws + /// Update message timestamp (for resending) func updateMessageTimestamp(id: UUID, timestamp: UInt32) async throws @@ -241,6 +244,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) diff --git a/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift b/MC1Services/Sources/MC1Services/Protocols/Persistence/RxLogPersisting.swift index 75146e9f57..cb7970b1e0 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,14 @@ public protocol RxLogPersisting: Actor { senderTimestamp: UInt32 ) async throws -> [RxLogEntryDTO] + /// Group-datagram rows for one radio and channel received inside `receivedWithin`. No sender timestamp. + func fetchRxLogEntries( + radioID: UUID, + channelIndex: UInt8, + payloadType: PayloadType, + receivedWithin: ClosedRange + ) 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 +121,15 @@ public protocol RxLogPersisting: Actor { // MARK: - Default Parameter Values extension RxLogPersisting { + func fetchRxLogEntries( + radioID: UUID, + channelIndex: UInt8, + payloadType: PayloadType, + receivedWithin: ClosedRange + ) 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..387839b72b 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,18 @@ 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, + receivedWithin: MCOImageTransport.datagramReceiveWindow(around: message.timestamp) + )) ?? [] + let decoded = await rxLog.decodedEntries(raw) + await repeats.harvestDatagramPaths(for: message, decodedCandidates: decoded) + } ) channelService = ChannelService( session: session, 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/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 addff30993..4fc42f65d0 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService+ChannelDrain.swift @@ -43,6 +43,7 @@ extension ChatSendQueueService { ) else { return } try cancelSendIfRetired(dependencies.sendsRetired) + let sentDatagram = MCOImageCodec.isChannelDataText(envelope.messageText) switch try await transmitQueuedChannel(envelope: envelope, dependencies: dependencies) { case .dropped: return @@ -60,13 +61,20 @@ extension ChatSendQueueService { timeout: dependencies.config.transportWaitTimeout ) case let .sent(indexTimestamp): - if let nodeName = envelope.localNodeName { + // 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) + } + } + if let target { _ = await dependencies.reactionService.indexMessage( id: envelope.messageID, channelIndex: envelope.channelIndex, - senderName: nodeName, - text: envelope.messageText, - timestamp: indexTimestamp + target: target ) } try? await dependencies.dataStore.deletePendingSendsForMessage(messageID: envelope.messageID) @@ -78,6 +86,7 @@ extension ChatSendQueueService { error, postBumpCount: postBumpCount, envelope: envelope, + sentDatagram: sentDatagram, dependencies: dependencies ) } @@ -132,9 +141,10 @@ extension ChatSendQueueService { _ error: Error, postBumpCount: Int, envelope: ChannelMessageEnvelope, + sentDatagram: Bool, dependencies: ChannelDrainDependencies ) async throws { - guard isTransientChannelMessageError(error) 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 d26df2cab0..507aa93577 100644 --- a/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift +++ b/MC1Services/Sources/MC1Services/Services/ChatSendQueueService.swift @@ -287,10 +287,8 @@ public final class ChatSendQueueService { let text: String 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 - ) + 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 @@ -567,8 +565,9 @@ public final class ChatSendQueueService { isTransientError(error, deviceCode: FirmwareDeviceErrorCode.directMessageTableFull) } - nonisolated static func isTransientChannelMessageError(_ error: Error) -> Bool { + nonisolated static func isTransientChannelMessageError(_ error: Error, sentDatagram: Bool) -> Bool { isTransientError(error, deviceCode: FirmwareDeviceErrorCode.channelMessageNotFound) + || (sentDatagram && 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/HeardRepeatsService.swift b/MC1Services/Sources/MC1Services/Services/HeardRepeatsService.swift index ff2d255f5b..ad73fb440b 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 } @@ -145,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, @@ -153,7 +157,8 @@ public actor HeardRepeatsService { snr: Double?, rssi: Int?, receivedAt: Date, - rxLogEntryID: UUID? + rxLogEntryID: UUID?, + adoptingContextOf contextSource: RxLogEntryDTO? = nil ) async -> Int? { #if DEBUG if let hold = admissionHoldForTesting { @@ -170,6 +175,14 @@ public actor HeardRepeatsService { receivedAt: receivedAt, rxLogEntryID: rxLogEntryID ) + if case .adoptedCanonical = admission, let contextSource { + try await dataStore.applyDatagramCanonicalContext( + messageID: message.id, + routeType: contextSource.routeType, + regionScope: contextSource.regionScope, + regionScopeMatches: contextSource.regionScopeMatches + ) + } 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 +193,61 @@ public actor HeardRepeatsService { } } + /// 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 { + 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 { + _ = await recordDatagramObservation(entry, on: message) + } + } + + /// 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, + timestampWindow: MCOImageTransport.datagramMatchWindow(around: earliest.receivedAt) + ) + 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 +289,51 @@ 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, + timestampWindow: MCOImageTransport.datagramMatchWindow(around: entry.receivedAt) + ) + var lastCount: Int? + for message in messages where message.datagramDataField == blob { + lastCount = await recordDatagramObservation(entry, on: message) ?? lastCount + } + return lastCount + } catch { + logger.error("Failed to process datagram repeat: \(error.localizedDescription)") + 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 new file mode 100644 index 0000000000..74bde2b947 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageDTO+MCOImage.swift @@ -0,0 +1,38 @@ +import Foundation + +public extension MessageDTO { + var mcoImage: MCOImageContent? { + MCOImageCodec.content(from: text) + } + + var isChannelMCOImage: Bool { + channelIndex != nil && MCOImageCodec.isMCOImageText(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, let channelIndex else { return false } + if isOutgoing { return MCOImageCodec.isChannelDataText(text) } + guard senderTimestamp == 0 else { return false } + let groupTextKey = DeduplicationKey.contentBased( + contactID: nil, + channelIndex: channelIndex, + senderNodeName: senderNodeName, + timestamp: 0, + content: text + ) + return deduplicationKey != groupTextKey + } + + /// False for an incoming datagram MCOimg: the packet carries no send time, so only receipt is known. + var hasWireSendTime: Bool { + isOutgoing || !isDatagramMCOImage + } + + /// 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/MessageFragmentBuilder.swift b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift index a50238fecf..854011a5cc 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageFragmentBuilder.swift @@ -35,6 +35,14 @@ public enum MessageFragmentBuilder { ) -> [MessageFragment] { var fragments: [MessageFragment] = [] + if let image = MCOImageCodec.content(from: message.text) { + fragments.append(.mcoImage(image)) + if 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 { @@ -244,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, @@ -274,7 +282,8 @@ public enum MessageFragmentBuilder { inputs: MessageBuildInputs, message: MessageDTO ) -> Bool { - inputs.previewState == .idle + 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..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 } } @@ -45,10 +41,9 @@ actor MessageLRUCache { } /// 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) - let key = MessageCacheKey(channelIndex: channelIndex, senderName: senderName, messageHash: hash) - let candidate = MessageCandidate(messageID: messageID, text: text, timestamp: timestamp) + 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) { @@ -89,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/MessageLanguageDetector.swift b/MC1Services/Sources/MC1Services/Services/MessageLanguageDetector.swift index 4672107431..589ad5e137 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.isMCOImageText(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..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,15 +24,35 @@ extension MessageService { } else { scope } - 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) + switch transmission { + case let .mcoImage(payload): + 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() + ) + } + 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 new file mode 100644 index 0000000000..8d86035774 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Services/MessageService+MCOImage.swift @@ -0,0 +1,85 @@ +import Foundation + +extension MessageService { + enum ChannelTransmission { + case text(String) + case mcoImage(Data) + } + + /// `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.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 { + /// 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 + if message.channelIndex != nil { + 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 + } + } + try await dataStore.updateMessageText(id: message.id, text: refreshed.text) + return refreshed + } + + 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, nil) + } + guard let device = try await dataStore.fetchDevice(radioID: radioID) else { + throw MessageServiceError.notConnected + } + return try await (canonicalChannelMCOImageText(text, senderName: device.nodeName, device: device), 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 + } + return payload + } +} diff --git a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift index 42b3282cdb..a125b25bdc 100644 --- a/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift +++ b/MC1Services/Sources/MC1Services/Services/MessageService+SendChannel.swift @@ -42,7 +42,7 @@ public extension MessageService { // retireInlineSends waits until the Sent write in this function finishes. try beginInlineSend() defer { endInlineSend() } - try await rejectIfChannelTextTooLong(text, radioID: radioID) + let prepared = try await prepareChannelMessage(text, radioID: radioID) let messageID = UUID() let timestamp = UInt32(Date().timeIntervalSince1970) @@ -52,16 +52,23 @@ 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) + await harvestOutgoingDatagramPathsIfNeeded(messageDTO) do { - try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, 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 +104,7 @@ public extension MessageService { radioID: UUID, textType: TextType = .plain ) async throws -> MessageDTO { - try await rejectIfChannelTextTooLong(text, radioID: radioID) + let prepared = try await prepareChannelMessage(text, radioID: radioID) let messageID = UUID() let timestamp = UInt32(Date().timeIntervalSince1970) @@ -106,15 +113,24 @@ 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) + 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.isDatagramMCOImage else { return } + await datagramPathHarvest?(message) + } + /// Sends an already-created pending channel message. /// /// Use this after ``createPendingChannelMessage(text:channelIndex:radioID:textType:)`` @@ -144,9 +160,19 @@ 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) { + let transmission = try await channelTransmission( + text: message.text, + 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( - text: message.text, + transmission, channelIndex: channelIndex, radioID: radioID, timestamp: Date(timeIntervalSince1970: TimeInterval(message.timestamp)) @@ -184,7 +210,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,9 +247,18 @@ public extension MessageService { acceptedChannelReactions.contains(messageID) || (preserveTimestamp && message.status == .sent) ) if !alreadyAccepted { - try await withPoolBackoff(transientCode: FirmwareDeviceErrorCode.channelMessageNotFound, config: config.poolBackoff, logger: logger) { + let transmission = try await channelTransmission( + text: message.text, + 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( - text: message.text, + transmission, channelIndex: channelIndex, radioID: message.radioID, timestamp: wireDate @@ -261,13 +296,23 @@ public extension MessageService { return wireTimestamp } + private func channelPoolErrorCode(_ transmission: ChannelTransmission) -> UInt8 { + switch transmission { + case .text: + FirmwareDeviceErrorCode.channelMessageNotFound + case .mcoImage: + FirmwareDeviceErrorCode.channelDataTableFull + } + } + private func createOutgoingChannelMessage( id: UUID, radioID: UUID, channelIndex: UInt8, text: String, timestamp: UInt32, - textType: TextType + textType: TextType, + mcoImageSenderName: String? ) -> MessageDTO { let message = Message( id: id, @@ -279,6 +324,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/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/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/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 93b344946d..6bf0061a2b 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+BackupBatchInsert.swift @@ -301,6 +301,29 @@ extension PersistenceStore { !secret.isEmpty && !secret.allSatisfy { $0 == 0 } } + /// 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, + 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 } + let window = MCOImageTransport.datagramMatchWindow(around: dto.timestamp) + return (stored + acceptedHere).first { window.contains($0.timestamp) && $0.datagramDataField == blob } + } + @discardableResult func batchInsertMessages( _ dtos: [MessageDTO], @@ -321,13 +344,17 @@ 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, // 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 { @@ -341,6 +368,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 +391,9 @@ extension PersistenceStore { knownKeys.insert(key) idsByKey[key, default: []].append(dto.id) toInsert.append(dto) + if isIncomingPicture { + 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..50f6270db0 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+Diagnostics.swift @@ -300,6 +300,30 @@ public extension PersistenceStore { return try modelContext.fetch(descriptor).map { RxLogEntryDTO(from: $0) } } + func fetchRxLogEntries( + radioID: UUID, + channelIndex: UInt8, + 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.receivedAt >= earliest && entry.receivedAt <= latest + } + 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 +463,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).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 7ac735a935..4917fc4bc4 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 @@ -198,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, @@ -209,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, @@ -217,32 +221,23 @@ 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 - } - } + if let match = candidates.first(where: isWanted) { + logger.debug("[REACTION-MATCH] Found match!") + return match + } - guard candidateHash == parsedReaction.messageHash else { - logger.debug("[REACTION-MATCH] Hash mismatch: \(candidateHash) != \(parsedReaction.messageHash)") - continue + 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 message in try modelContext.fetch(descriptor) { + let candidate = MessageDTO(from: message) + if candidate.isDatagramMCOImage, isWanted(candidate) { + logger.debug("[REACTION-MATCH] Found datagram match") + return candidate } - - logger.debug("[REACTION-MATCH] Found match!") - return candidate } logger.debug("[REACTION-MATCH] No match found") @@ -529,6 +524,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 @@ -806,6 +814,58 @@ public extension PersistenceStore { // MARK: - Heard Repeats + /// 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] { + 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/PersistenceStore+OutgoingReactions.swift b/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift index 36cec2c74f..e1b0fbe853 100644 --- a/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift +++ b/MC1Services/Sources/MC1Services/Services/PersistenceStore+OutgoingReactions.swift @@ -6,10 +6,14 @@ 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 = 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/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 4b51ddb790..1198280088 100644 --- a/MC1Services/Sources/MC1Services/Services/ReactionService.swift +++ b/MC1Services/Sources/MC1Services/Services/ReactionService.swift @@ -71,24 +71,15 @@ public actor ReactionService { public func indexMessage( id: UUID, channelIndex: UInt8, - senderName: String, - text: String, - timestamp: UInt32 + target: ChannelReactionTarget ) async -> [PendingReaction] { - await messageCache.index( - messageID: id, - channelIndex: channelIndex, - senderName: senderName, - text: text, - timestamp: timestamp - ) + await messageCache.index(messageID: id, channelIndex: channelIndex, target: target) // Check pending queue for matching reactions - let hash = ReactionParser.generateMessageHash(text: text, timestamp: timestamp) let key = PendingReactionKey( channelIndex: channelIndex, - targetSender: senderName, - messageHash: hash + targetSender: target.senderName, + messageHash: target.messageHash ) guard let matched = pendingReactions.removeValue(forKey: key) else { @@ -109,8 +100,15 @@ public actor ReactionService { targetText: String, targetTimestamp: UInt32 ) -> String { - let hash = ReactionParser.generateMessageHash(text: targetText, timestamp: targetTimestamp) - return "@[\(targetSender)]\(emoji)\n\(hash)" + buildReactionText( + emoji: emoji, + target: ChannelReactionTarget(senderName: targetSender, text: targetText, timestamp: targetTimestamp) + ) + } + + /// 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/Services/RxLogService+RegionResolution.swift b/MC1Services/Sources/MC1Services/Services/RxLogService+RegionResolution.swift index 0c8faea989..22fd99d3b5 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,31 @@ extension RxLogService { if !rxUpdates.isEmpty { try await dataStore.batchUpdateRxLogRegion(updates: rxUpdates) } + 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, + receivedWithin: MCOImageTransport.datagramReceiveWindow(around: earliest).lowerBound + ... MCOImageTransport.datagramReceiveWindow(around: latest).upperBound + ) + 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+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..89e4f92cf0 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,21 +59,52 @@ 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: .datagram(frame, senderName: decoded.senderName, text: decoded.text, channel: channel), + receivedAt: arrivedAt, + context: context, + dependencies: dependencies, + selfNodeName: selfNodeName, + scope: scope, + preference: preference + ) + } + } + // MARK: - Incoming Message Pipeline - /// Discriminates the two text-message ingestion paths, carrying the wire + /// 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?) + /// 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?) - /// Log noun distinguishing the two paths in shared diagnostics. + /// Log noun distinguishing the paths in shared diagnostics. var logLabel: String { switch self { case .direct: "direct" - case .channel: "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 @@ -127,6 +159,82 @@ 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, + receivedWithin: MCOImageTransport.datagramReceiveWindow(around: messageDTO.timestamp) + ) + 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, 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, + 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, + timestampWindow: MCOImageTransport.datagramMatchWindow(around: message.timestamp) + ) + 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( @@ -221,11 +329,22 @@ extension SyncCoordinator { contactID = nil channelIndex = message.channelIndex senderKeyPrefix = nil + 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 = message.channelIndex + senderKeyPrefix = nil } let timestamp = UInt32(senderTimestampDate.timeIntervalSince1970) - // Correct invalid timestamps (sender clock wrong) + // 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, timestampCorrected) = Self.correctTimestampIfNeeded(timestamp, receiveTime: receiveTime) if timestampCorrected { @@ -237,18 +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. - let deduplicationKey = Self.fallbackDeduplicationKey( - contactID: contactID, channelIndex: channelIndex, - senderNodeName: senderNodeName, timestamp: timestamp, content: text + // 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: resolvedKind.hasSenderClock ? timestamp : finalTimestamp, + content: text ) // Channel lookup joins decrypted 0x88 rows by DeduplicationKey; DMs still - // match timestamp then sender-prefix. + // 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: timestamp, + senderTimestamp: resolvedKind.hasSenderClock ? timestamp : nil, senderPublicKeyPrefix: senderKeyPrefix, defaultPathLength: reportedPathLength, channelDeduplicationKey: channelIndex != nil ? deduplicationKey : nil @@ -260,9 +384,11 @@ extension SyncCoordinator { case .direct: !selfNodeName.isEmpty && MentionUtilities.containsSelfMention(in: text, selfName: selfNodeName) - case .channel: + 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) } @@ -321,64 +447,103 @@ extension SyncCoordinator { scope: scope, preference: preference, dependencies: dependencies ) - case let .channel(message, channel): - if await recordChannelArrivalAndSkipDuplicate( + case let .channel(frame, channel), let .datagram(frame, _, _, channel): + await receiveChannelMessage( + messageDTO, + frame: frame, 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, + channel: channel, 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 = try await harvestAndRefreshChannelMessage( - messageDTO: messageDTO, - radioID: radioID, + ) + } + } + + private func receiveChannelMessage( + _ message: MessageDTO, + frame: ChannelMessage, + deduplicationKey: String, + rxResult: RxLogLookupResult, + channel: ChannelDTO?, + selfNodeName: String, + scope: ReceiveScope, + preference: TextRulesPreference?, + dependencies: SyncDependencies + ) async { + if await skipExistingDatagramPicture( + message, dependencies: dependencies, scope: scope + ) { + return + } + // 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, + snr: message.snr, + receiveTime: message.createdAt, + dependencies: dependencies, + scope: scope + ) { + return + } + guard scope.isCurrent else { return } + if isBlockedSender(message.senderNodeName) { + return + } + do { + 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)") + 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: channel?.textRulesID + ), + scope.isCurrent else { return } + let savedDTO = if message.isDatagramMCOImage { + try await harvestDatagramAndRefresh( + messageDTO: message, dependencies: dependencies, scope: scope ) - try await indexAndNotifyChannelMessage( - messageDTO: savedDTO, - channel: channel, + } else { + 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)") } + try await indexAndNotifyChannelMessage( + messageDTO: savedDTO, + channel: channel, + dependencies: dependencies, + scope: scope + ) + await notifyConversationsChanged(scope: scope) + } catch { + logger.error("Failed to save channel message: \(error)") } } @@ -492,13 +657,11 @@ extension SyncCoordinator { ) 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 { + if let target = messageDTO.channelReactionTarget(localNodeName: nil) { let pendingMatches = await dependencies.reactionService.indexMessage( id: messageDTO.id, channelIndex: channelIndex, - senderName: senderName, - text: messageDTO.text, - timestamp: messageDTO.reactionTimestamp + target: target ) for pending in pendingMatches { @@ -713,6 +876,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 .datagram = 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/Sync/SyncCoordinator+ReactionHandlers.swift b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift index 5d4a292817..722d7203f7 100644 --- a/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift +++ b/MC1Services/Sources/MC1Services/Sync/SyncCoordinator+ReactionHandlers.swift @@ -228,21 +228,13 @@ extension SyncCoordinator { 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 { + 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, - senderName: targetSenderName, - text: targetMessage.text, - timestamp: targetMessage.reactionTimestamp + target: target ) } @@ -360,6 +352,7 @@ extension SyncCoordinator { for candidate in candidates { // Skip messages that are themselves reactions if ReactionParser.isReactionText(candidate.text, isDM: false) { continue } + if candidate.isChannelMCOImage { continue } // For channel messages, the Dart hash includes the sender name let candidateSenderName: String? = if candidate.direction == .outgoing { @@ -472,6 +465,7 @@ extension SyncCoordinator { for candidate in candidates { if ReactionParser.isReactionText(candidate.text, isDM: false) { continue } + if candidate.isChannelMCOImage { continue } // Verify sender name hash let candidateSenderName: String? = if candidate.direction == .outgoing { 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/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..b988b31651 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOImageTransport.swift @@ -0,0 +1,86 @@ +import Foundation +import MeshCore + +/// 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 + 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 + + /// 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) + } + + /// 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) + 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..fad53af475 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBase91.swift @@ -0,0 +1,64 @@ +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 + + /// 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 + 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..698566ae72 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitReader.swift @@ -0,0 +1,85 @@ +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: try read(2) + case 1: try read(4) + 4 + case 2: try read(8) + 20 + default: 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..926946bf25 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageBitWriter.swift @@ -0,0 +1,46 @@ +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..c0a665d273 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageCodec.swift @@ -0,0 +1,97 @@ +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 isMCOImageText(_ text: String) -> Bool { + 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 + } + + 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 try .raster(MCOImageV3Codec.decodeBody(body)) + case v4Version: return try .document(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 } + 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) + } + + 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 + } + } + + /// 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: ":"), + MCOImageBase91.isEncodedText(text[text.index(after: colon)...]) 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..35c2f5c725 --- /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..d8eaf075e0 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImagePalette.swift @@ -0,0 +1,51 @@ +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..0cce5f046c --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Bitplanes.swift @@ -0,0 +1,60 @@ +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..4fbab5243c --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+CompactRows.swift @@ -0,0 +1,91 @@ +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..417d73961b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+Containers.swift @@ -0,0 +1,111 @@ +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 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) + 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 try Array(repeating: 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 { + try writer.write(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..94ed3d87a0 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec+LocalPalette.swift @@ -0,0 +1,108 @@ +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..a4d41d5f8b --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV3Codec.swift @@ -0,0 +1,142 @@ +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..8fe8bf358d --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4BitReader.swift @@ -0,0 +1,71 @@ +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 try Data((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..ad4e6d472e --- /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 = try Extended(rawValue: 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..485bf3ba30 --- /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..3646cbedd7 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser+Paths.swift @@ -0,0 +1,78 @@ +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 { + try previous.translated(x: reader.signed(shortBits), y: reader.signed(shortBits)) + } else { 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..61bdc4f10a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageV4Parser.swift @@ -0,0 +1,195 @@ +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 = try String(data: reader.data(count), encoding: .utf8) else { + throw MCOImageCodecError.damaged + } + targetName = name + } + if flags & Field.replyFlag != 0 { + 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 } + } + 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 = try Opcode(rawValue: 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..ab5be172c6 --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOImageWireBudget.swift @@ -0,0 +1,3 @@ +public enum MCOImageWireBudget { + public static let maximumChannelDataBytes = PacketBuilder.channelDataMaxPayloadBytes +} diff --git a/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift new file mode 100644 index 0000000000..ef2da0a42f --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextBitReader.swift @@ -0,0 +1,39 @@ +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..584e20186a --- /dev/null +++ b/MC1Services/Sources/MC1Services/Utilities/MCOimg/MCOTextDecoder.swift @@ -0,0 +1,167 @@ +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 + try output.append(contentsOf: 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.. (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, + timestamp: UInt32 = 1_700_000_000 + ) -> MessageDTO { + var message = MessageDTO.testChannelMessage( + id: id, + radioID: radioID, + channelIndex: channelIndex, + text: text, + timestamp: timestamp, + 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/Fixtures/MCOTextFixtures.json b/MC1Services/Tests/MC1ServicesTests/Fixtures/MCOTextFixtures.json new file mode 100644 index 0000000000..86947a4449 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Fixtures/MCOTextFixtures.json @@ -0,0 +1,108 @@ +{ + "reference": "9.5.1-mod-1.9.0", + "source": "independent field assembly and frozen generation 0 Dart model tables", + "fixtures": [ + { + "name": "all predictions en", + "dataBase64": "IHgEBQGgPBIKgtBeEQlCaE8MhqG0N4hEURojxSKorRXjEZRmjPHI6jtHeQSFIaQ8kkqS0l5RKUppTyyWpbS3mExTGmPNJqmtNecTlOac88nqe096BQVBqD0SiqLUXpFJUmpPTKaptTeoVFUao9Uqqq1V6xWVZqz1yuq7V3sFhWGsPZLKstZe0Wlaa09stq21t7hcVxrj3S6rrXXvF5XmvPfL6vtffgHAXAbgPwTgrgtwX4Rwlwm4T8M4a4bcN+IcRcRuI/5ME/KwV+WwW/L4Lg==", + "bitLength": 1663, + "text": " t a i sonoro oud dodedaanatala initisi lllol lerer rnromemom may yoyeyst thtotecochcacepepsp powewiwaw s stseshf fofrfig goghgehehahohibebubobangn ninee eresenkek kskiutusu urveviv4vax xtxpxi101 1512jujojaje3 30363d2 2225208 8m86804 404446zezzzyzi5 505652quq qmqt6 6069687 7l7c7r9 969d990 000m09h. m.st.ti.m" + }, + { + "name": "all predictions ru", + "dataBase64": "IPgEBQGgPBIKgtBeEQlCaE8MhqG0N4hEURojxSKorRXjEZRmjPHI6jtHeQSFIaQ8kkqS0l5RKUppTyyWpbS3mExTGmPNJqmtNecTlOac88nqe096BQVBqD0SiqLUXpFJUmpPTKaptTeoVFUao9Uqqq1V6xWVZqz1yuq7V3sFhWGsPZLKstZe0Wlaa09stq21t7hcVxrj3S6rrXXvF5XmvPfL6vtffgHAXAbgPwTgrgtwX4Rwlwm4T8M4a4bcN+IcRcRuI/FOKuK3FfjHGXGbjPxzjrjtx35ByFyG5D8k5K5Lcl+UcpcpuU/LOWuW3Lf8mCflYK/LYLfl8Fw=", + "bitLength": 2006, + "text": " н п с встсес сом мемомау утудужрорарерикокак кие етенерлильлоленанонении итиниля ятязялтотат тьбобрбыбедадодедив вевавогогдгагичечтчачиа алакатзаз знзио отодовы ыйышылпопрпипай йтйчйкхох хахужежнжджишешишашкю ютючюсь ьнькьсэтэкэнэлщещащёщицицецац фифофлфе1 1011142 2025223 303332ё ётёмёл4 4043455 5055568 8680827 7770756 6568609 9990950 000м0къеъяъёъип. н.т .1д.к" + }, + { + "name": "all predictions fr", + "dataBase64": "IXgEBQGgPBIKgtBeEQlCaE8MhqG0N4hEURojxSKorRXjEZRmjPHI6jtHeQSFIaQ8kkqS0l5RKUppTyyWpbS3mExTGmPNJqmtNecTlOac88nqe096BQVBqD0SiqLUXpFJUmpPTKaptTeoVFUao9Uqqq1V6xWVZqz1yuq7V3sFhWGsPZLKstZe0Wlaa09stq21t7hcVxrj3S6rrXXvF5XmvPfL6vtffgHAXAbgPwTgrgtwX4Rwlwm4T8M4a4bcN+IcRcRuI/FOKuK3FfjHGXGbjPxzjrjtx35ByFyG5D8k5K5Lcl+UcpcpuU/LOWuW3LfmHMXMbmPzTmrmtzX5xzlzm5z885657c9+gdBdBug/ROiui3RfpHSXSbpP0zprpt036h1F1G6j/kwT8rBX5bBb8vgu", + "bitLength": 2447, + "text": " d p l suru utuit tetitocochcecamemamomir rerarolelalll onouoiori isinire eseneraia anass stsesan ntnensvevovivapapopeprété éeépjejojujabobiblbededid dugegrgagnhehohah fafrfifoquq qqqry yeyoytçaçuçoç à àeàsàak kekaki2 202129x xextxo1 1311175 505952z zazezi4 494443wiwewawo3 3334387371707 6 686264èsèrètèm0 0006078 868m8fêtêmêvê 9 9a9f9eôtôlôpô înîtîlîcù ùeùsùaûrû ûeûsürü üeüsëlë ëeësœiœ œeœsâ âeâsâaæ æeæsæaï ïeïsïaÿ ÿeÿsÿab. s.at.ec.n" + }, + { + "name": "all predictions de", + "dataBase64": "IfgEBQGgPBIKgtBeEQlCaE8MhqG0N4hEURojxSKorRXjEZRmjPHI6jtHeQSFIaQ8kkqS0l5RKUppTyyWpbS3mExTGmPNJqmtNecTlOac88nqe096BQVBqD0SiqLUXpFJUmpPTKaptTeoVFUao9Uqqq1V6xWVZqz1yuq7V3sFhWGsPZLKstZe0Wlaa09stq21t7hcVxrj3S6rrXXvF5XmvPfL6vtffgHAXAbgPwTgrgtwX4Rwlwm4T8M4a4bcN+IcRcRuI/FOKuK3FfjHGXGbjPxzjrjtx35ByFyG5D/kwT8rBX5bBb8vguA=", + "bitLength": 1859, + "text": " a d m is stsesct tetattbebibab h hahehtoroionopgegugrg lllelil inicieitmomemiman ndnenar rergrausutunurwewiwawokekokak fefaf frenere eichckcoc auanalacdedad dizuzeztz pspepppfüßürübücvovevivujejajojuönörölögätäääuän1 1011123 3130382 202723yty yeyo5 505h579 9h90984 4740466 6163667 7371748 818386ßeß ßtßix xixtxe0 000607quq qtqsg. m.bh.dd.a" + }, + { + "name": "all predictions it", + "dataBase64": "IngEBQGgPBIKgtBeEQlCaE8MhqG0N4hEURojxSKorRXjEZRmjPHI6jtHeQSFIaQ8kkqS0l5RKUppTyyWpbS3mExTGmPNJqmtNecTlOac88nqe096BQVBqD0SiqLUXpFJUmpPTKaptTeoVFUao9Uqqq1V6xWVZqz1yuq7V3sFhWGsPZLKstZe0Wlaa09stq21t7hcVxrj3S6rrXXvF5XmvPfL6vtffgHAXAbgPwTgrgtwX4Rwlwm4T8M4a4bcN+IcRcRuI/FOKuK3FfjHGXGbjPxzjrjtx35ByFyG5D8k5K5Lcl+UcpcpuU/LOWuW3LfmHMXMbmPzTmrmtzX/Jgn5WCvy2C35fBc=", + "bitLength": 2104, + "text": " a s d ctetitottlal lelimemimamopepopspruounutuai ioiainrerarirococichcesesastsigigggrgavevavovie ereneso onoropa analarnon nantdadidodebubebibahohehihazizazzzofafifefoquqtq qrè èoèaèi1 10121a3 3b333h2 2028294 49454hwiwaw wek kikrku737 7f756 6168658 868b8f5 505156yty ygysà àoàaàiì ìaìnìo9 9o9192ò òeòoòa0 000206ù ùoùaùijnjoj jaé éoéaéix xcxuxdí íoíaíió óoóaóiú úoúaúib. c.is.ai.r" + }, + { + "name": "all predictions uk", + "dataBase64": "IvgEBQGgPBIKgtBeEQlCaE8MhqG0N4hEURojxSKorRXjEZRmjPHI6jtHeQSFIaQ8kkqS0l5RKUppTyyWpbS3mExTGmPNJqmtNecTlOac88nqe096BQVBqD0SiqLUXpFJUmpPTKaptTeoVFUao9Uqqq1V6xWVZqz1yuq7V3sFhWGsPZLKstZe0Wlaa09stq21t7hcVxrj3S6rrXXvF5XmvPfL6vtffgHAXAbgPwTgrgtwX4Rwlwm4T8M4a4bcN+IcRcRuI/FOKuK3FfjHGXGbjPxzjrjtx35ByFyG5D8k5K5Lcl+UcpcpuU/LOWuW3Lf8mCflYK/LYLfl8Fw=", + "bitLength": 2006, + "text": " п в н ткокакикустсьсяспрорарериі ідінілмомам меу увутулнаноненізаз знзібубабобілельлилядодадедуо омоводи ивитися якятява анатале енеремтатитотьв вавивішишошешучичачечой йнйтйогогагігрпрпопіпежежнж жию юєютювцеціцюцях хохихтє єтємєдщощещащуфіфофафтї їхїїїн2 2226203 323330ь ьнькьс12101 154 4347405 5в5052808 8682686 62637 707к7м0 000к0м969 999гґ ґоґаґн . т.5н.0д.1" + }, + { + "name": "all predictions be", + "dataBase64": "I3gEBQGgPBIKgtBeEQlCaE8MhqG0N4hEURojxSKorRXjEZRmjPHI6jtHeQSFIaQ8kkqS0l5RKUppTyyWpbS3mExTGmPNJqmtNecTlOac88nqe096BQVBqD0SiqLUXpFJUmpPTKaptTeoVFUao9Uqqq1V6xWVZqz1yuq7V3sFhWGsPZLKstZe0Wlaa09stq21t7hcVxrj3S6rrXXvF5XmvPfL6vtffgHAXAbgPwTgrgtwX4Rwlwm4T8M4a4bcN+IcRcRuI/FOKuK3FfjHGXGbjPxzjrjtx35ByFyG5D8k5K5Lcl+UcpcpuU/5ME/KwV+WwW/L4Lg=", + "bitLength": 1957, + "text": " н п в скакок кллольл ламом мемастс сесое етенеррорарерув вавевонаноненуя ятязяндедодадуу утужустотат тьчечачтчно одоботпопрпапезаз знзоы ыйылытй йтйкйсгогргдгабобыбубржежнжужаа аласатшешьшаштючю ютюдхох хахзь ьньшьтэтэкэфэв2 222024фофафффуцецацвцы10151 114 454840ё ётёмёо3 3032346 686769868 858о5 50565с7 767275000 0205909 9м93і іоіеіаў ўоўеўа . т.тн.2е.7" + }, + { + "name": "encoded text 0", + "dataBase64": "IH8EUTemQVFhFh7WHv/uY0RH7nJL1AiywA==", + "bitLength": 194, + "text": "Hello World 123!\nWAIT for Help" + }, + { + "name": "encoded text 1", + "dataBase64": "IP8J5yTQpMTBP2iE122cTgg=", + "bitLength": 133, + "text": "Привет мир. ПОМОЩЬ 42" + }, + { + "name": "encoded text 2", + "dataBase64": "IX9Sn0LJFVhYp6fWHnMWSHyifhg=", + "bitLength": 157, + "text": "Déjà reçu: Équipe à côté!" + }, + { + "name": "encoded text 3", + "dataBase64": "If9BUt+KYR+4zVpR+5jJozWeKLBA", + "bitLength": 162, + "text": "Straße, GRÜN und größer." + }, + { + "name": "encoded text 4", + "dataBase64": "In8lBfhYp6sSjhFUjYI=", + "bitLength": 111, + "text": "Città: È già qui." + }, + { + "name": "encoded text 5", + "dataBase64": "Iv9XHT0cI9fsT4MCIctkoOCA", + "bitLength": 137, + "text": "Привіт, Їжак і ґанок." + }, + { + "name": "encoded text 6", + "dataBase64": "IN8Kp9SeiKO2Eek0JU+HGhLD", + "bitLength": 144, + "text": "Прывітанне, Беларусь!" + }, + { + "name": "encoded text 7", + "dataBase64": "IV9JanGkKp8ehxoUKC1U+9VTNYBHggtLhp/SIUqNIlNH+PRoMNX3hJkek0JU+HGhQVOA", + "bitLength": 402, + "text": "English Русский Français Deutsch Italiano Українська Беларуская" + }, + { + "name": "encoded text 8", + "dataBase64": "I5Dwn5mCIOadseS6rCDOms6xzrvOt868zq3Pgc6x", + "bitLength": 240, + "text": "🙂 東京 Καλημέρα" + }, + { + "name": "encoded text 9", + "dataBase64": "IHA=", + "bitLength": 12, + "text": "" + } + ] +} \ No newline at end of file diff --git a/MC1Services/Tests/MC1ServicesTests/Fixtures/MCOimgV4Fixtures.json b/MC1Services/Tests/MC1ServicesTests/Fixtures/MCOimgV4Fixtures.json new file mode 100644 index 0000000000..b001d88e6e --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Fixtures/MCOimgV4Fixtures.json @@ -0,0 +1,4083 @@ +{ + "source": "independent command-test bit assembly", + "fixtures": [ + { + "bodyBase64": "AAgPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AEgzAQ==", + "document": { + "width": 20, + "height": 10, + "profile": 2, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AIjnDwA=", + "document": { + "width": 40, + "height": 64, + "profile": 2, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AIjgAQA=", + "document": { + "width": 33, + "height": 8, + "profile": 2, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AMjGAA==", + "document": { + "width": 100, + "height": 100, + "profile": 2, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AMjHjgE=", + "document": { + "width": 100, + "height": 200, + "profile": 2, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AMj/AQA=", + "document": { + "width": 256, + "height": 1, + "profile": 2, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AEgpAQ==", + "error": "damaged" + }, + { + "bodyBase64": "AIjnCQA=", + "error": "damaged" + }, + { + "bodyBase64": "AIhTAgA=", + "error": "damaged" + }, + { + "bodyBase64": "AMh+AA==", + "error": "damaged" + }, + { + "bodyBase64": "AMjHxgA=", + "error": "damaged" + }, + { + "bodyBase64": "AMhPfgA=", + "error": "damaged" + }, + { + "bodyBase64": "AAjPAw==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 3, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAhPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": null, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAAPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 0, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAQPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 1, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAwPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 3, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ABAPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 4, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ABQPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 5, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ABgPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 6, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ABwPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 7, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ACAPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 8, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ACQPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 9, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ACgPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 10, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ACwPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 11, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ADAPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 12, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ADQPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 13, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ADgPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 14, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "ADwPAA==", + "document": { + "width": 16, + "height": 16, + "profile": 15, + "backgroundColor": 0, + "figures": [], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAoPAA==", + "error": "unsupported" + }, + { + "bodyBase64": "AAsPAA==", + "error": "unsupported" + }, + { + "bodyBase64": "AAkPAA==", + "error": "damaged" + }, + { + "bodyBase64": "AAgPIiSO4AM=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": 3, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 14, + 13 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPIuT3l0HwAQ==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": 3, + "strokeColor": 4, + "strokeWidth": 2 + }, + "kind": "dot", + "point": [ + 14, + 13 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPOMkhKgYA", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": 3, + "strokeColor": 4, + "strokeWidth": 5 + }, + "kind": "dot", + "point": [ + 3, + 4 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPUWMcBA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": null, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 1 + ], + "end": [ + 5, + 6 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPXwA=", + "error": "damaged" + }, + { + "bodyBase64": "AEgzGUxkAA==", + "error": "damaged" + }, + { + "bodyBase64": "AAgPKgYA", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 4 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPGiQtAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 2 + ], + "end": [ + 7, + 9 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPI2QlVQA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "rectangle", + "first": [ + 2, + 2 + ], + "second": [ + 9, + 7 + ], + "third": [ + 8, + 3 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPI2QlVQA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "ellipse", + "first": [ + 2, + 2 + ], + "second": [ + 9, + 7 + ], + "third": [ + 8, + 3 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPRMhKAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "rectangle", + "first": [ + 2, + 2 + ], + "second": [ + 9, + 7 + ], + "third": [ + 2, + 7 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPTMhKAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "rectangle", + "first": [ + 2, + 2 + ], + "second": [ + 9, + 7 + ], + "third": [ + 9, + 2 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPRshKAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "ellipse", + "first": [ + 2, + 2 + ], + "second": [ + 9, + 7 + ], + "third": [ + 2, + 7 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPRQhDBAA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "wave", + "start": [ + 2, + 2 + ], + "end": [ + 10, + 6 + ], + "depth": 3, + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPTQhDAwA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "wave", + "start": [ + 2, + 2 + ], + "end": [ + 10, + 6 + ], + "depth": -2, + "closed": true + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPI4SQcwA=", + "error": "damaged" + }, + { + "bodyBase64": "AAgPQYQA", + "error": "damaged" + }, + { + "bodyBase64": "AEgzWWRYwQA=", + "error": "damaged" + }, + { + "bodyBase64": "AAiPBwjxAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 2, + 2 + ], + "end": [ + 5, + 0 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AMj+PKChYQI=", + "document": { + "width": 128, + "height": 128, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 10, + 10 + ], + "end": [ + 13, + 12 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPv2QsAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 2, + 1 + ], + "end": [ + 2, + 9 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPP2UsAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 3 + ], + "end": [ + 9, + 3 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPj5HBAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 2, + 1 + ], + "end": [ + 2, + 7 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPFxBiwAA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "rectangle", + "first": [ + 2, + 2 + ], + "second": [ + 5, + 2 + ], + "third": [ + 5, + 5 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPlxBiwAA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "ellipse", + "first": [ + 2, + 2 + ], + "second": [ + 5, + 2 + ], + "third": [ + 5, + 5 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPFxBipgA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "rectangle", + "first": [ + 2, + 2 + ], + "second": [ + 5, + 4 + ], + "third": [ + 4, + 1 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPnwVCLAA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "wave", + "start": [ + 2, + 2 + ], + "end": [ + 5, + 3 + ], + "depth": -3, + "closed": true + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPR2KYIQA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "ellipse", + "first": [ + 2, + 4 + ], + "second": [ + 10, + 4 + ], + "third": [ + 6, + 7 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPR2KYGQA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "ellipse", + "first": [ + 2, + 4 + ], + "second": [ + 10, + 4 + ], + "third": [ + 6, + 2 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPRyGKAAA=", + "error": "damaged" + }, + { + "bodyBase64": "AAiP14gQSQI=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 3 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 4, + 4 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPVyTEleLeAw==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 12, + 3 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 12 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 13, + 13 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPB2I0AA==", + "error": "damaged" + }, + { + "bodyBase64": "AAiPrDHQQGggAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 1, + 1 + ], + [ + 6, + 1 + ], + [ + 6, + 6 + ], + [ + 1, + 6 + ] + ], + "closed": true + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPhcYg6gAA", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + [ + 12, + 2 + ] + ], + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPJ2gMbgA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 1, + 1 + ], + [ + 4, + 1 + ], + [ + 4, + 4 + ] + ], + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPp2gMbgU=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 1, + 1 + ], + [ + 4, + 1 + ], + [ + 4, + 4 + ], + [ + 1, + 4 + ] + ], + "closed": true + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPryqFCEAoBA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 3, + 3 + ], + [ + 7, + 3 + ], + [ + 7, + 5 + ], + [ + 3, + 5 + ] + ], + "closed": true + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPN6kUIgACEAA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 3, + 3 + ], + [ + 7, + 3 + ], + [ + 7, + 5 + ] + ], + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPL4DwBEgA", + "error": "damaged" + }, + { + "bodyBase64": "AAiPLyiFACgA", + "error": "damaged" + }, + { + "bodyBase64": "AAiPFAgxBBFFGHEEAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 0, + 0 + ], + [ + 1, + 0 + ], + [ + 2, + 0 + ], + [ + 3, + 0 + ], + [ + 4, + 0 + ], + [ + 5, + 0 + ] + ], + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPNAAhhiCiCCOOQCIJJZZgogknnoAiCjHGIKMMM84A", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 0, + 0 + ], + [ + 1, + 0 + ], + [ + 2, + 0 + ], + [ + 3, + 0 + ], + [ + 4, + 0 + ], + [ + 5, + 0 + ], + [ + 6, + 0 + ], + [ + 7, + 0 + ], + [ + 8, + 0 + ], + [ + 9, + 0 + ], + [ + 10, + 0 + ], + [ + 11, + 0 + ], + [ + 12, + 0 + ], + [ + 13, + 0 + ], + [ + 14, + 0 + ], + [ + 15, + 0 + ], + [ + 0, + 1 + ], + [ + 1, + 1 + ], + [ + 2, + 1 + ], + [ + 3, + 1 + ], + [ + 4, + 1 + ], + [ + 5, + 1 + ] + ], + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPdEoBIYYgoggjjkAiCSWWYKIJJ56AIgoxxiCjDDPOQCMNNdZgow033oAjDkEGIaQQQw5BJBFFFmGkEUcegSQSUUYhpRRTTkElFVVWYaUVV16BJRZhhiGmGGOOQSYZZZZhphlnnoEmGnHGIaccc85BJx111mGnHXfegScegQYiqCCDDkIoIYUWYqghhx6CKCKRRiKpJJNOQikllVZiqSWXXoIpJqGGIqooo45CKimllmKqKaeegioqscYiqyyzzkIrLbXWYqstt96CKy7BBiOsMMMOQywxxRZjrDHHHoMsMtFGI600005DLTXVVmOtNddegy024YYjrjjjjkMuOeWWY645556DLjrxxiOvPPPOQy899dZjrz333oMvPgEHJLBAAw9EMEEFF2SwQQcfhDBCEUcksUQTT0QxRRVXZLFFF1+EMUYhhiCiCCOOQCIJJZZgogknnoAiCjHGIKMMM84A", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 0, + 0 + ], + [ + 1, + 0 + ], + [ + 2, + 0 + ], + [ + 3, + 0 + ], + [ + 4, + 0 + ], + [ + 5, + 0 + ], + [ + 6, + 0 + ], + [ + 7, + 0 + ], + [ + 8, + 0 + ], + [ + 9, + 0 + ], + [ + 10, + 0 + ], + [ + 11, + 0 + ], + [ + 12, + 0 + ], + [ + 13, + 0 + ], + [ + 14, + 0 + ], + [ + 15, + 0 + ], + [ + 0, + 1 + ], + [ + 1, + 1 + ], + [ + 2, + 1 + ], + [ + 3, + 1 + ], + [ + 4, + 1 + ], + [ + 5, + 1 + ], + [ + 6, + 1 + ], + [ + 7, + 1 + ], + [ + 8, + 1 + ], + [ + 9, + 1 + ], + [ + 10, + 1 + ], + [ + 11, + 1 + ], + [ + 12, + 1 + ], + [ + 13, + 1 + ], + [ + 14, + 1 + ], + [ + 15, + 1 + ], + [ + 0, + 2 + ], + [ + 1, + 2 + ], + [ + 2, + 2 + ], + [ + 3, + 2 + ], + [ + 4, + 2 + ], + [ + 5, + 2 + ], + [ + 6, + 2 + ], + [ + 7, + 2 + ], + [ + 8, + 2 + ], + [ + 9, + 2 + ], + [ + 10, + 2 + ], + [ + 11, + 2 + ], + [ + 12, + 2 + ], + [ + 13, + 2 + ], + [ + 14, + 2 + ], + [ + 15, + 2 + ], + [ + 0, + 3 + ], + [ + 1, + 3 + ], + [ + 2, + 3 + ], + [ + 3, + 3 + ], + [ + 4, + 3 + ], + [ + 5, + 3 + ], + [ + 6, + 3 + ], + [ + 7, + 3 + ], + [ + 8, + 3 + ], + [ + 9, + 3 + ], + [ + 10, + 3 + ], + [ + 11, + 3 + ], + [ + 12, + 3 + ], + [ + 13, + 3 + ], + [ + 14, + 3 + ], + [ + 15, + 3 + ], + [ + 0, + 4 + ], + [ + 1, + 4 + ], + [ + 2, + 4 + ], + [ + 3, + 4 + ], + [ + 4, + 4 + ], + [ + 5, + 4 + ], + [ + 6, + 4 + ], + [ + 7, + 4 + ], + [ + 8, + 4 + ], + [ + 9, + 4 + ], + [ + 10, + 4 + ], + [ + 11, + 4 + ], + [ + 12, + 4 + ], + [ + 13, + 4 + ], + [ + 14, + 4 + ], + [ + 15, + 4 + ], + [ + 0, + 5 + ], + [ + 1, + 5 + ], + [ + 2, + 5 + ], + [ + 3, + 5 + ], + [ + 4, + 5 + ], + [ + 5, + 5 + ], + [ + 6, + 5 + ], + [ + 7, + 5 + ], + [ + 8, + 5 + ], + [ + 9, + 5 + ], + [ + 10, + 5 + ], + [ + 11, + 5 + ], + [ + 12, + 5 + ], + [ + 13, + 5 + ], + [ + 14, + 5 + ], + [ + 15, + 5 + ], + [ + 0, + 6 + ], + [ + 1, + 6 + ], + [ + 2, + 6 + ], + [ + 3, + 6 + ], + [ + 4, + 6 + ], + [ + 5, + 6 + ], + [ + 6, + 6 + ], + [ + 7, + 6 + ], + [ + 8, + 6 + ], + [ + 9, + 6 + ], + [ + 10, + 6 + ], + [ + 11, + 6 + ], + [ + 12, + 6 + ], + [ + 13, + 6 + ], + [ + 14, + 6 + ], + [ + 15, + 6 + ], + [ + 0, + 7 + ], + [ + 1, + 7 + ], + [ + 2, + 7 + ], + [ + 3, + 7 + ], + [ + 4, + 7 + ], + [ + 5, + 7 + ], + [ + 6, + 7 + ], + [ + 7, + 7 + ], + [ + 8, + 7 + ], + [ + 9, + 7 + ], + [ + 10, + 7 + ], + [ + 11, + 7 + ], + [ + 12, + 7 + ], + [ + 13, + 7 + ], + [ + 14, + 7 + ], + [ + 15, + 7 + ], + [ + 0, + 8 + ], + [ + 1, + 8 + ], + [ + 2, + 8 + ], + [ + 3, + 8 + ], + [ + 4, + 8 + ], + [ + 5, + 8 + ], + [ + 6, + 8 + ], + [ + 7, + 8 + ], + [ + 8, + 8 + ], + [ + 9, + 8 + ], + [ + 10, + 8 + ], + [ + 11, + 8 + ], + [ + 12, + 8 + ], + [ + 13, + 8 + ], + [ + 14, + 8 + ], + [ + 15, + 8 + ], + [ + 0, + 9 + ], + [ + 1, + 9 + ], + [ + 2, + 9 + ], + [ + 3, + 9 + ], + [ + 4, + 9 + ], + [ + 5, + 9 + ], + [ + 6, + 9 + ], + [ + 7, + 9 + ], + [ + 8, + 9 + ], + [ + 9, + 9 + ], + [ + 10, + 9 + ], + [ + 11, + 9 + ], + [ + 12, + 9 + ], + [ + 13, + 9 + ], + [ + 14, + 9 + ], + [ + 15, + 9 + ], + [ + 0, + 10 + ], + [ + 1, + 10 + ], + [ + 2, + 10 + ], + [ + 3, + 10 + ], + [ + 4, + 10 + ], + [ + 5, + 10 + ], + [ + 6, + 10 + ], + [ + 7, + 10 + ], + [ + 8, + 10 + ], + [ + 9, + 10 + ], + [ + 10, + 10 + ], + [ + 11, + 10 + ], + [ + 12, + 10 + ], + [ + 13, + 10 + ], + [ + 14, + 10 + ], + [ + 15, + 10 + ], + [ + 0, + 11 + ], + [ + 1, + 11 + ], + [ + 2, + 11 + ], + [ + 3, + 11 + ], + [ + 4, + 11 + ], + [ + 5, + 11 + ], + [ + 6, + 11 + ], + [ + 7, + 11 + ], + [ + 8, + 11 + ], + [ + 9, + 11 + ], + [ + 10, + 11 + ], + [ + 11, + 11 + ], + [ + 12, + 11 + ], + [ + 13, + 11 + ], + [ + 14, + 11 + ], + [ + 15, + 11 + ], + [ + 0, + 12 + ], + [ + 1, + 12 + ], + [ + 2, + 12 + ], + [ + 3, + 12 + ], + [ + 4, + 12 + ], + [ + 5, + 12 + ], + [ + 6, + 12 + ], + [ + 7, + 12 + ], + [ + 8, + 12 + ], + [ + 9, + 12 + ], + [ + 10, + 12 + ], + [ + 11, + 12 + ], + [ + 12, + 12 + ], + [ + 13, + 12 + ], + [ + 14, + 12 + ], + [ + 15, + 12 + ], + [ + 0, + 13 + ], + [ + 1, + 13 + ], + [ + 2, + 13 + ], + [ + 3, + 13 + ], + [ + 4, + 13 + ], + [ + 5, + 13 + ], + [ + 6, + 13 + ], + [ + 7, + 13 + ], + [ + 8, + 13 + ], + [ + 9, + 13 + ], + [ + 10, + 13 + ], + [ + 11, + 13 + ], + [ + 12, + 13 + ], + [ + 13, + 13 + ], + [ + 14, + 13 + ], + [ + 15, + 13 + ], + [ + 0, + 14 + ], + [ + 1, + 14 + ], + [ + 2, + 14 + ], + [ + 3, + 14 + ], + [ + 4, + 14 + ], + [ + 5, + 14 + ], + [ + 6, + 14 + ], + [ + 7, + 14 + ], + [ + 8, + 14 + ], + [ + 9, + 14 + ], + [ + 10, + 14 + ], + [ + 11, + 14 + ], + [ + 12, + 14 + ], + [ + 13, + 14 + ], + [ + 14, + 14 + ], + [ + 15, + 14 + ], + [ + 0, + 15 + ], + [ + 1, + 15 + ], + [ + 2, + 15 + ], + [ + 3, + 15 + ], + [ + 4, + 15 + ], + [ + 5, + 15 + ], + [ + 6, + 15 + ], + [ + 7, + 15 + ], + [ + 8, + 15 + ], + [ + 9, + 15 + ], + [ + 10, + 15 + ], + [ + 11, + 15 + ], + [ + 12, + 15 + ], + [ + 13, + 15 + ], + [ + 14, + 15 + ], + [ + 15, + 15 + ], + [ + 0, + 0 + ], + [ + 1, + 0 + ], + [ + 2, + 0 + ], + [ + 3, + 0 + ], + [ + 4, + 0 + ], + [ + 5, + 0 + ], + [ + 6, + 0 + ], + [ + 7, + 0 + ], + [ + 8, + 0 + ], + [ + 9, + 0 + ], + [ + 10, + 0 + ], + [ + 11, + 0 + ], + [ + 12, + 0 + ], + [ + 13, + 0 + ], + [ + 14, + 0 + ], + [ + 15, + 0 + ], + [ + 0, + 1 + ], + [ + 1, + 1 + ], + [ + 2, + 1 + ], + [ + 3, + 1 + ], + [ + 4, + 1 + ], + [ + 5, + 1 + ] + ], + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiP9EkBAA==", + "error": "damaged" + }, + { + "bodyBase64": "AAiPdEAAAA==", + "error": "damaged" + }, + { + "bodyBase64": "AAiPdEBAQEDAAAA=", + "error": "damaged" + }, + { + "bodyBase64": "AAiPdFaBMQA=", + "error": "damaged" + }, + { + "bodyBase64": "AAgPIsQRAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 2 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AMj+PEkQELQyFAAA", + "document": { + "width": 128, + "height": 128, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 0, + 0 + ], + [ + 5, + 0 + ], + [ + 5, + 5 + ] + ], + "closed": false + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 40, + 0 + ], + [ + 45, + 0 + ], + [ + 45, + 5 + ] + ], + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPIoSNAAA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 5, + 1 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPJ2gMbmLsM5EA", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 1, + 1 + ], + [ + 4, + 1 + ], + [ + 4, + 4 + ] + ], + "closed": false + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 10, + 10 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 2, + 2 + ], + [ + 5, + 2 + ], + [ + 5, + 5 + ] + ], + "closed": false + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPIoTW+gxBAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 9, + 9 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 3 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPIkTOkQA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 3, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 3 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPGgMZueeRNBcA", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 1 + ], + "end": [ + 6, + 4 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 3, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 2, + 2 + ], + "end": [ + 7, + 5 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 4, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 3, + 3 + ], + "end": [ + 8, + 6 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 5, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 4, + 4 + ], + "end": [ + 9, + 7 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPGsOMZwACl9YC", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 1 + ], + "end": [ + 4, + 1 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 3 + ], + "end": [ + 4, + 3 + ] + }, + { + "style": { + "fillColor": 5, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 5 + ], + "end": [ + 4, + 5 + ] + }, + { + "style": { + "fillColor": 5, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 9, + 9 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPGuN5CAE=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 1, + 1 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 1 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 5, + 1 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 7, + 1 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPFgQA", + "error": "damaged" + }, + { + "bodyBase64": "AAiP55EAAA==", + "error": "damaged" + }, + { + "bodyBase64": "AAgPIoQK+UQkAA==", + "error": "damaged" + }, + { + "bodyBase64": "AAgPIoQK+VQkAA==", + "error": "damaged" + }, + { + "bodyBase64": "AAgPitGxAQ==", + "error": "damaged" + }, + { + "bodyBase64": "AAiPbxEhjgA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 2 + ] + } + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPuW8QIeQcAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 3, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 3, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + } + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 3, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 12, + 12 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPIuQbcnQOrQU=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 3, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 5, + 5 + ] + } + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 9, + 9 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPb3yLCKG1AA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 9, + 9 + ] + } + ] + } + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPGuNbdI4jAQ==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 1, + 1 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 5, + 5 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 6, + 6 + ] + } + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPb32LCKG1agxkCEIA", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 9, + 9 + ] + } + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 1 + ], + "end": [ + 6, + 4 + ] + } + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 14, + 14 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiPbwAA", + "error": "damaged" + }, + { + "bodyBase64": "AAiPb7wCIecA", + "error": "damaged" + }, + { + "bodyBase64": "AAmP9zHIBCQyxBgA", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": null, + "strokeWidth": 1 + }, + "kind": "raster", + "origin": [ + 1, + 1 + ], + "width": 2, + "height": 2, + "profile": 2, + "pixels": [ + 0, + 2, + 2, + 0 + ], + "transparentColor": null + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 10, + 10 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAmP9zHIBCQyLAgA", + "error": "damaged" + }, + { + "bodyBase64": "AAiP9zHIBCQyAA==", + "error": "damaged" + }, + { + "bodyBase64": "AAmPb7yPQSYgkQE=", + "error": "damaged" + }, + { + "bodyBase64": "AAmP9zFAAAA=", + "error": "damaged" + }, + { + "bodyBase64": "AMj+/AMGBjZA4A8H", + "document": { + "width": 128, + "height": 128, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "text", + "origin": [ + 8, + 8 + ], + "width": 120, + "fontSize": 15, + "alignment": 0, + "text": "Hi" + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAiP/wA=", + "error": "unsupported" + }, + { + "bodyBase64": "AMj+/AMGhu4JPAw=", + "error": "damaged" + }, + { + "bodyBase64": "AEgz+QcywT2BhwE=", + "error": "damaged" + }, + { + "bodyBase64": "AEgz+QcyxD2BhwE=", + "error": "damaged" + }, + { + "bodyBase64": "AMj+/AMGBkIBBw==", + "error": "unsupported" + }, + { + "bodyBase64": "AAgPygQA", + "error": "damaged" + }, + { + "bodyBase64": "AAiPAmBOAA==", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + -2, + -2 + ], + "end": [ + 17, + 17 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgP+A==", + "error": "damaged" + }, + { + "bodyBase64": "AAgPKgY=", + "error": "damaged" + }, + { + "bodyBase64": "", + "error": "damaged" + }, + { + "bodyBase64": "BwgPKgYAAwNCb2IEAwIB", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 4 + ] + } + ], + "targetName": "Bob", + "replyTimestamp": 16909060 + } + }, + { + "bodyBase64": "AAgPKgYAAQFB", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 4 + ] + } + ], + "targetName": "A", + "replyTimestamp": null + } + }, + { + "bodyBase64": "AAgPKgYAAgEAAAA=", + "document": { + "width": 16, + "height": 16, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 3, + 4 + ] + } + ], + "targetName": null, + "replyTimestamp": 1 + } + }, + { + "bodyBase64": "AAgPKgYABA==", + "error": "damaged" + }, + { + "bodyBase64": "AAgPKgYAAQA=", + "error": "damaged" + }, + { + "bodyBase64": "AAgPKgYAAgEAAACZ", + "error": "damaged" + }, + { + "bodyBase64": "AMj+kITEQxES7HEvJiFBqWH5vRQ8CgmBCUlIDUAnNY10SHZxfmnQMfk1yH6L6OgcSeofKBA/VmEwBPGQ56QhPmFOiIgA", + "document": { + "width": 128, + "height": 128, + "profile": 2, + "backgroundColor": 0, + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 2, + 2 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "line", + "start": [ + 1, + 2 + ], + "end": [ + 7, + 9 + ] + }, + { + "style": { + "fillColor": 3, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "rectangle", + "first": [ + 20, + 20 + ], + "second": [ + 40, + 30 + ], + "third": [ + 38, + 24 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 4, + "strokeWidth": 3 + }, + "kind": "ellipse", + "first": [ + 50, + 50 + ], + "second": [ + 80, + 50 + ], + "third": [ + 65, + 60 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "path", + "points": [ + [ + 90, + 10 + ], + [ + 100, + 12 + ], + [ + 95, + 30 + ], + [ + 91, + 22 + ] + ], + "closed": true + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "wave", + "start": [ + 10, + 100 + ], + "end": [ + 60, + 110 + ], + "depth": -7, + "closed": false + }, + { + "style": { + "fillColor": null, + "strokeColor": 5, + "strokeWidth": 1 + }, + "kind": "group", + "figures": [ + { + "style": { + "fillColor": null, + "strokeColor": 5, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 100, + 100 + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 5, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 101, + 101 + ] + } + ] + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "text", + "origin": [ + 4, + 120 + ], + "width": 100, + "fontSize": 6, + "alignment": 1, + "text": "Привет, mesh" + }, + { + "style": { + "fillColor": null, + "strokeColor": 2, + "strokeWidth": 1 + }, + "kind": "dot", + "point": [ + 120, + 120 + ] + } + ], + "targetName": null, + "replyTimestamp": null + } + } + ], + "decoderTag": "9.5.1-mod-1.9.0", + "decoderCommit": "fe375741226588440e268002b4975349b2e95ffe", + "assemblyCommit": "d388ee8444078635d74dd98ab288269c3a8a9162" +} diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift new file mode 100644 index 0000000000..252dfbc9b3 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageBinarySendTests.swift @@ -0,0 +1,279 @@ +import Foundation +@testable import MC1Services +import MeshCore +import Testing + +@Suite("MCOimg binary channel sending") +struct MCOImageBinarySendTests { + private let fixture = "im3:g/5WjAL`NA" + + enum SendPath: CaseIterable { case inline, pending, resend } + + @Test(arguments: SendPath.allCases) + func `every channel send path emits v4 GROUP_DATA and never text`(path: SendPath) 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: "救援隊", 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: stored, senderNodeName: "救援隊" + ) + try await store.saveMessage(legacy) + switch path { + case .inline: + _ = try await service.sendChannelMessage(text: fixture, channelIndex: channel.index, radioID: radioID) + case .pending: try await service.sendPendingChannelMessage(messageID: legacy.id) + case .resend: try await service.resendChannelMessage(messageID: legacy.id) + } + let call = try #require(await session.sendChannelDataInvocations.first) + #expect(await session.sendChannelDataInvocations.count == 1) + #expect(await session.sendChannelMessageInvocations.isEmpty) + #expect(call.channelIndex == channel.index) + #expect(call.dataType == 0x0120) + #expect(call.floodScope == .scope(.region("Alpha"))) + let nameBytes = "救援隊".utf8.count + #expect(call.payload.first == UInt8(nameBytes)) + let payload = Data(call.payload.dropFirst(1 + nameBytes)) + #expect(payload.first == 0x14) + let original = try MCOImageCodec.appPayload(fromText: fixture) + #expect(payload[1] == original[1]) + let document = try MCOImageV4Codec.decodeBody(Data(payload.dropFirst())) + #expect(try document.figures == [.raster(origin: .init(x: 0, y: 0), image: + MCOImageV3Codec.decodeBody(Data(original.dropFirst())))]) + let frame = try PacketBuilder.sendChannelData(channelIndex: channel.index, dataType: call.dataType, payload: call.payload) + #expect(frame.prefix(5) == Data([0x3E, channel.index, 0xFF, 0x20, 0x01])) + #expect(frame.count == call.payload.count + 5) + } + + @Test + func `automatic attempts retain payload while user resend persists a refreshed v4 nonce`() 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: 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) + let firstCalls = await session.sendChannelDataInvocations + #expect(firstCalls[0].payload == firstCalls[1].payload) + 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") + try await service.resendChannelMessage(messageID: message.id) + try await service.resendChannelMessage(messageID: message.id, preserveTimestamp: true) + let calls = await session.sendChannelDataInvocations + #expect(calls[2].payload == expected) + #expect(calls[3].payload == expected) + #expect(calls[0].payload.dropFirst(8) == calls[2].payload.dropFirst(8)) + #expect(await session.sendChannelMessageInvocations.isEmpty) + } + + @Test + func `complete UTF8 binary budget accepts 165 and rejects 166 at admission`() async throws { + let radioID = UUID() + let store = MockPersistenceStore() + let session = MockMeshCoreSession() + let service = MessageService(session: session, dataStore: store, contactService: nil) + let 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) + 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", firmwareVersion: 11)) + 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 == .sent) + } + + @Test(arguments: ["im3:!", "im4:!", "im5:AA"]) + 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() + let service = MessageService(session: session, dataStore: store, contactService: nil) + 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) + } + #expect(await session.sendChannelDataInvocations.isEmpty) + #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.channelReactionTarget(localNodeName: nil) != 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, 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) { + 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 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", firmwareVersion: 11)) + try await store.saveChannel(ChannelDTO.testChannel(radioID: radioID, index: 0)) + 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") + _ = 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", 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]) + 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), sentDatagram: true)) + #expect(!ChatSendQueueService.isTransientChannelMessageError(MeshCoreError.deviceError(code: 3), sentDatagram: 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..1f1d49736a --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageReceiveIntegrationTests.swift @@ -0,0 +1,499 @@ +import CommonCrypto +import CryptoKit +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, firmwareVersion: 11)) + 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.hasWireSendTime) + #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 + } + } + } + + @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, 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)) + 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("\(sender): \(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) + } + + @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() + defer { Task { await opened.services.tearDown() } } + let payload = try v3Payload() + 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)) + + 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 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() + 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.isDatagramMCOImage == false) + #expect(datagram.senderTimestamp == 0) + #expect(datagram.isDatagramMCOImage) + } + + @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, firmwareVersion: 11)) + 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, + pathLength: 2, + dataType: MCOImageTransport.applicationDataType, + data: Data([UInt8(sender.utf8.count)]) + Data(sender.utf8) + payload, + 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/MCOImageSendIntegrationTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageSendIntegrationTests.swift new file mode 100644 index 0000000000..1094dc9271 --- /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", 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", firmwareVersion: 11)) + 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 `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.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)) + #expect(refreshedPayload.count == originalPayload.count) + #expect(try await store.fetchMessage(id: original.id)?.text == refreshed.text) + #expect(refreshed.id == original.id) + } + + @Test + 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.prepareMCOImageForResend(original) == original) + } +} diff --git a/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift b/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift new file mode 100644 index 0000000000..4d3163b598 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/MCOImageTransportTests.swift @@ -0,0 +1,164 @@ +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 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))) + #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() + 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 + 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 + 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)])) + let admitted = duplicates.admit(packet, radioID: radioID, receivedAt: time) + #expect(admitted) + } + let evicted = duplicates.admit(datagram(payload: Data([0, 0x13, 0])), radioID: radioID, receivedAt: time) + #expect(evicted) + } + + private actor Receipt { + var received: [(ChannelDatagram, DeliveryContext)] = [] + + func record(_ packet: ChannelDatagram, context: DeliveryContext) { + received.append((packet, context)) + } + } + + @Test + 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() + 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..30a79ad4f7 --- /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 `decodes all upstream containers and algorithms`() 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 `encoding preserves pixels across profiles and nonces`() 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..31f02b186b 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 } @@ -221,34 +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 { - 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 + if let match = candidates.first(where: isWanted) { + return match } - - return nil + return messages.values + .filter { $0.radioID == radioID && $0.channelIndex == channelIndex && $0.isDatagramMCOImage } + .sorted { $0.createdAt > $1.createdAt } + .first(where: isWanted) } public func fetchChannelMessageCandidates( @@ -1150,6 +1142,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..5e5525b9ab 100644 --- a/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/PersistenceStoreTests.swift @@ -1090,6 +1090,211 @@ struct PersistenceStoreTests { #expect(found?.id == outgoingMessage.id) } + @Test + 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 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?.id == newer.id) + } + + @Test + 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) + 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: 1, + text: text, + timestamp: timestamp, + createdAt: Date(timeIntervalSince1970: TimeInterval(timestamp)), + direction: .incoming, + status: .delivered, + senderNodeName: sender + ) + timed.senderTimestamp = nil + timed.timestampCorrected = false + let datagram = datagramImage( + radioID: device.id, channelIndex: 2, text: text, sender: sender, + createdAt: Date(timeIntervalSince1970: TimeInterval(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 missedUntimed = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 1, parsedReaction: untimedParsed, + localNodeName: "Local", timestampWindow: window, limit: 200 + ) + let foundDatagram = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 2, parsedReaction: untimedParsed, + localNodeName: "Local", timestampWindow: window, limit: 200 + ) + let missedTimed = try await store.findChannelMessageForReaction( + radioID: device.id, channelIndex: 2, parsedReaction: timedParsed, + localNodeName: "Local", timestampWindow: window, limit: 200 + ) + #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() + let device = createTestDevice() + 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: 0, + text: text, + timestamp: 1_000_000, + createdAt: Date(timeIntervalSince1970: 1_000_000), + direction: .outgoing, + status: .sent, + senderNodeName: "Painter" + ) + try await store.saveMessage(image) + + 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 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.findChannelMessageForReaction( + radioID: device.id, channelIndex: 0, parsedReaction: renamed, + localNodeName: "Other", timestampWindow: window, limit: 200 + ) + #expect(found?.id == image.id) + #expect(missed == nil) + } + + @Test + func `Group text outside the window does not match`() async throws { + let store = try await createTestStore() + let device = createTestDevice() + try await store.saveDevice(device) + let text = MessageDTO.testChannelMessage( + radioID: device.id, + channelIndex: 0, + text: "Plain channel text", + timestamp: 100, + createdAt: Date(timeIntervalSince1970: 100), + direction: .incoming, + status: .delivered, + senderNodeName: "Ada" + ) + try await store.saveMessage(text) + + 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) + } + + @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 + message.timestampCorrected = true + message.deduplicationKey = try? DeduplicationKey.channelMCOImage( + channelIndex: channelIndex, + dataField: MCOImageTransport.dataField(text: text, senderName: sender) + ) + return message + } + @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..b1eeb2649a 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 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) + let image = MessageDTO.testChannelMessage( + radioID: connection.device.radioID, + text: "im4:pixel", + direction: .incoming, + status: .delivered, + senderNodeName: "" + ) + 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/ChatSendQueueServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/ChatSendQueueServiceTests.swift index 068ac9a3de..9cc5fe9764 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", 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( + 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/HeardRepeatsServiceTests.swift b/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift index 36801a403d..2f4566d457 100644 --- a/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift +++ b/MC1Services/Tests/MC1ServicesTests/Services/HeardRepeatsServiceTests.swift @@ -659,4 +659,276 @@ struct HeardRepeatsServiceTests { #expect(repeats.count == 1) #expect(repeats.first?.pathNodes == Data([0xBB])) } + + // MARK: - Datagram paths + + /// 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 { + 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, + // 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, + 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/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/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 6426f1b5fd..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) 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/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift new file mode 100644 index 0000000000..ed4db0eed2 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/SyncCoordinatorChannelMCOImageReactionTests.swift @@ -0,0 +1,203 @@ +import Foundation +@testable import MC1Services +import MeshCoreTestSupport +import Testing + +@Suite("Channel MCOimg reactions") +@MainActor +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 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) + 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/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() diff --git a/MC1Services/Tests/MC1ServicesTests/Utilities/MCOImageV4CodecTests.swift b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOImageV4CodecTests.swift new file mode 100644 index 0000000000..a21b5f3af8 --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOImageV4CodecTests.swift @@ -0,0 +1,176 @@ +import Foundation +@testable import MC1Services +import Testing + +struct MCOImageV4CodecTests { + @Test func `decodes empty vector document`() 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 `rejects reserved mode as unsupported`() { + #expect(throws: MCOImageCodecError.unsupported) { + try MCOImageV4Codec.decodeBody(Data([0, 2, 0])) + } + } + + @Test func `rejects truncated document as damaged`() { + #expect(throws: MCOImageCodecError.damaged) { + try MCOImageV4Codec.decodeBody(Data([0])) + } + } + + @Test func `bounds zero delta repeat expansion before allocating`() 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 `bounds nested group depth`() throws { + #expect(try MCOImageV4Codec.decodeBody(nestedGroups(depth: 64)).figures.count == 1) + #expect(throws: MCOImageCodecError.unsupported) { + try MCOImageV4Codec.decodeBody(nestedGroups(depth: 65)) + } + } + + @Test func `tagged dart command fixtures`() 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 = try dump(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..4f6c97161c --- /dev/null +++ b/MC1Services/Tests/MC1ServicesTests/Utilities/MCOTextCodecTests.swift @@ -0,0 +1,44 @@ +import Foundation +@testable import MC1Services +import Testing + +struct MCOTextCodecTests { + @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]]) + #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 `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 `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) + } + } + + 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..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,72 @@ 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]) + 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(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) + } + if let channel = viewModel.currentChannel { + #expect(try await store.fetchMessages(radioID: radioID, channelIndex: channel.index).isEmpty) + } } @Test(arguments: [false, true]) @@ -151,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 825871b3d1..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: {} + 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 311310ea49..9435af8527 100644 --- a/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift +++ b/MC1Tests/Views/Chats/Components/ChatNativeSplitLayoutTests.swift @@ -1032,7 +1032,8 @@ private struct ChatNativeSplitHarness: View { focusRequest: $model.inputFocusRequest, nodeNameByteCount: 0, onSend: { _ in true }, - onWillSend: { model.scrollToBottomRequest += 1 } + onWillSend: { model.scrollToBottomRequest += 1 }, + onNotAdmitted: {} ) .background { GateAIdentifierView(identifier: "gateA.composer") 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..2541fa0b4d 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 `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)) + 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..611826b057 --- /dev/null +++ b/MC1Tests/Views/Chats/MCOImageGeometryTests.swift @@ -0,0 +1,50 @@ +@testable import MC1 +import MC1Services +import SwiftUI +import Testing + +@Suite("MCOimg rendering geometry") +@MainActor +struct MCOImageGeometryTests { + private func point(_ x: Int, _ y: Int) -> MCOImageV4Point { + .init(x: x, y: y) + } + + @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 `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)) + 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 `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 } } + #expect(control == CGPoint(x: 4.5, y: 4.5)) + #expect(path.boundingRect.maxY == 2.5) + } + + @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 + 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..eb17e3e8ae --- /dev/null +++ b/MC1Tests/Views/Chats/MCOImageMessageTests.swift @@ -0,0 +1,39 @@ +import Foundation +@testable import MC1 +import MC1Services +import Testing + +@Suite("MCOimg message content") +struct MCOImageMessageTests { + @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()) + #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 `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 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..7513fef387 100644 --- a/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift +++ b/MC1Tests/Views/Chats/MessageActionAvailabilityTests.swift @@ -197,11 +197,45 @@ struct MessageActionAvailabilityTests { #expect(availability.canBlockSender == false) } + @Test + 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 MCOimg 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 +248,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..cdccfd1eff 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 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, .reactionSummary]) + } + + @Test + 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]) + } + /// 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.) @@ -447,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 @@ -621,6 +648,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 +661,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 +844,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..20ad31791e --- /dev/null +++ b/MC1Tests/Views/Chats/PixelPaintDraftTests.swift @@ -0,0 +1,389 @@ +@testable import MC1 +import MC1Services +import Testing + +@Suite("Pixel paint drafts") +@MainActor +struct PixelPaintDraftTests { + @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) + draft.endStroke() + 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, + transport: .direct, + senderName: { "Radio" }, + isReady: { self.ready }, + onSend: { text in + self.payloads.append(text) + if pauseOnSend { await pause.pause() } + return self.accept + }, + onWillSend: {}, + onAdmitted: { self.admitted += 1 }, + 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, transport: transport) + } + ) + } + 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 + } +} + +@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 new file mode 100644 index 0000000000..723e409b24 --- /dev/null +++ b/MC1Tests/Views/Chats/PixelPaintPresentationTests.swift @@ -0,0 +1,615 @@ +import Foundation +@testable import MC1 +@testable import MC1Services +import SwiftUI +import Testing +import UIKit + +private struct AccessibilityDump: Error, CustomStringConvertible { + var description: String + init(_ description: String) { + self.description = description + } +} + +@Suite("Pixel paint presentation", .serialized) +@MainActor +struct PixelPaintPresentationTests { + @Test func `full screen cover blocks dismissal and cancel asks before discarding 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() + 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") { 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 { + $0.delegate?.presentationControllerShouldDismiss?($0) == false + } == true + } + do { + 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 + } + } 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(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 on a drawing should ask before discarding") { + alertTitled(L10n.Chats.Chats.Mcoimg.discardTitle, from: window.rootViewController) + } + #expect(presentedController(in: window) != nil) + #expect(draft.image == pixels) + try #require(await activate(L10n.Chats.Chats.Mcoimg.discard, in: window)) + try await waitUntil("Discard 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") { presentedController(in: window) != nil } + #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) + try #require(await activate(L10n.Localizable.Common.cancel, in: window)) + try await waitUntil("Cancel on a blank canvas should dismiss directly") { presentedController(in: window) == nil } + } + + @Test func `cancel while encoding retires the drawing without asking`() 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) + draft.endStroke() + let model = SendModel() + model.pauseOnEncode = true + 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 } + try #require(await activate(L10n.Chats.Chats.Mcoimg.send, in: window)) + await model.pause.untilPaused() + #expect(draft.isSubmitting) + #expect(!draft.isAdmitting) + try #require(await activate(L10n.Localizable.Common.cancel, in: window)) + try await waitUntil("Cancel should dismiss the editor") { presentedController(in: window) == nil } + #expect(!alertTitled(L10n.Chats.Chats.Mcoimg.discardTitle, from: window.rootViewController)) + model.pause.resume() + await model.task?.value + #expect(model.payloads.isEmpty) + #expect(model.admittedCount == 0) + #expect(draft.image.pixels.allSatisfy { $0 == PixelPaintDraft.background }) + } + + @Test func `a transport change re-measures and re-enables send`() async throws { + let appState = try AppState(modelContainer: PersistenceStore.createContainer(inMemory: true), isPlaceholder: true) + appState.connectionManager.setTestState(connectionState: .ready) + let draft = PixelPaintDraft() + draft.pixels = try await drawingOverTextLimitButWithinDataLimit() + let model = TransportModel() + let window = try host(TransportHarness(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 } + try await waitUntil("A drawing over the text limit disables Send") { + draft.encodedByteCount != nil && isEnabled(L10n.Chats.Chats.Mcoimg.send, in: window) == false + } + #expect(draft.isOverBudget(for: .channelText)) + model.transport = .channelData + try await waitUntil("The channel data measurement re-enables Send") { + isEnabled(L10n.Chats.Chats.Mcoimg.send, in: window) == true + } + #expect(!draft.isOverBudget(for: .channelData)) + } + + @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) + 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 `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) + 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 `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) + 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, + transport: .direct, + senderName: { "" }, + isReady: { appState.connectionState == .ready }, + onSend: { _ in + model.payloads.append("admitted") + return true + }, + onWillSend: {}, + onAdmitted: {}, + encode: { image, transport in + await pause.pause() + return try await encodePixelDrawing(image, transport: transport) + } + ) + } + 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 `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) + 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.submissions == ["Hello"]) + #expect(model.text.isEmpty) + #expect(composer.onSend?() == false) + #expect(model.submissions == ["Hello"]) + } + + private struct Harness: View { + let draft: PixelPaintDraft + @Bindable var presentation: Presentation + var body: some View { + Color.clear + .fullScreenCover(isPresented: $presentation.isPresented) { + PixelPaintEditor(draft: draft, transport: .direct, senderName: "", 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, transport: .direct, senderName: "") { + guard let attempt = draft.begin(isReady: { model.ready }) else { return } + let pause = model.pause + let pauseOnEncode = model.pauseOnEncode + model.task = Task { + await draft.run( + attempt, + transport: .direct, + senderName: { "" }, + isReady: { model.ready }, + onSend: { text in + model.payloads.append(text) + await model.pause.pause() + return model.accept + }, + onWillSend: {}, + onAdmitted: { + model.admittedCount += 1 + model.isPresented = false + }, + encode: { image, transport in + if pauseOnEncode { await pause.pause() } + return try await encodePixelDrawing(image, transport: transport) + } + ) + } + if let task = model.task { draft.track(task) } + } + } + .onAppear { model.isReady = true } + } + } + + @Observable + @MainActor + final class Presentation { + var isPresented = false + var isReady = false + } + + @Observable + @MainActor + final class SendModel { + static let originalText = "Existing text stays" + var text = originalText + var isPresented = false + var isReady = false + var ready = true + var accept = true + var payloads: [String] = [] + var sendErrorMessage: String? + var pauseOnEncode = false + var admittedCount = 0 + var task: Task? + 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 { + 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: InputModel.maxBytes, + isEncrypted: true, + leading: { EmptyView() }, + onSend: { model.submissions.append($0) } + ) + } + } + + 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) + 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 { + 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) + } + 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 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 } + 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) + let count = object.accessibilityElementCount() + if count != NSNotFound, count > 0 { + for index in 0.. 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 } @@ -79,17 +121,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/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/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift b/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift index 693b3a55f4..9b2f148797 100644 --- a/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift +++ b/MeshCore/Sources/MeshCore/Protocols/MessagingSessionOps.swift @@ -44,6 +44,24 @@ public protocol MessagingSessionOps: Actor { timestamp: Date, floodScope: ResolvedFloodScope ) async throws + + /// Applies the channel's flood scope and sends binary GROUP_DATA in the same command-response slot. + func sendChannelData( + channelIndex: UInt8, + dataType: UInt16, + payload: Data, + floodScope: ResolvedFloodScope + ) async throws + + /// Sends binary GROUP_DATA without a flood-scope preface. + /// Radios older than the scope command use this when the resolved scope is disabled. + func sendChannelData( + channelIndex: UInt8, + dataType: UInt16, + payload: Data, + pathLength: UInt8, + pathBytes: Data + ) async throws } // MARK: - Default Implementations diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift index 0a7751522a..83a488ec5e 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift @@ -28,7 +28,21 @@ public extension MeshCoreSession { timestamp: Date, floodScope: ResolvedFloodScope ) async throws { - try await performChannelSend(channel: channel, text: text, timestamp: timestamp, floodScope: floodScope) + let message = PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp) + try await performChannelCommand(message, floodScope: floodScope) + } + + /// Applies a channel's flood scope and sends binary GROUP_DATA without interleaving another command. + func sendChannelData( + channelIndex: UInt8, + dataType: UInt16, + payload: Data, + floodScope: ResolvedFloodScope + ) async throws { + let message = try PacketBuilder.sendChannelData( + channelIndex: channelIndex, dataType: dataType, payload: payload + ) + try await performChannelCommand(message, floodScope: floodScope) } /// Reads the channel and sends while holding one command slot, so another command cannot land between them. @@ -87,9 +101,13 @@ public extension MeshCoreSession { timestamp: Date, floodScope: ResolvedFloodScope? ) async throws { + let message = PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp) + try await performChannelCommand(message, floodScope: floodScope) + } + + private func performChannelCommand(_ message: Data, floodScope: ResolvedFloodScope?) async throws { let cancelled = Mutex(false) let isCancelled: @Sendable () -> 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/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 + } } diff --git a/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift b/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift index b5ae74c631..6eec3816c2 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/ChannelSendSerializationTests.swift @@ -11,23 +11,21 @@ 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( - channel: Self.firstChannel, text: "first", timestamp: Self.timestamp, - floodScope: .scope(Self.firstScope) - ) + try await send(session: session, binary: binary, + 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 session.sendChannelMessage( - channel: Self.secondChannel, text: "second", timestamp: Self.timestamp, - floodScope: .scope(Self.secondScope) - ) + try await send(session: session, binary: binary, + 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] == PacketBuilder.sendChannelMessage( - 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,11 +53,11 @@ 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( - 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())) - #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() } @@ -173,6 +170,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/docs/Reactions.md b/docs/Reactions.md index 171e10548c..a55dbf9550 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 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? @@ -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. 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" diff --git a/scripts/mcoimg/README.md b/scripts/mcoimg/README.md new file mode 100644 index 0000000000..8f592be6aa --- /dev/null +++ b/scripts/mcoimg/README.md @@ -0,0 +1,91 @@ +# 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 +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 +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. + +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 \ + tmp/mcoimg-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/tmp/mcoimg-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 +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/tmp/mcoimg-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. 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-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/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") + } +}