// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL import QtQuick import QtQuick.Controls as QQC2 import org.kde.kirigami as Kirigami import org.kde.kirigamiaddons.components as Components import koutnet.app // Bottom to top over a ReversedChatModel: QQuickListView extrapolates from Item { id: root property var messagesModel: null property real zoom: 1.0 property string selfName: "" property string peerName: "" property string selfDisplayName: "" property string selfAvatarSource: "" // fallback for rows whose senderAvatar role is empty, which is every LAN // peer row: the peer's picture arrives as a network frame, not per message. property string peerAvatarSource: "" property bool canEditMessages: true // the chat the timeline shows, threaded to each row so a poll vote can name // its room. Empty for the saved-messages chat, which has no polls. property string chatId: "" // What the window's single music player holds, threaded down to the rows: // an audio row draws honestly only if it knows whether its track is playing. property string musicActiveChatId: "" property string musicActiveSource: "" property bool musicPlaying: false property int musicPositionMs: 0 property int musicDurationMs: 0 // The page's one video player, said through the rows: which recording it // holds and what it is doing with it. property string videoClaimMsgId: "" property bool videoPlaying: false property int videoPositionMs: 0 property int videoDurationMs: 0 // Rows crossing this boundary go through toSourceRow()/fromSourceRow(); every // signal carries a ChatModel row, so nothing above knows the list is upside down. ReversedChatModel { id: reversed sourceModel: root.messagesModel } // originY + contentHeight = position of row 0, a real built item, so the two // estimate errors cancel. atYEnd uses float comparison and never settles. readonly property real tailDistance: messagesList.originY + messagesList.contentHeight + messagesList.bottomMargin - messagesList.height - messagesList.contentY // the window reads this to decide whether an arriving message counts as read: // a receipt for a message scrolled past above the fold is a lie. readonly property bool atBottom: Math.round(root.tailDistance) <= 1 // Sampled before the insert: after count changes, atBottom reads false and // a test there would drop out of a conversation the reader never left. property bool followTail: true onMessagesModelChanged: root.followTail = true onAtBottomChanged: if (root.atBottom) root.readReached() Connections { target: root.messagesModel function onRowsAboutToBeInserted() { root.followTail = root.atBottom } } readonly property int unreadCount: root.messagesModel ? root.messagesModel.unreadCount : 0 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) // 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. signal musicRowState(string msgId, bool onScreen) signal videoRowState(string msgId, bool onScreen) // The claim on the page's one player, and the row-side controls. 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, or for a seek: both go to the window's // one player, which no row can see. signal musicActivated(string chatId, string source, string title) signal musicSeek(int positionMs) signal readReached() // Files dropped onto the conversation, as local paths. The window owns // sending, so the timeline only says what was dropped. signal filesDropped(var localPaths) // the anchor item belongs to a delegate, so nothing may hold on to it. signal avatarActivated(bool own, string userId, Item anchorItem) signal mentionRequested(string name, string userId) signal copyLinkRequested(string url) signal openChatRequested(string userId) // User scrolled to the oldest loaded messages; request more history if available. signal olderHistoryRequested() // Horizontal collision between delivery marks and the scrollbar. // Unconditional to avoid a binding loop on contentHeight. readonly property real scrollBarRoom: Math.max(Kirigami.Units.smallSpacing, verticalScrollBar.implicitWidth) // Column-width minus scrollbar track. readonly property real messageWidth: messagesList.width - Kirigami.Units.largeSpacing * 2 - root.scrollBarRoom // Row 0 is the newest, so the way back to it is the beginning of the view. function scrollToEnd() { messagesList.positionViewAtBeginning() } function jumpToRow(row) { if (row < 0 || !root.messagesModel) return const idx = root.messagesModel.index(row, 0) root.jumpTo(row, root.messagesModel.data(idx, ChatModel.MsgIdRole) || "") } function jumpTo(sourceRow, msgId) { const target = reversed.fromSourceRow(sourceRow) if (target < 0) return // by index and not by contentY: an index is the one way of asking for a // position that does not go through the estimate. messagesList.positionViewAtIndex(target, ListView.Center) flashTarget.msgId = msgId flashTimer.restart() } function jumpToMessage(msgId) { if (!root.messagesModel) return const row = root.messagesModel.rowForMsgId(msgId) if (row < 0) return root.jumpTo(row, msgId) } function jumpToFirstUnread() { if (!root.messagesModel) return root.jumpToRow(root.messagesModel.firstUnreadRow()) } // Held here because a recycled delegate forgets. By id, not row: row // numbers shift on every insert in a reversed list. QtObject { id: flashTarget property string msgId: "" } Timer { id: flashTimer interval: Kirigami.Units.humanMoment onTriggered: flashTarget.msgId = "" } ListView { id: messagesList anchors.fill: parent clip: true model: reversed verticalLayoutDirection: ListView.BottomToTop spacing: 0 topMargin: Kirigami.Units.smallSpacing bottomMargin: Kirigami.Units.smallSpacing // Fix for the stall: destroyed delegates re-enter short and shift the row // height estimate. Recycled delegates keep their heights. reuseItems: true QQC2.ScrollBar.vertical: QQC2.ScrollBar { id: verticalScrollBar // The desktop style's column sets aside twenty-one pixels for a implicitWidth: Math.round(Kirigami.Units.gridUnit * 10 / 18) contentItem: Rectangle { implicitWidth: parent.width implicitHeight: parent.height radius: width / 2 color: verticalScrollBar.pressed ? Kirigami.ColorUtils.linearInterpolation(ThemePalette.surface, ThemePalette.text, 0.5) : Kirigami.ColorUtils.linearInterpolation(ThemePalette.surface, ThemePalette.text, 0.35) opacity: verticalScrollBar.active ? 0.85 : 0.55 Behavior on opacity { NumberAnimation { duration: Kirigami.Units.longDuration easing.type: Easing.OutCubic } } } background: null } boundsBehavior: Flickable.StopAtBounds // Delegates are expensive - rich text, reactions, an attachment - so a cacheBuffer: Math.max(0, Math.round(messagesList.height)) // the wheel goes to Kirigami's handler, which clamps against originY and // both margins and whose blockTargetWheel keeps the flick path out. Kirigami.WheelHandler { target: messagesList // Accepting the event stops the handler scrolling on the same notch. // Only Ctrl is read, so a plain scroll notch is left alone. onWheel: (wheel) => { if (!(wheel.modifiers & Qt.ControlModifier)) return root.zoom = Math.max(0.7, Math.min(2.0, root.zoom + (wheel.angleDelta.y > 0 ? 0.05 : -0.05))) wheel.accepted = true } } // Following the conversation only while the reader is already at the end, // deferred by a frame so the inserted row is measured before the view sits on it. onCountChanged: if (root.followTail) Qt.callLater(messagesList.positionViewAtBeginning) // nothing on completion. A bottom-to-top view already opens on row 0, and onAtYBeginningChanged: { if (atYBeginning && count > 0 && contentHeight > height) root.olderHistoryRequested() } delegate: MessageDelegate { id: messageRow contentWidth: root.messageWidth zoom: root.zoom selfName: root.selfName peerName: root.peerName selfDisplayName: root.selfDisplayName selfAvatarSource: root.selfAvatarSource peerAvatarSource: root.peerAvatarSource canEditMessages: root.canEditMessages chatId: root.chatId activeChatId: root.musicActiveChatId activeSource: root.musicActiveSource musicPlaying: root.musicPlaying musicPositionMs: root.musicPositionMs musicDurationMs: root.musicDurationMs videoClaimMsgId: root.videoClaimMsgId videoPlaying: root.videoPlaying videoPositionMs: root.videoPositionMs videoDurationMs: root.videoDurationMs flashing: flashTarget.msgId.length > 0 && flashTarget.msgId === messageRow.msgId onReplyRequested: (row, author, excerpt, msgId) => root.replyRequested(reversed.toSourceRow(row), author, excerpt, msgId) onPinRequested: (row, msgId) => root.pinRequested(reversed.toSourceRow(row), msgId) onEditRequested: (row, body) => root.editRequested(reversed.toSourceRow(row), body) onReactRequested: (row) => root.reactRequested(reversed.toSourceRow(row)) onMenuRequested: (row, author, body, msgId) => root.menuRequested(reversed.toSourceRow(row), author, body, msgId) onReactionToggled: (row, emoji) => root.reactionToggled(reversed.toSourceRow(row), emoji) onJumpRequested: (msgId) => root.jumpToMessage(msgId) 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) onMusicRequested: (chatId, source, title) => root.musicActivated(chatId, source, title) onMusicSeekRequested: (positionMs) => root.musicSeek(positionMs) onAvatarClicked: (own, userId, anchorItem) => root.avatarActivated(own, userId, anchorItem) onMentionRequested: (name, userId) => root.mentionRequested(name, userId) onCopyLinkRequested: (url) => root.copyLinkRequested(url) onOpenChatRequested: (uid) => root.openChatRequested(uid) } } // Dropped files go where a chosen file would have gone. A drop carrying // anything else is left alone: the window decides what it can send. DropArea { id: fileDrop anchors.fill: parent onDropped: function(drop) { if (!drop.hasUrls) return const paths = [] for (let i = 0; i < drop.urls.length; ++i) { // Depending on the platform Qt exposes each URL as either a QUrl // wrapper or a plain string. Do not read QUrl properties before // normalising it: with a string that silently rejects the drop. const text = String(drop.urls[i]) if (text.indexOf("file://") === 0 || text.indexOf("file:") === 0) // through FsUtils, which percent-decodes: a hand-made string // strip leaves %20 in every name with a space, and a path with // %20 in it is a file nothing can open. paths.push(FsUtils.toLocalPath(text)) } if (paths.length === 0) return drop.acceptProposedAction() root.filesDropped(paths) } } QQC2.Pane { visible: fileDrop.containsDrag anchors.fill: parent anchors.margins: Kirigami.Units.gridUnit Kirigami.PlaceholderMessage { anchors.centerIn: parent width: parent.width - Kirigami.Units.largeSpacing * 4 icon.name: "document-send" text: i18nc("@info:placeholder what dropping files onto the conversation does", "Drop files here to share them") } } Kirigami.PlaceholderMessage { anchors.centerIn: parent width: parent.width - Kirigami.Units.gridUnit * 4 visible: messagesList.count === 0 icon.name: "dialog-messages" text: i18nc("@info an open conversation with no messages in it", "Nothing here yet") explanation: i18nc("@info", "Write something below, or drop a file on this window to send it.") } // Top corner, because it sends the view upwards and the other button down. Components.FloatingButton { anchors.right: parent.right anchors.top: parent.top anchors.margins: Kirigami.Units.largeSpacing z: 2 visible: root.unreadCount > 0 && !root.atBottom icon.name: "mail-unread-symbolic" text: i18ncp("@action:button go to the oldest message not yet read, %1 is a number", "Jump to %1 unread message", "Jump to %1 unread messages", root.unreadCount) QQC2.ToolTip.visible: hovered QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay QQC2.ToolTip.text: text onClicked: root.jumpToFirstUnread() } // only up while there is somewhere to go back from. No room reserved: // reserving some is what wip19 did. Components.FloatingButton { id: jumpButton anchors.right: parent.right anchors.bottom: parent.bottom anchors.margins: Kirigami.Units.largeSpacing z: 2 visible: !root.atBottom icon.name: "go-bottom" text: i18nc("@action:button scroll the conversation back to the newest message", "Jump to the latest message") QQC2.ToolTip.visible: hovered QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay QQC2.ToolTip.text: text onClicked: { root.scrollToEnd() root.readReached() } } }