// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL import QtQuick import QtQuick.Layouts import QtQuick.Controls as QQC2 import org.kde.kirigami as Kirigami import org.kde.kirigamiaddons.components as Components import koutnet.app // Flat: no bubble. A bubble frames a message to say where it starts and who sent // it, and the run header above and the gutter beside already say both; the frame // only costs width. Consecutive messages from one sender share a header, and the // model works out where a run begins because that is a statement about the row // before this one and a delegate cannot see its neighbour. Own messages get a // stripe down the leading edge rather than alignment or a fill: alternating sides // halves the usable width and moves every run start, and a fill puts the loudest // colour on the half of the conversation you wrote. Item { id: root // Required, so a renamed role is a hard error at load and not a blank row. required property int index required property string sender required property string senderAvatar // the id behind the name when the backend has one: the account a tap on the // avatar opens a card for. Names can be shared, so the card is asked by id. required property string senderId required property string text required property string formattedText required property bool isOwn required property bool isSystem required property bool isEdited required property string replyToText required property string replyToSender required property string replyToId required property string msgId required property bool isRead required property bool isPending required property var reactions required property string timeString required property double stampSecs required property bool isFile required property string filePath required property bool isImage required property string mediaKind required property string mediaUrl required property string mediaThumbnailUrl required property int mediaWidth required property int mediaHeight required property int mediaDuration required property bool showAuthor required property bool showDay // the poll this row carries, from the model role of the same name (empty for // non-poll rows). Declared like every other role so root.poll resolves; // without it the voting UI never shows. required property var poll // the room this row belongs to, fed from MessageTimeline so a poll vote can // name its room on the wire. poll comes from the model role; do NOT declare // it here or the local property shadows the role. property string chatId: "" // The page's one video player: which recording it holds, what it is doing, // and where it stands. The holding row draws the controls; others draw posters. property string videoClaimMsgId: "" property bool videoPlaying: false property int videoPositionMs: 0 property int videoDurationMs: 0 property real contentWidth: root.width property real zoom: 1.0 property string selfName: "" property string peerName: "" property string selfDisplayName: "" property string selfAvatarSource: "" // The peer chat's avatar, filled in by the timeline: a LAN row has no // per-message senderAvatar, so without it every bubble shows the initials. property string peerAvatarSource: "" // False in a Matrix room: an edit that never reaches the homeserver is a // private disagreement with what everybody else can still read. property bool canEditMessages: true // Per-message: revealing one spoiler should not reveal the whole backlog. property bool spoilerRevealed: false property bool flashing: false // What the window's single music player holds, from Main.qml, so an audio // row can say whether its track is playing. Idle elsewhere; a video keeps // its own inline player and never reads these. property string activeChatId: "" property string activeSource: "" property bool musicPlaying: false property int musicPositionMs: 0 property int musicDurationMs: 0 // the quote travels with the request rather than being looked up again by row: // the page would have to reach into the model to find what this is holding. signal replyRequested(int row, string author, string excerpt, string msgId) signal pinRequested(int row, string msgId) signal editRequested(int row, string body) signal reactRequested(int row) signal menuRequested(int row, string author, string body, string msgId) signal reactionToggled(int row, string emoji) signal jumpRequested(string msgId) // A URL rather than a path: the attachment may never have been on this disk. signal imageActivated(string source) signal fileActivated(string source) // The transport's hand-off: the player page takes the local copy. signal videoActivated(string source) // What a row's media is doing, for the page's floats: where the window's // track stands, where the video tile is. Both carry the message id, the one // address the timeline can jump back by. signal musicRowState(string msgId, bool onScreen) signal videoRowState(string msgId, bool onScreen) // The claim on the page's one player: the recording and the surface it is // drawn on - the anchor item again, owned by the delegate. signal videoClaimRequested(string msgId, string source, string name, Item surface) signal videoToggleRequested(string msgId) signal videoSeekRequested(int positionMs) // an audio row asked for its track: the window's player takes it. signal musicRequested(string chatId, string source, string title) signal musicSeekRequested(int positionMs) signal avatarClicked(bool own, string userId, Item anchorItem) signal mentionRequested(string name, string userId) signal copyLinkRequested(string url) signal openChatRequested(string userId) // The face and the name in a run open the same small panel NeoChat shows: // identity at the top, profile and mention beneath it. function copyLink(userId) { root.copyLinkRequested("matrix.to/#/" + (userId || root.senderId)) } // The old card for everyone: the account card on own messages, the peer // card (or member card in a room) on anyone else's - as before all this. function openUserMenu(anchorItem) { root.avatarClicked(root.isOwn, root.senderId, anchorItem || root) } // Whether this row is inside the viewport, read through the view's own // coordinates. contentY is read on purpose: mapToItem is not a tracked // dependency. A row scrolled past hands its controls to the page's float. readonly property bool rowOnScreen: { const view = ListView.view if (!view) return true const offset = view.contentY const pos = mapToItem(view, 0, 0) return pos.y + height > 0 && pos.y < view.height } // Your own name and not the word "You", because a reply quotes it and the // context menu is titled with it; "You" under another message reads as nobody. readonly property string authorName: root.isOwn ? (root.selfDisplayName.length > 0 ? root.selfDisplayName : i18nc("@info:placeholder the local user, as the author of their own message", "You")) : (root.sender.length > 0 ? root.sender : root.peerName) // Marked, so a glance down the column still tells your own messages from the // peer's: the gutter stripe was carrying that alone, and it is two pixels wide. readonly property string headerName: root.isOwn ? i18nc("@info run header over your own messages, %1 is your own display name", "%1 (you)", root.authorName) : root.authorName // Colours are handed over rather than read inside TextHandler, because this // item is the one that knows which theme chain it is drawing under. readonly property var bodyOptions: ({ "mentionName": root.selfDisplayName, "mentionColor": ThemePalette.accent.toString(), "codeBackground": ThemePalette.surfaceAlt.toString(), "spoilerBackground": Kirigami.ColorUtils .linearInterpolation(ThemePalette.surface, ThemePalette.text, 0.5).toString(), "spoilerRevealed": root.spoilerRevealed, "elideLinksAt": 48 }) readonly property string renderedBody: root.formattedText.length > 0 ? TextHandler.renderFormatted(root.formattedText, root.bodyOptions) : TextHandler.toRichText(root.text, root.bodyOptions) readonly property bool hasSpoiler: root.text.indexOf("||") >= 0 || root.formattedText.indexOf("data-mx-spoiler") >= 0 readonly property bool hasReply: root.replyToText.length > 0 readonly property bool isPicture: root.isFile && root.isImage readonly property bool emojiOnly: !root.isFile && !root.isSystem && root.looksLikeEmojiRun(root.text) // Ctrl+wheel zooms the whole conversation, so a row's measurements scale by // the same factor as its text. Scaling only the font left avatars, bubbles // and images at their usual size around larger words. readonly property real uiScale: root.zoom readonly property real gutterWidth: Math.round(Kirigami.Units.iconSizes.medium * root.uiScale) // Which end of the row this run starts from. Zero and two keep the usual // left edge for other people; one puts everything on the right, two splits // by author. The face follows the block so there is no empty half-row. readonly property bool messageOnRight: appSettings.messageBubbles && (appSettings.messageAlignment === 1 || (appSettings.messageAlignment === 2 && root.isOwn)) // Six is the cut-off: past that it is a sentence written in pictures. function looksLikeEmojiRun(str) { if (!str || str.trim().length === 0 || str.length > 16) return false if (str.indexOf(" ") >= 0 || str.indexOf("\n") >= 0) return false let count = 0 for (const ch of str) { count++ if (!root.isEmojiCodePoint(ch.codePointAt(0))) return false } return count > 0 && count <= 6 } function isEmojiCodePoint(cp) { return (cp >= 0x1F300 && cp <= 0x1FAFF) || (cp >= 0x2600 && cp <= 0x27BF) || (cp >= 0x1F1E0 && cp <= 0x1F1FF) || cp === 0x2764 || cp === 0x2665 || cp === 0x2B50 || cp === 0x2B55 || cp === 0x00A9 || cp === 0x00AE || cp === 0x2122 || cp === 0x3030 || cp === 0x303D || (cp >= 0x200B && cp <= 0x200F) || (cp >= 0xFE00 && cp <= 0xFE0F) } // ListView sizes a delegate's height from it and leaves the width alone, so // the width has to be taken from the view by hand. width: root.ListView.view ? root.ListView.view.width : root.contentWidth implicitHeight: layout.implicitHeight height: implicitHeight // the view reassigns every required property on reuse, so anything bound to a // role puts itself right. These two were set by hand and would keep the last // row's spoiler and hover strip. ListView.onReused: { root.spoilerRevealed = false hoverActions.stripHovered = false } ColumnLayout { id: layout // Leading edge rather than centred: centring split the scrollBarRoom // reservation between both sides. anchors.left: parent.left anchors.leftMargin: Math.round(Kirigami.Units.largeSpacing * root.uiScale) anchors.top: parent.top width: root.contentWidth spacing: 0 DateSeparator { Layout.fillWidth: true Layout.topMargin: Math.round(Kirigami.Units.largeSpacing * root.uiScale) Layout.bottomMargin: Math.round(Kirigami.Units.largeSpacing * root.uiScale) visible: root.showDay Layout.preferredHeight: visible ? -1 : 0 whenSecs: root.stampSecs } SystemMessage { Layout.fillWidth: true visible: root.isSystem Layout.preferredHeight: visible ? -1 : 0 text: root.text } Item { id: body Layout.fillWidth: true visible: !root.isSystem implicitHeight: bodyRow.implicitHeight Layout.preferredHeight: visible ? -1 : 0 Layout.topMargin: root.showAuthor && !root.showDay ? Math.round(Kirigami.Units.largeSpacing * root.uiScale) : 0 HoverHandler { id: bodyHover } Rectangle { anchors.fill: parent anchors.leftMargin: -Math.round(Kirigami.Units.smallSpacing * root.uiScale) anchors.rightMargin: -Math.round(Kirigami.Units.smallSpacing * root.uiScale) radius: Kirigami.Units.cornerRadius visible: root.flashing && !appSettings.messageBubbles color: Kirigami.ColorUtils.tintWithAlpha(ThemePalette.surface, ThemePalette.accent, 0.25) } RowLayout { id: bodyRow anchors.left: parent.left anchors.right: parent.right anchors.top: parent.top spacing: Math.round(Kirigami.Units.smallSpacing * root.uiScale) // the gutter holds nothing at all on rows that continue a run, but // is reserved either way so every line of a run starts at the same x. Item { Layout.alignment: Qt.AlignTop Layout.preferredWidth: root.gutterWidth Layout.preferredHeight: root.gutterWidth visible: !root.messageOnRight Rectangle { anchors.left: parent.left anchors.top: parent.top anchors.bottom: parent.bottom width: Math.max(2, Math.round(Kirigami.Units.smallSpacing * root.uiScale / 2)) radius: width / 2 visible: root.isOwn color: ThemePalette.accent } Components.Avatar { id: authorAvatar anchors.right: parent.right anchors.top: parent.top width: root.gutterWidth - Math.round(Kirigami.Units.smallSpacing * root.uiScale) height: width visible: root.showAuthor // the plain name and not the header's: the generated colour // and fallback initial must not come off the "(you)". name: root.authorName // Peers published a name and a bio but no picture, so theirs used // to stay an initial; now an avatar frame lands on the TLS channel // and spells a real face. senderAvatar is the per-row role, and // avatarSource is the fallback behind it. source: root.isOwn ? (root.senderAvatar.length > 0 ? root.senderAvatar : root.selfAvatarSource) : (root.senderAvatar.length > 0 ? root.senderAvatar : root.peerAvatarSource) asynchronous: true // the card is hung off this item, so it has to be the one // that reports the tap. TapHandler { acceptedButtons: Qt.LeftButton gesturePolicy: TapHandler.ReleaseWithinBounds onTapped: root.openUserMenu(authorAvatar) } HoverHandler { cursorShape: Qt.PointingHandCursor } } // on hover only: a column of times down the gutter is noise, and // the wanted one is beside the message being looked at. QQC2.Label { anchors.right: parent.right anchors.top: parent.top visible: !root.showAuthor && bodyHover.hovered text: root.timeString textFormat: Text.PlainText font: Kirigami.Theme.smallFont color: AppPalette.disabledText } } Item { Layout.fillWidth: true Layout.alignment: Qt.AlignTop implicitHeight: messageBlock.implicitHeight Layout.bottomMargin: appSettings.messageBubbles ? Math.round(Kirigami.Units.smallSpacing * root.uiScale) : 0 // The block is sized by its own content, up to the width the // column can spare, instead of being stretched over the row. // Every run still starts at the gutter, so the timeline keeps // its left edge instead of leaving half of it empty. MessageBubble { id: messageBlock // The block is sized by its text, up to the width the // row can spare. Only the side changes with the mode: // "mine right" puts your runs at the trailing edge. // With blocks off the row is the old flat one: full // width from the gutter, no card, no trailing edge. width: appSettings.messageBubbles ? Math.min(implicitWidth, root.contentWidth - root.gutterWidth - Math.round(Kirigami.Units.largeSpacing * 2 * root.uiScale)) : root.contentWidth - root.gutterWidth x: root.messageOnRight ? root.contentWidth - root.gutterWidth - width : 0 isOwn: root.isOwn showHighlight: root.flashing bubbleRadius: Math.round(appSettings.bubbleRadius * root.uiScale) contentScale: root.uiScale RowLayout { Layout.fillWidth: true visible: root.showAuthor Layout.preferredHeight: visible ? -1 : 0 spacing: Math.round(Kirigami.Units.smallSpacing * root.uiScale) QQC2.Label { text: root.headerName textFormat: Text.PlainText TapHandler { acceptedButtons: Qt.LeftButton onTapped: root.openUserMenu(authorAvatar) } elide: Text.ElideRight font.bold: true // the accent, not a per-sender colour: generated colours // answer a question only group chats have. color: ThemePalette.accent // Off contentWidth, not the row: reading back a width the // layout is still working out puts the header in a loop. Layout.maximumWidth: Math.round(root.contentWidth * 0.5) } QQC2.Label { text: root.timeString textFormat: Text.PlainText font: Kirigami.Theme.smallFont color: AppPalette.disabledText HoverHandler { id: timeHover } QQC2.ToolTip.visible: timeHover.hovered QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay QQC2.ToolTip.text: i18nc("@info:tooltip when a message was sent, %1 is a date and time", "Sent %1", new Date(root.stampSecs * 1000).toLocaleString(Qt.locale())) } Item { Layout.fillWidth: true } } // Quote, attachment and reactions are loaded rather than declared: // most messages have none, and building all three per row cost a scroll. Loader { Layout.fillWidth: true active: root.hasReply visible: active sourceComponent: ReplyQuote { author: root.replyToSender excerpt: root.replyToText targetId: root.replyToId onJumpRequested: (msgId) => root.jumpRequested(msgId) } } Loader { Layout.fillWidth: true active: root.isFile visible: active sourceComponent: AttachmentBlock { chatId: root.chatId eventId: root.msgId filePath: root.filePath mediaUrl: root.mediaUrl thumbnailUrl: root.mediaThumbnailUrl mediaKind: root.mediaKind mediaWidth: root.mediaWidth mediaHeight: root.mediaHeight mediaDurationMs: root.mediaDuration fileName: root.text isImage: root.isImage // the window's player, seen from the row: what it // holds, whether it runs, and where it stands. activeChatId: root.activeChatId activeSource: root.activeSource musicPlaying: root.musicPlaying musicPositionMs: root.musicPositionMs musicDurationMs: root.musicDurationMs // the ceiling scales with the zoom too: an unscaled cap // would not grow past the text around it. maxImageWidth: Math.min(Kirigami.Units.gridUnit * 18 * root.uiScale, root.contentWidth - root.gutterWidth - Math.round(Kirigami.Units.largeSpacing * 2 * root.uiScale)) // the decode cap is fixed, not the live ceiling: // binding it to the width re-decodes on every resize tick. // The smaller setting trades detail for a smaller // decoded image in every attachment row. decodeCapWidth: Math.round(Kirigami.Units.gridUnit * (appSettings.smallerAttachments ? 12 : 18) * root.uiScale) // a recording may take a little more room than a // photograph: the picture is the whole message. videoMaxWidth: Math.min(Kirigami.Units.gridUnit * 22 * root.uiScale, root.contentWidth - root.gutterWidth - Math.round(Kirigami.Units.largeSpacing * 2 * root.uiScale)) // where this row stands in the viewport, and the // page's one video player, said through the row. rowOnScreen: root.rowOnScreen videoClaimMsgId: root.videoClaimMsgId videoPlaying: root.videoPlaying videoPositionMs: root.videoPositionMs videoDurationMs: root.videoDurationMs onImageActivated: (source) => root.imageActivated(source) onFileActivated: (source) => root.fileActivated(source) onVideoActivated: (source) => root.videoActivated(source) onMusicRowState: (msgId, onScreen) => root.musicRowState(msgId, onScreen) onVideoRowState: (msgId, onScreen) => root.videoRowState(msgId, onScreen) onVideoClaimRequested: (msgId, source, name, surface) => root.videoClaimRequested(msgId, source, name, surface) onVideoToggleRequested: (msgId) => root.videoToggleRequested(msgId) onVideoSeekRequested: (positionMs) => root.videoSeekRequested(positionMs) onMusicActivated: (chatId, source, title) => root.musicRequested(chatId, source, title) onMusicSeek: (positionMs) => root.musicSeekRequested(positionMs) } } // A poll, drawn by PollBlock after NeoChat's own component. Loader { Layout.fillWidth: true active: root.poll ? ((root.poll.answers ? root.poll.answers.length : 0) > 0) : false visible: active sourceComponent: PollBlock { chatId: root.chatId eventId: root.msgId poll: root.poll } } // Plain Label rather than SelectableLabel: that one takes the // right button, and here it belongs to the message menu. QQC2.Label { id: bodyLabel Layout.fillWidth: true visible: !root.isFile && !(root.poll ? (root.poll.answers && root.poll.answers.length > 0) : false) Layout.preferredHeight: visible ? -1 : 0 text: root.emojiOnly ? root.text : root.renderedBody textFormat: root.emojiOnly ? Text.PlainText : Text.RichText wrapMode: Text.Wrap // pointSize and not pixelSize: a desktop font is configured in // points and reports pixelSize -1, which the zoom would multiply. font.pointSize: (root.emojiOnly ? 2.5 : 1.0) * Kirigami.Theme.defaultFont.pointSize * root.zoom // Opened outside rather than followed in place: nothing in here // renders a page, and a messenger that navigates is a browser. onLinkActivated: (link) => Qt.openUrlExternally(link) HoverHandler { cursorShape: bodyLabel.hoveredLink.length > 0 ? Qt.PointingHandCursor : Qt.ArrowCursor } // only bound when the message has a spoiler, so an ordinary // message is not swallowing left clicks. TapHandler { enabled: !root.spoilerRevealed && root.hasSpoiler acceptedButtons: Qt.LeftButton onTapped: root.spoilerRevealed = true } } Loader { Layout.fillWidth: true active: root.reactions.length > 0 visible: active sourceComponent: ReactionFlow { reactions: root.reactions selfName: root.selfName onToggled: (emoji) => root.reactionToggled(root.index, emoji) onAddRequested: root.reactRequested(root.index) } } } Components.Avatar { x: root.contentWidth - width anchors.top: parent.top width: root.gutterWidth - Math.round(Kirigami.Units.smallSpacing * root.uiScale) height: width visible: root.messageOnRight && root.showAuthor name: root.authorName source: root.isOwn ? (root.senderAvatar.length > 0 ? root.senderAvatar : root.selfAvatarSource) : (root.senderAvatar.length > 0 ? root.senderAvatar : root.peerAvatarSource) asynchronous: true TapHandler { acceptedButtons: Qt.LeftButton gesturePolicy: TapHandler.ReleaseWithinBounds onTapped: root.openUserMenu(parent) } } } // at the trailing edge rather than under the message: a line of its // own would double the height of a run of one-word replies. RowLayout { Layout.alignment: Qt.AlignTop spacing: Math.round(Kirigami.Units.smallSpacing * root.uiScale / 2) QQC2.Label { visible: root.isEdited text: i18nc("@info:status the message was changed after it was sent", "edited") textFormat: Text.PlainText font.pointSize: Kirigami.Theme.smallFont.pointSize font.italic: true color: AppPalette.disabledText } } } // Loaded on hover and thrown away after: four buttons, four tooltips and // a shadowed rectangle, once built for every message in the view. The // strip hangs half above the message, so bodyHover alone would lose it. Loader { id: hoverActions property bool stripHovered: false // Beside the message, on whichever side has room: a right-hand // run gets the strip at its left edge, so it never covers the // text or hides behind the avatar. x: root.messageOnRight ? Math.max(0, root.contentWidth - root.gutterWidth - messageBlock.width - hoverActions.width) : Math.min(Math.max(0, parent.width - hoverActions.width), messageBlock.width + root.gutterWidth) anchors.verticalCenter: parent.top z: 1 active: bodyHover.hovered || hoverActions.stripHovered sourceComponent: MessageActions { hoverEnabled: true canEdit: root.canEditMessages && root.isOwn && !root.isFile onHoveredChanged: hoverActions.stripHovered = hovered // or a strip unloaded while the pointer was still on it // would leave the flag up and the next one stuck open. Component.onDestruction: hoverActions.stripHovered = false onReactRequested: root.reactRequested(root.index) onReplyRequested: root.replyRequested(root.index, root.authorName, root.text, root.msgId) onPinRequested: root.pinRequested(root.index, root.msgId) onEditRequested: root.editRequested(root.index, root.text) onMenuRequested: root.menuRequested(root.index, root.authorName, root.text, root.msgId) } } TapHandler { acceptedButtons: Qt.RightButton onTapped: root.menuRequested(root.index, root.authorName, root.text, root.msgId) } TapHandler { acceptedButtons: Qt.LeftButton onLongPressed: root.menuRequested(root.index, root.authorName, root.text, root.msgId) } } } }