// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // up to three columns of a Kirigami.PageRow, folding to one on a narrow import QtMultimedia import QtQuick import QtQuick.Effects import QtQuick.Layouts import QtQuick.Window import QtQuick.Controls as QQC2 import org.kde.kirigami as Kirigami import koutnet.app Kirigami.ApplicationWindow { id: root title: i18nc("@title:window", "KOutNet") width: Kirigami.Units.gridUnit * 55 height: Kirigami.Units.gridUnit * 36 // Narrow enough that the page row folds to a single column. minimumWidth: Kirigami.Units.gridUnit * 20 minimumHeight: Kirigami.Units.gridUnit * 18 // Kirigami resolves its theme by walking up the parent chain, so the one // chain that matters starts here. Feed it the same colours the custom rows // read from AppPalette; otherwise plain QQC2 controls inside Kirigami pages // keep a system-palette look while everything around them is Breeze. Kirigami.Theme.inherit: false Kirigami.Theme.backgroundColor: AppPalette.background Kirigami.Theme.alternateBackgroundColor: AppPalette.alternateBackground Kirigami.Theme.textColor: AppPalette.text Kirigami.Theme.disabledTextColor: AppPalette.disabledText Kirigami.Theme.highlightColor: ThemePalette.accent Kirigami.Theme.highlightedTextColor: ThemePalette.accentText Kirigami.Theme.positiveTextColor: AppPalette.positiveText Kirigami.Theme.negativeTextColor: AppPalette.negativeText Kirigami.Theme.neutralTextColor: AppPalette.neutralText Kirigami.Theme.hoverColor: AppPalette.hover Kirigami.Theme.focusColor: AppPalette.focus // incoming transfers wait here for a consent decision, one dialog at a // time. Each entry is { host, meta }: host is the address the frame came // on, and it is carried because the handler binds the transfer to it. property var pendingFiles: [] // the first-run tour runs in a window of its own; the main window stays // hidden until the tour ends. property var wizardWindow: null // Shown by hand in onCompleted rather than bound, so the tray's show and // hide keep working: a binding here would dance with root.hide(). visible: false function openWizard() { if (wizardWindow) return wizardWindow = wizardComponent.createObject(root) wizardWindow.show() } // Closing is the same whichever way the tour ends, so it is written once. // It also hands the screen back to the main window, which opened hidden so // that the tour could go first. function closeWizard() { appSettings.showWelcome = false if (wizardWindow) { wizardWindow.destroy() wizardWindow = null } if (!root.visible) root.show() } // A mode the user picks and keeps, unlike the automatic fold the page row // does when the window is dragged narrow. Not the same layout - see // ChatListPage, ContactDelegate and AccountRow, which each hold half of it. readonly property bool compact: appSettings.compactMode // compact mode: one conversation, the list a back button away. PageRow's property real kChatListColumnWidth: 0 // the handle's range: the wide end fits a name, a preview and a timestamp; // the narrow end is one avatar plus the room to click it. readonly property real kMinChatListWidth: Kirigami.Units.smallSpacing * 2 + kChatListAvatarSize readonly property real kMaxChatListWidth: Kirigami.Units.gridUnit * 26 // shared with ChatListPage and every row: a minimum that differs between // them is a width nothing can be drawn in. readonly property int kChatListAvatarSize: 40 // the row's horizontal padding in the roomy layout, copied from readonly property real kRowHorizontalPadding: (Kirigami.Settings.tabletMode ? Kirigami.Units.largeSpacing : Kirigami.Units.mediumSpacing) + Math.round(Kirigami.Units.smallSpacing / 2) // below this the list becomes a strip of avatars. It sits above the // minimum on purpose: the layout collapses while the handle still moves. readonly property real kNarrowChatListWidth: kRowHorizontalPadding * 2 + kChatListAvatarSize + Kirigami.Units.smallSpacing // the opening width: a fifth of the window, kept between the two bounds. function defaultChatListColumnWidth() { return Math.min(Math.max(Kirigami.Units.gridUnit * 17, Math.round(root.width * 0.2)), Kirigami.Units.gridUnit * 26) } function chatListColumnWidth() { return Math.max(root.kMinChatListWidth, Math.min(root.kMaxChatListWidth, root.kChatListColumnWidth)) } function setChatListColumnWidth(width) { // called by the handle and always stored. A non-number is refused, not // clamped: NaN would pass through min/max and leave a column that can no // longer be moved. if (!Number.isFinite(width)) return const clamped = Math.round(Math.max(root.kMinChatListWidth, Math.min(root.kMaxChatListWidth, width))) root.kChatListColumnWidth = clamped appSettings.chatListWidth = clamped } // the room panel's own width, so dragging one column leaves the other alone. property real kInfoPanelColumnWidth: 0 // the panel handle's range: its page wants fifteen grid units at the // narrow end, and the wide end is the same roof as the chat list. readonly property real kMinInfoPanelWidth: Kirigami.Units.gridUnit * 15 readonly property real kMaxInfoPanelWidth: Kirigami.Units.gridUnit * 26 // the panel's opening width, worked out the same way as the chat list's. function defaultInfoPanelColumnWidth() { return Math.min(Math.max(Kirigami.Units.gridUnit * 17, Math.round(root.width * 0.2)), root.kMaxInfoPanelWidth) } function infoPanelColumnWidth() { return Math.max(root.kMinInfoPanelWidth, Math.min(root.kMaxInfoPanelWidth, root.kInfoPanelColumnWidth)) } function setInfoPanelColumnWidth(width) { // The same contract as setChatListColumnWidth above: the handle is the // only caller, the value is always stored, and a measurement that could // not be read is refused rather than clamped, for the same NaN reasons. if (!Number.isFinite(width)) return const clamped = Math.round(Math.max(root.kMinInfoPanelWidth, Math.min(root.kMaxInfoPanelWidth, width))) root.kInfoPanelColumnWidth = clamped appSettings.roomInfoWidth = clamped } readonly property real kRoomyColumnWidth: root.compact ? root.width : root.chatListColumnWidth() readonly property int kCompactWidth: Kirigami.Units.gridUnit * 22 readonly property int kCompactHeight: Kirigami.Units.gridUnit * 28 function toggleCompact() { if (!root.compact) { // Persisted rather than kept in memory: leaving compact mode after a // restart used to come back to whatever the default width was. appSettings.roomyWidth = root.width appSettings.roomyHeight = root.height appSettings.compactMode = true // Compact mode has no third column. root.closePeerInfo() root.applyCompactSize() return } appSettings.compactMode = false if (appSettings.roomyWidth > 0) root.width = appSettings.roomyWidth if (appSettings.roomyHeight > 0) root.height = appSettings.roomyHeight } function applyCompactSize() { root.width = root.kCompactWidth root.height = root.kCompactHeight } property string currentPeerIp: "" property string openedTelegramChatId: "" readonly property string kSelfChatId: "__self__" // chat id -> the peer's last known avatar as a local file. Kept apart from // peersModel (which forgets a peer the moment presence goes quiet) so an // offline peer still has the face it pushed over the TLS channel. property var peerAvatarMap: ({}) // The banner side of the same story: a peer's header picture as it arrived // over its TLS banner frame, keyed by chat id so an offline card still // shows the last one pushed. property var peerBannerMap: ({}) property bool micMuted: false // Deafen implies mute, but the engine is told about both separately, because // un-deafening has to put the microphone back the way the user left it. property bool deafened: false // the one door every chat action goes through: the backend is chosen by property var currentRoomInfo: null readonly property bool currentIsRoom: root.currentRoomInfo !== null function isLanGroup(chatId) { return chatId.length > 0 && chatTransport.transportName(chatId) === "lan" && GroupManager.isGroup(chatId) } function lanGroupName(chatId) { const g = GroupManager.get(chatId) return (g && g.name) ? g.name : chatId } function ensureLanGroupChat(chatId, name) { if (chatId.length === 0 || !GroupManager.isGroup(chatId)) return chatList.openChat(chatId, name && name.length > 0 ? name : lanGroupName(chatId)) chatList.setChatAsRoom(chatId, true) } function refreshRoomInfo() { if (root.isLanGroup(root.currentPeerIp)) { const g = GroupManager.get(root.currentPeerIp) const members = GroupManager.memberIps(root.currentPeerIp) const name = g && g.name ? g.name : root.currentPeerIp root.currentRoomInfo = { roomId: root.currentPeerIp, name: name, displayName: name, topic: "", memberCount: members.length, joinedCount: members.length, avatarUrl: "" } return } // hasRooms() is the question "does this chat have a room column at // all"; the room may still be unsynced, which the empty-but-kept map // below covers the same way it always did. if (!chatTransport.hasRooms(root.currentPeerIp)) { root.currentRoomInfo = null return } const info = chatTransport.roomInfo(root.currentPeerIp) // an empty map means the session has not synced this room yet. Kept as // a room all the same: the header must not fall back to peer furniture // for the second between opening the row and the state arriving. root.currentRoomInfo = info && info.roomId ? info : {} } function toggleMic() { root.micMuted = !root.micMuted voiceCallManager.setMute(root.micMuted) } function toggleDeafen() { root.deafened = !root.deafened voiceCallManager.setDeafen(root.deafened) } // A read receipt is a claim that somebody read something, so it is only sent // for a message that was actually on the screen. property bool chatAtBottom: true // One number for all three wallpaper blur effects: the lower cap needs // fewer texture levels and is the whole of the "lower blur detail" saving. readonly property int wallpaperBlurMax: appSettings.lowBlurDetail ? 32 : 64 // The cache trims its own oldest files when this changes. Binding { target: MediaCache property: "limitMb" value: appSettings.mediaCacheLimitMb } // the peer sends nothing at all when it stops, so the timer is what ends the // state: waiting for a "stopped typing" a lost datagram can swallow leaves the // dots up forever. property string typingChatId: "" Timer { id: typingTimeout interval: 6000 onTriggered: root.typingChatId = "" } property var chatModels: ({}) Component { id: chatModelComponent ChatModel {} } function modelForPeer(ip) { if (!chatModels[ip]) { const m = chatModelComponent.createObject(root) m.historyManager = HistoryManager m.reactionStore = ReactionStore m.unreadManager = UnreadManager m.chatId = ip // every message in any chat, in either direction, from one place; // wiring the four send and receive sites instead breaks at the fifth. m.messageAdded.connect(root.onChatActivity) m.reactionToggledLocally.connect((identifier, emoji, added) => { root.onLocalReaction(ip, identifier, emoji, added) }) chatModels[ip] = m } return chatModels[ip] } function onChatActivity(chatId, preview, isOwn, ts) { chatList.noteMessage(chatId, preview, isOwn, ts) } // the row, the unread count and the saved history, gone, without telling // any server: the local half of leaving. Both a real leave and the // context-menu "Delete this chat here" land here. function dropChatLocally(chatId) { root.modelForPeer(chatId).clearMessages() UnreadManager.markRead(chatId) chatList.removeChat(chatId) if (root.currentPeerIp === chatId) root.currentPeerIp = "" } // A reaction only leaves the window when the transport can carry it. function onLocalReaction(chatId, identifier, emoji, added) { if (root.isLanGroup(chatId)) return if (chatTransport.supportsReactions(chatId)) chatTransport.sendReaction(chatId, identifier, emoji, added) } // Called when a chat is opened and when a message arrives in the one already // open; the second was missing, which kept an outgoing message's "sent, not // confirmed" arrow up while the peer sat reading it. function markChatRead(ip) { if (ip.length === 0 || ip === root.kSelfChatId) return notificationManager.clearChat(ip) root.modelForPeer(ip).markAllRead() if (chatTransport.transportName(ip) === "lan") { if (root.isLanGroup(ip)) return // The receipt carries the newest stamp this screen has shown: the // peer marks its own rows up to exactly that, not one line further. networkManager.sendReadReceipt(ip, "dm", root.modelForPeer(ip).lastMessageStamp()) } else { // the registry sends the receipt the right way for this chat: a // homeserver receipt for a room, Telegram's read point for its own. chatTransport.markRead(ip) } } function upsertPeer(info) { const ip = info.ip if (!ip) return for (let i = 0; i < peersModel.count; ++i) { if (peersModel.get(i).ip === ip) { peersModel.set(i, info) return } } peersModel.append(info) } function removePeer(ip) { for (let i = 0; i < peersModel.count; ++i) { if (peersModel.get(i).ip === ip) { peersModel.remove(i) return } } } ListModel { id: peersModel } // rooms this account has been invited to; the sidebar draws accept and // decline. An invitation is not a conversation, so it stays out of chatList. ListModel { id: invitesModel } // what the sidebar draws: survives restarts and peers going offline, neither // of which peersModel does. ChatListModel { id: chatList historyManager: HistoryManager unreadManager: UnreadManager } // The folders the list is split into. They need the list to tell a room from Binding { target: ChatFolders property: "connectionMode" value: appSettings.connectionMode restoreMode: Binding.RestoreNone } Binding { target: ChatFolders property: "includeAllProtocols" value: appSettings.showChatsFromAllProtocols restoreMode: Binding.RestoreNone } // Matrix and Telegram reach the same models through the same calls as LAN; // nothing below this block knows which transport a conversation came from. Connections { target: telegramRooms function onRoomListed(chatId, displayName, avatarUrl, isRoom) { chatList.openChat(chatId, displayName) if (avatarUrl && avatarUrl.length > 0) chatList.setAvatar(chatId, avatarUrl) chatList.setChatAsRoom(chatId, isRoom) } function onRoomMessage(chatId, eventId, text, sender, isOwn, ts, isSystem, senderAvatar, senderId) { const model = root.modelForPeer(chatId) // Telegram replays history on every start/reconnect. Messages at or // below its read point were read in Telegram itself, so draw them // but neither notify nor count them as work still to do here. const inbox = telegramRooms.readInbox(chatId) const alreadyRead = inbox > 0 && !isOwn && !isSystem && Number(eventId) <= inbox if (!model.ingestRemoteMessage(eventId, text, sender, isOwn, ts, isSystem, senderAvatar, "", senderId, alreadyRead)) return if (isOwn) { // history and echoes are marked against the read point Telegram // already named, so a row ingested after its own outbox update // does not wait for one that will never come again. const outbox = telegramRooms.readOutbox(chatId) if (outbox > 0) model.markOwnMessagesReadUpToById(outbox) return } if (isSystem) return if (!alreadyRead && !(chatId === root.currentPeerIp && root.chatAtBottom)) notificationManager.notifyMessage(chatId, root.peerLabel(chatId), text) if (chatId === root.currentPeerIp && root.chatAtBottom) root.markChatRead(chatId) } function onRoomAttachment(chatId, eventId, media, sender, isOwn, ts, senderAvatar, senderId) { const model = root.modelForPeer(chatId) const inbox = telegramRooms.readInbox(chatId) const alreadyRead = inbox > 0 && !isOwn && Number(eventId) <= inbox if (!model.ingestRemoteAttachment(eventId, media, sender, isOwn, ts, senderAvatar, senderId, alreadyRead)) return if (isOwn) { const outbox = telegramRooms.readOutbox(chatId) if (outbox > 0) model.markOwnMessagesReadUpToById(outbox) return } if (!alreadyRead && !(chatId === root.currentPeerIp && root.chatAtBottom)) notificationManager.notifyMessage(chatId, root.peerLabel(chatId), media.name || "") if (chatId === root.currentPeerIp && root.chatAtBottom) root.markChatRead(chatId) } function onRoomAttachmentUpdated(chatId, eventId, media) { root.modelForPeer(chatId).updateRemoteAttachment(eventId, media) } // Telegram's read point moved for this chat: everything of ours up to // the named message id was read on the other side. function onRoomReadOutbox(chatId, maxMessageId) { root.modelForPeer(chatId).markOwnMessagesReadUpToById(maxMessageId) } // The client refused a send before any byte left - not signed in, or // the conversation is not one this account can write to. function onSendFailed(chatId, reason) { root.reportError(reason) } function onRoomLeft(chatId) { chatList.removeChat(chatId) } } Connections { target: matrixRooms function onRoomListed(chatId, displayName, avatarUrl, isRoom) { // openChat() is idempotent and never reorders, so a sync that lists // forty rooms does not shuffle the conversation the user is reading. chatList.openChat(chatId, displayName) if (avatarUrl && avatarUrl.length > 0) chatList.setAvatar(chatId, avatarUrl) // A Matrix room and a Matrix direct chat share one chat id prefix, so // only the homeserver's own answer says which folder the conversation // belongs in, and it arrives on this signal rather than as a lookup. chatList.setChatAsRoom(chatId, isRoom) } function onDirectChatOpened(chatId) { root.openChat(chatId) } function onRoomMessage(chatId, eventId, text, sender, isOwn, ts, isSystem, senderAvatar, formattedText, senderId) { const model = root.modelForPeer(chatId) // false means this event id was already ingested, as it is for the // backlog replayed after every reconnect. if (!model.ingestRemoteMessage(eventId, text, sender, isOwn, ts, isSystem, senderAvatar, formattedText, senderId)) return if (isSystem || isOwn) return if (!(chatId === root.currentPeerIp && root.chatAtBottom)) notificationManager.notifyMessage(chatId, root.peerLabel(chatId), text) if (chatId === root.currentPeerIp && root.chatAtBottom) root.markChatRead(chatId) } function onRoomAttachment(chatId, eventId, media, sender, isOwn, ts, senderAvatar, senderId) { const model = root.modelForPeer(chatId) if (!model.ingestRemoteAttachment(eventId, media, sender, isOwn, ts, senderAvatar, senderId)) return if (isOwn) return if (!(chatId === root.currentPeerIp && root.chatAtBottom)) notificationManager.notifyMessage(chatId, root.peerLabel(chatId), media.name || "") if (chatId === root.currentPeerIp && root.chatAtBottom) root.markChatRead(chatId) } function onRoomPoll(chatId, eventId, question, answers, disclosed, sender, isOwn, ts, senderAvatar, senderId) { // A poll is its own row kind; the window votes through sendPollVote. root.modelForPeer(chatId).ingestRemotePoll(eventId, question, answers, disclosed, sender, isOwn, ts, senderAvatar, senderId) } function onRoomPollVote(chatId, eventId, answerId, voterId, isOwn) { // not a row: a vote folded into the tally of the poll it answers. root.modelForPeer(chatId).applyPollResponse(eventId, answerId, voterId, isOwn) } // never a new row: the corrected text replaces what is already on the // screen, and false means the original is older than the loaded backlog. function onRoomMessageEdited(chatId, eventId, newText, formattedText) { root.modelForPeer(chatId).applyRemoteEdit(eventId, newText, true, formattedText) } // the same replacement without the "edited" mark: the key for an // encrypted message turned up and the placeholder row can finally say // what it always said. Nobody edited it. function onRoomMessageRevealed(chatId, eventId, text, formattedText) { root.modelForPeer(chatId).applyRemoteEdit(eventId, text, false, formattedText) } // A reaction badge to lift or take down, keyed on the stamp of the // message being reacted to - the same key the LAN reaction packet uses. function onRoomReaction(chatId, ts, emoji, sender, added) { if (added) ReactionStore.add(chatId, ts, emoji, sender) else ReactionStore.remove(chatId, ts, emoji, sender) } // one typing indicator per conversation, exactly as the LAN path's // onTyping is: a single string the page compares against its own chat. function onRoomTyping(chatId, typing) { if (typing) { root.typingChatId = chatId typingTimeout.restart() } else if (root.typingChatId === chatId) { root.typingChatId = "" } } // the peer read up to one of our messages; without a stamp, all of ours // are read by definition. function onRoomReadReceipt(chatId, upToTs) { const model = root.modelForPeer(chatId) if (upToTs > 0) model.markOwnMessagesReadUpTo(upToTs) else model.markOwnMessagesRead() } // A message that was already on the screen was redacted. The row goes // the way an unsent LAN message does: gone. function onRoomMessageRemoved(chatId, eventId) { const model = root.modelForPeer(chatId) const row = model.rowForMsgId(eventId) if (row >= 0) model.deleteMessage(row) } function onRoomInfoChanged(chatId) { if (chatId === root.currentPeerIp) root.refreshRoomInfo() // a room's picture can be changed from the room info column; the // conversation row keeps the avatar it got at listing time unless // it is refreshed from the same shape the header already re-reads. const refreshed = chatTransport.roomInfo(chatId) if (refreshed && refreshed.roomId) chatList.setAvatar(chatId, refreshed.avatarUrl || "") } function onRoomLeft(chatId) { // a left room leaves the window and the index; it can be re-entered // by Join or a fresh invite. root.dropChatLocally(chatId) } function onRoomInvited(chatId, displayName, inviterId, inviterName) { const inviter = inviterName && inviterName.length > 0 ? inviterName : (inviterId || "") for (let i = 0; i < invitesModel.count; i++) { if (invitesModel.get(i).chatId === chatId) { // name can arrive after the invite, so treat a repeat as an update invitesModel.set(i, { chatId: chatId, displayName: displayName, inviterId: inviterId || "", inviterName: inviter }) return } } invitesModel.append({ chatId: chatId, displayName: displayName, inviterId: inviterId || "", inviterName: inviter }) const roomLabel = displayName.length > 0 ? displayName : chatId notificationManager.notifyMessage(chatId, i18nc("@info:notification a Matrix room invitation", "Invited to a room"), inviter.length > 0 ? i18nc("@info:notification %1 is who invited, %2 is the room", "%1 invited you to %2", inviter, roomLabel) : roomLabel) } function onRoomInviteGone(chatId) { for (let i = 0; i < invitesModel.count; i++) { if (invitesModel.get(i).chatId === chatId) { invitesModel.remove(i) return } } } function onRoomOperationFailed(chatId, reason) { root.notify(reason, Kirigami.MessageType.Danger) } function onRoomOperationSucceeded(chatId) { root.notify(i18nc("@info", "Saved"), Kirigami.MessageType.Positive) } // a room call offered to this session: the dialog names who and the // media address accepting will dial. function onRoomCallInvited(chatId, callId, sender, mediaAddress) { // a second member may ask for our voice feed; another room waits // until this call closes. Nothing connects before the answer. const openWindow = root.activeCallWindow ? root.activeCallWindow : root.outgoingCallWindow if (openWindow && chatId !== openWindow.peerIp) return incomingCall.callerSource = chatId incomingCall.callerName = sender.length > 0 ? sender : root.peerLabel(chatId) incomingCall.callId = callId incomingCall.mediaAddress = mediaAddress incomingCall.open() } // the caller's invitation was answered: the media channel is up and the // call UI may come on screen. function onRoomCallAccepted(chatId) { root.openActiveCall(root.peerLabel(chatId), chatId) } // the call in the room is over, from the far side or from here. function onRoomCallEnded(chatId) { if (root.activeCallWindow && root.activeCallWindow.peerIp === chatId) { root.activeCallWindow.close() root.activeCallWindow = null } if (root.outgoingCallWindow && root.outgoingCallWindow.peerIp === chatId) { root.outgoingCallWindow.close() root.outgoingCallWindow = null } incomingCall.close() } function onSendFailed(chatId, reason) { root.reportError(reason) } } Connections { target: matrixManager function onSessionNotPersisted(reason) { root.notify(i18nc("@info:status %1 is the reason the store gave", "Signed in, but the session could not be saved: %1", reason), Kirigami.MessageType.Warning) } // the sign-in page is where a session is started and almost never where // the user is when one dies, so every failure is reported here too. The // alternative was the window saying "Syncing..." for the rest of the day. function onSessionError(message) { root.reportError(message) } } // never let a secret-store failure or identity change go unseen: each one // gets a visible banner. Connections { target: cryptoManager function onStoreDegraded(reason) { root.notify(i18nc("@info:status %1 is why the store failed", "Secret store unavailable (%1). " + "Keys are stored in an encrypted file for this session only " + "and will be lost on restart. Fix the store to keep your identity.", reason), Kirigami.MessageType.Warning) } function onPlaintextKeysLeftInConfig(reason) { root.notify(i18nc("@info:status %1 explains why the deletion failed", "Your private keys are still readable in the config file (%1). " + "Delete the identity_priv_b64 and dh_priv_b64 entries by hand.", reason), Kirigami.MessageType.Error) } } // the failure may predate this handler; Component.onCompleted checks for // that. Either way: no key store, no on-disk history. Connections { target: HistoryManager function onHistoryStoreUnavailable(reason) { root.notify(i18nc("@info:status %1 is why the store failed", "Chat history cannot be encrypted (%1). ", +"Nothing new will be saved to disk until the system key store works again.", reason), Kirigami.MessageType.Warning) } } // peersModel.count is read only to register a dependency, so this // re-evaluates as peers come and go. function peerInfoFor(ip) { /* eslint-disable no-unused-expressions */ peersModel.count if (ip === root.kSelfChatId) { return { // the address the card's Write button routes on: without it // the card would answer a tap with a chat id it could not open. ip: root.kSelfChatId, username: i18nc("@item contact list, chat with yourself", "Favorites"), os: "", e2e: false, avatarLetter: "\u2605", isFavorites: true, online: false, lastSeen: 0 } } for (let i = 0; i < peersModel.count; ++i) { const p = peersModel.get(i) if (p.ip === ip) { return { ip: ip, username: p.username || root.unknownPeerName, displayName: p.display_name || "", bio: p.bio || "", os: p.os || "", e2e: p.e2e === true, avatarLetter: (p.username || root.unknownPeerName).charAt(0).toUpperCase(), // set by onPeerAvatar on the row itself, so the open chat's // header re-reads it the moment the frame lands. avatar: p.avatar || "", // the header picture, arrived the same way: bytes off the // pinned channel, filed under the peer's key. banner: p.banner || root.peerBannerMap[ip] || "", isFavorites: false, statusEmoji: p.status_emoji || "", presence: p.presence || 0, // Being in peersModel is what reachable means: userOffline // takes a peer out as soon as presence stops arriving. online: true, // Stamped by handlePresence() on arrival, not sent by the peer, // so it only says anything once "online" above has gone false. lastSeen: p.last_seen || 0 } } } // not on the network: the conversation list is the only thing that still // remembers when a peer that is switched off was last around. const known = chatList.chatInfo(ip) return { ip: ip, username: known.displayName || root.unknownPeerName, os: "", e2e: false, avatarLetter: (known.displayName || root.unknownPeerName).charAt(0).toUpperCase(), // offline peers keep what they last pushed, keyed by chat id here so // the offline card still shows a face. avatar: root.peerAvatarMap[ip] || "", // and the same for the header picture: the last frame before the // peer went away is what an offline card shows. banner: root.peerBannerMap[ip] || "", isFavorites: false, statusEmoji: "", presence: 0, online: false, lastSeen: known.lastSeenSecs || 0 } } // the incoming call is declared below as a dialog instead: answering is a // question with two answers. property var outgoingCallWindow: null property var activeCallWindow: null // nothing rather than the bare address at the end, which used to put an IP in // the window title, in every notification and in the conversation list. function peerDisplayName(ip) { for (let i = 0; i < peersModel.count; ++i) { const p = peersModel.get(i) if (p.ip === ip) return p.display_name || p.username || "" } return "" } readonly property string unknownPeerName: i18nc("@info a peer that has published no name of its own", "Unknown peer") function peerLabel(ip) { if (root.isLanGroup(ip)) return root.lanGroupName(ip) const named = root.peerDisplayName(ip) if (named.length > 0) return named // the conversation list remembers a name for a peer that is switched // off, and it is the only place a room name can still be found. const known = chatList.chatInfo(ip) return known.displayName || root.unknownPeerName } // one file out, by whichever path the chat needs, so the attach button and // a drop cannot drift apart. chatPage's properties are read through root: // unqualified names here are ReferenceErrors. function sendOneFile(ip, localFilePath) { if (chatTransport.serverOwnsTimeline(ip)) { // no local row first: the server echoes the file back with the id // the whole room sees. if (chatTransport.transportName(ip) === "matrix") matrixRooms.sendFile(ip, localFilePath) else chatTransport.sendFile(ip, localFilePath) return } if (root.isLanGroup(ip)) { root.notify(i18nc("@info", "Sending files to LAN groups is not supported yet."), Kirigami.MessageType.Information) return } const model = root.modelForPeer(ip) if (!model) return const stamp = model.sendFile(localFilePath, root.looksLikeImage(localFilePath)) // A refused send is not a sent one: the row keeps its hourglass instead // of a tick, and whatever error the transport raised says why. if (ip !== root.kSelfChatId && !chatTransport.sendFile(ip, localFilePath)) return model.markSent(stamp) } function startOutgoingCall(ip) { if (root.outgoingCallWindow) return if (root.isLanGroup(ip)) { root.reportError(i18nc("@info:status", "Calls are not available in LAN groups.")) return } if (!chatTransport.supportsCalls(ip)) { // Voice is the LAN protocol's own, peer to peer over TCP. There is // no call on this transport and pretending otherwise would ring // nothing. root.reportError(i18nc("@info:status", "Calls are not available in this chat.")) return } if (root.currentIsRoom) { matrixRooms.callRoom(ip) } else { networkManager.sendCallRequest(ip) } const win = outgoingCallComponent.createObject( root, { peerName: root.peerLabel(ip), peerIp: ip }) win.cancelled.connect(function() { if (root.currentIsRoom) matrixRooms.hangupRoomCall(ip) else networkManager.sendCallEnd(ip) root.outgoingCallWindow = null }) root.outgoingCallWindow = win } function openActiveCall(username, ip) { if (root.outgoingCallWindow) { root.outgoingCallWindow.close() root.outgoingCallWindow = null } if (root.activeCallWindow) return const win = activeCallComponent.createObject(root, { peerName: username, peerIp: ip }) win.hangup.connect(function() { if (root.currentIsRoom) matrixRooms.hangupRoomCall(ip) else networkManager.sendCallEnd(ip) voiceCallManager.hangup(ip) root.activeCallWindow = null }) win.muteToggled.connect(function(muted) { voiceCallManager.setMute(muted) }) root.activeCallWindow = win } function endAllCalls() { voiceCallManager.hangupAll() if (root.activeCallWindow) { root.activeCallWindow.close(); root.activeCallWindow = null } if (root.outgoingCallWindow) { root.outgoingCallWindow.close(); root.outgoingCallWindow = null } } // by type rather than by resource path: the old Qt.createComponent() calls had // the module's internal resource layout in three string literals. Component { id: outgoingCallComponent; OutgoingCallWindow {} } Component { id: activeCallComponent; ActiveCallWindow {} } // one card, moved to whatever was clicked. openAt() reparents it, so it must // not be declared inside anything that gets destroyed under it - a delegate. PeerCard { id: peerCard onMessageRequested: (chatId) => root.openChat(chatId) onCallRequested: (chatId) => root.startOutgoingCall(chatId) onDetailsRequested: (chatId) => { root.openChat(chatId) if (!root.peerInfoOpen && !root.roomInfoPanelOpen) root.togglePeerInfo() } } // the account card, shared by the drawer's account row and an own message's // avatar; a room member opens the member card instead. RoomMemberCard { id: roomMemberCard chatId: root.currentPeerIp onNotifyRequested: (text) => root.notify(text, Kirigami.MessageType.Information) } // window-level, because a verification must survive the page that started // it, and another session may ask while no page of ours is open. DeviceVerificationDialog { id: deviceVerificationDialog } Connections { target: matrixVerification function onSessionFinished(ok, message) { root.notify(message, ok ? Kirigami.MessageType.Positive : Kirigami.MessageType.Warning) } } function showPeerCard(chatId, anchorItem) { if (chatId.length === 0 || chatId === root.kSelfChatId) return if (chatTransport.hasRooms(chatId) || root.isLanGroup(chatId)) { // the row in the conversation list is the room, not a person; the // room's own column is what has anybody in it. root.openChat(chatId) if (!root.peerInfoOpen && !root.roomInfoPanelOpen) root.togglePeerInfo() return } peerCard.openAt(anchorItem, root.peerInfoFor(chatId)) } function showRoomMemberCard(userId, anchorItem) { if (userId.length === 0 || !root.currentIsRoom) return if (root.isLanGroup(root.currentPeerIp)) return const info = chatTransport.memberInfo(root.currentPeerIp, userId) if (!info || !info.userId) return roomMemberCard.openAt(anchorItem, info) } AccountCard { id: accountCard onEditProfileRequested: root.showLayer(settingsPageComponent) onNotifyRequested: (text) => root.notify(text, Kirigami.MessageType.Information) } function showAccountCard(anchorItem) { // the row's tap toggles: the row that opened the card also closes it; // another anchor only moves it. if (accountCard.opened && accountCard.parent === anchorItem) accountCard.close() else accountCard.openAt(anchorItem) } IncomingCallDialog { id: incomingCall property string callId: "" onAnswered: { if (incomingCall.callId.length > 0) { matrixRooms.acceptCall(incomingCall.callerSource, incomingCall.callId) } else { networkManager.sendCallAccept(incomingCall.callerSource) voiceCallManager.call(incomingCall.callerSource) } root.openActiveCall(incomingCall.callerName, incomingCall.callerSource) } onDeclined: { if (incomingCall.callId.length > 0) matrixRooms.declineCall(incomingCall.callerSource, incomingCall.callId) else networkManager.sendCallReject(incomingCall.callerSource) } } Kirigami.Dialog { id: invitePeerDialog property string groupId: "" title: i18nc("@title:window", "Invite to LAN group") standardButtons: Kirigami.Dialog.Close preferredWidth: Kirigami.Units.gridUnit * 24 ColumnLayout { spacing: Kirigami.Units.smallSpacing QQC2.Label { Layout.fillWidth: true wrapMode: Text.WordWrap text: invitePeerDialog.groupId.length > 0 ? i18nc("@info %1 is a group name", "Choose an online peer to invite to \"%1\".", root.lanGroupName(invitePeerDialog.groupId)) : "" } ListView { Layout.fillWidth: true Layout.preferredHeight: Kirigami.Units.gridUnit * 14 clip: true model: peersModel delegate: QQC2.ItemDelegate { required property var model width: ListView.view.width text: (model.display_name || model.username || model.ip) + " (" + model.ip + ")" onClicked: { if (invitePeerDialog.groupId.length === 0) return GroupManager.addMember(invitePeerDialog.groupId, model.ip) networkManager.sendGroupInvite(invitePeerDialog.groupId, root.lanGroupName(invitePeerDialog.groupId), model.ip) root.notify(i18nc("@info:status %1 is a peer name, %2 is a group name", "Invite sent to %1 for \"%2\".", model.display_name || model.username || model.ip, root.lanGroupName(invitePeerDialog.groupId)), Kirigami.MessageType.Positive) invitePeerDialog.close() } } Kirigami.PlaceholderMessage { anchors.centerIn: parent width: parent.width - Kirigami.Units.largeSpacing * 4 visible: peersModel.count === 0 icon.name: "network-wireless" text: i18nc("@info", "No peers online") } } } } IncomingFileDialog { id: incomingFile // The consent is by transfer id: the handler already filed this offer // with the host it arrived from, so the dialog cannot name a different // file than the one the peer announced. onAcceptRequested: { if (root.pendingFiles.length === 0) return const offer = root.pendingFiles.shift() if (offer.meta.tid) fileTransferHandler.acceptOffer(offer.meta.tid) root.promptNextFile() } onDeclineRequested: { if (root.pendingFiles.length === 0) return const offer = root.pendingFiles.shift() if (offer.meta.tid) fileTransferHandler.declineOffer(offer.meta.tid) root.promptNextFile() } } onCurrentPeerIpChanged: { if (typeof telegramRooms !== "undefined") { if (root.openedTelegramChatId.length > 0 && root.openedTelegramChatId !== currentPeerIp) telegramRooms.setClosedChat(root.openedTelegramChatId) if (currentPeerIp.length > 0 && currentPeerIp.startsWith("tg:")) { root.openedTelegramChatId = currentPeerIp telegramRooms.setOpenedChat(currentPeerIp) telegramRooms.requestChatHistory(currentPeerIp) } else { root.openedTelegramChatId = "" } } if (currentPeerIp.length > 0 && currentPeerIp !== kSelfChatId) { chatList.openChat(currentPeerIp, root.peerDisplayName(currentPeerIp)) root.markChatRead(currentPeerIp) } root.refreshRoomInfo() // the details column and the room's side panel belong to the chat they // were opened from; switching chats closes both. // reopening it here was what made room info pop up over the new chat. if (root.peerInfoOpen || root.roomInfoPanelOpen) root.closePeerInfo() } function openChat(chatId) { root.currentPeerIp = chatId while (pageStack.layers.depth > 1) pageStack.layers.pop() pageStack.currentIndex = 1 } // The chat column stays open and shows its "pick a chat" placeholder - the // same thing Telegram does when a conversation is closed. Clearing the peer // is enough: onCurrentPeerIpChanged drops the details and refreshes the room. function closeChat() { if (root.currentPeerIp.length === 0) return root.currentPeerIp = "" // In compact mode there is no second column to look at, so the list is // what Escape should land on there. if (root.compact) pageStack.currentIndex = 0 } // Escape walks back out of whatever is on top, the same order the things function handleEscape(event) { // A Shortcut has no key event to accept; a Keys handler does. One local // object keeps both entry points on the same code path. const e = event || {accepted: false} if (pageStack.layers.depth > 1) { pageStack.layers.pop() e.accepted = true return } if (root.peerInfoOpen || root.roomInfoPanelOpen) { root.closePeerInfo() e.accepted = true return } if (root.currentPeerIp.length > 0) { root.closeChat() e.accepted = true return } if (pageStack.currentIndex === 1) { pageStack.currentIndex = 0 e.accepted = true } } // ApplicationWindow is a Window, not an Item: attaching Keys to it makes // Qt warn on every start. A window-scoped Shortcut is the platform way, and // PageRow still forwards Escape to the current item, handled below. Shortcut { // Cancel maps to several keys on some platforms; binding the list keeps // all of them working instead of picking one and warning about the rest. sequences: [StandardKey.Cancel] context: Qt.WindowShortcut onActivated: root.handleEscape(null) } pageStack.Keys.onEscapePressed: (event) => root.handleEscape(event) // True when the details page is up, on either stack: PeerInfoPage is a // pageStack column, RoomInfoPage rides on layers so it can be dismissed at // any width. Reading both keeps the toggle honest. readonly property bool peerInfoOpen: pageStack.depth > 2 || pageStack.layers.depth > 1 // the room info panel over the conversation; only its visibility is owned // here, the chat page draws it and gives it the dragged width. property bool roomInfoPanelOpen: false function closePeerInfo() { while (pageStack.layers.depth > 1) pageStack.layers.pop() while (pageStack.depth > 2) pageStack.pop() // the panel is the third shape the details take, and one close ends all // of them: a reader asking for the details to go away means all of them. root.roomInfoPanelOpen = false } function togglePeerInfo() { if (root.peerInfoOpen) { root.closePeerInfo() return } // a narrow window has no room beside the conversation, so the room info // returns to being a layer there. if (root.currentIsRoom) { if (root.compact || !chatPage.infoPanelFits) { root.showLayer(roomInfoComponent, { chatId: root.currentPeerIp }) return } root.roomInfoPanelOpen = !root.roomInfoPanelOpen } else { pageStack.push(peerInfoComponent) pageStack.currentIndex = pageStack.depth - 1 } } // an InlineMessage in the footer rather than the modal sheet this used to be, // which took the window away from whoever was using it. function notify(text, type) { notification.text = text // Some callers come in without a type; assigning undefined to the // int-typed property is a binding error, so fall back to the default. notification.type = typeof type === "undefined" ? Kirigami.MessageType.Information : type notification.visible = true } function reportError(text) { root.notify(text, Kirigami.MessageType.Error) } // Layers are one deep by design: a drawer entry replaces whatever layer is // showing instead of stacking a second copy of it behind the first. function showLayer(page, properties) { while (pageStack.layers.depth > 1) pageStack.layers.pop() pageStack.layers.push(page, properties) } // local decoration: never on the wire. Every page draws an opaque Item { id: wallpaperHost anchors.fill: parent z: -1 // never hidden: the chat list washes this item through its blur, and an // invisible item gives the effect nothing to draw. AnimatedImage { id: wallpaperImage readonly property bool wallpaperEnabled: !appSettings.disableWallpaper && appSettings.wallpaperPath.length > 0 // Tiling repeats the source at its decoded size, so shrinking it would readonly property bool tiledWallpaper: fillMode === Image.Tile || fillMode === Image.TileVertically || fillMode === Image.TileHorizontally readonly property int decodeLimitSetting: appSettings.wallpaperDecodeLimit visible: wallpaperEnabled anchors.fill: parent // through FsUtils: a theme gives a bare path, the file dialog gives // a file:// URL, and an Image in a qrc-loaded component resolves the // bare path as qrc:/home/... and draws nothing. source: wallpaperEnabled ? FsUtils.toSourceUrl(appSettings.wallpaperPath) : "" fillMode: ThemePalette.wallpaperFillModeOf(appSettings.wallpaperFillMode) asynchronous: true sourceSize: (tiledWallpaper || decodeLimitSetting <= 0) ? undefined : Qt.size(decodeLimitSetting, decodeLimitSetting) playing: !appSettings.freezeAnimatedImages onStatusChanged: { if (status === AnimatedImage.Ready) playing = !appSettings.freezeAnimatedImages } onPlayingChanged: { if (appSettings.freezeAnimatedImages && playing) playing = false } } // the blur, off at zero: the Image above is what it samples, so the // pair still draws the picture exactly once. MultiEffect { id: wallpaperBlurEffect visible: wallpaperImage.wallpaperEnabled && !appSettings.disableWallpaperBlur anchors.fill: parent source: wallpaperImage // the picture fills the window edge to edge, and a blur that // shrank it to make room for its own spread would show a border of // nothing round it; the shader clamps at the edges instead. autoPaddingEnabled: false blurEnabled: !appSettings.disableWallpaperBlur && appSettings.wallpaperBlur > 0 blur: appSettings.wallpaperBlur / 100 // the strongest blur the effect's own scale tops out at; below it // the slider's whole range is on the same curve. blurMax: root.wallpaperBlurMax } // the scrim is floored: text over an arbitrary photograph is not // legible, and in the theme's surface colour the picture and the window // keep the contrast they had over the grey. Rectangle { visible: wallpaperImage.wallpaperEnabled anchors.fill: parent color: ThemePalette.surface opacity: Math.max(0.2, 1 - appSettings.wallpaperOpacity / 100) } // the chat list's own blur over the wallpaper, separate from the Item { id: chatListBackdropBlur readonly property point panelPos: { const d = [chatListPage.x, chatListPage.y, chatListPage.width, chatListPage.height, root.width, root.height, pageStack.width, pageStack.x, pageStack.currentIndex, root.compact, chatListPage.visible] return chatListPage.mapToItem(wallpaperHost, 0, 0) } readonly property bool active: wallpaperImage.wallpaperEnabled && !appSettings.disableOverlayBlur && appSettings.panelTransparency > 0 && chatListPage.visible x: panelPos.x y: panelPos.y width: chatListPage.width height: chatListPage.height visible: active clip: true MultiEffect { x: -chatListBackdropBlur.panelPos.x y: -chatListBackdropBlur.panelPos.y width: wallpaperHost.width height: wallpaperHost.height source: wallpaperImage autoPaddingEnabled: false blurEnabled: !appSettings.disableOverlayBlur && appSettings.panelWallpaperBlur > 0 blur: appSettings.panelWallpaperBlur / 100 blurMax: root.wallpaperBlurMax } } // The profile row shares the list's veil but can keep its own blur, so Item { id: profileBarBackdropBlur readonly property Item bar: chatListPage.profileBarItem readonly property bool barShown: bar !== null && bar.visible readonly property point barPos: barShown ? bar.mapToItem(wallpaperHost, 0, 0) : Qt.point(0, 0) readonly property bool active: appSettings.profileBarBlurEnabled && !appSettings.reuseWindowBlur && !appSettings.disableOverlayBlur && wallpaperImage.wallpaperEnabled && appSettings.panelTransparency > 0 && barShown x: barPos.x y: barPos.y width: barShown ? bar.width : 0 height: barShown ? bar.height : 0 visible: active clip: true MultiEffect { x: -profileBarBackdropBlur.barPos.x y: -profileBarBackdropBlur.barPos.y width: wallpaperHost.width height: wallpaperHost.height source: wallpaperImage autoPaddingEnabled: false blurEnabled: !appSettings.disableOverlayBlur && appSettings.profileBarWallpaperBlur > 0 blur: appSettings.profileBarWallpaperBlur / 100 blurMax: root.wallpaperBlurMax } } } // the window's one music player: a single decoder that outlives every // page, so a song keeps playing between conversations. QtObject { id: musicState // the chat the track came from, and the local file behind it. property string chatId: "" property string source: "" property string title: "" property string performer: "" readonly property bool active: chatId.length > 0 && source.length > 0 } // the played tracks in the order they were first asked for; a track is a // message, not a library entry, so the queue is not persisted. property var musicQueue: [] property int musicQueueIndex: -1 // What the repeat button cycles through: 0 nothing, 1 the whole queue, // 2 the one track, over and over. property int musicRepeatMode: 0 // One entry point for every row and the bar itself: a second tap on the // track that is already playing is a pause, the pause button the row // itself cannot be. function playMusic(chatId, source, title) { if (source.length === 0) return if (musicState.chatId === chatId && musicState.source === source) { if (musicPlayer.playbackState === MediaPlayer.PlayingState) musicPlayer.pause() else musicPlayer.play() return } // The track joins the queue the first time it is asked for; one // already in it is jumped to, and the ask-to-end order is kept. musicQueueIndex = -1 for (let i = 0; i < musicQueue.length; ++i) { if (musicQueue[i].source === source) { musicQueueIndex = i break } } if (musicQueueIndex < 0) { musicQueue.push({ chatId: chatId, source: source, title: title }) musicQueueIndex = musicQueue.length - 1 } startTrack(chatId, source, title) } // The player's one way onto a track: state, stop, source, play. The // performer is cleared here rather than only filled by metadata: a track // with no artist tag would otherwise keep the name of the one before it. function startTrack(chatId, source, title) { musicState.chatId = chatId musicState.source = source musicState.title = title musicState.performer = "" musicPlayer.stop() musicPlayer.source = source musicPlayer.play() } // The float's forward and back: one step through the queue, wrapping // only while the whole queue is set to repeat, standing still at the // ends otherwise - a queue of one track steps nowhere without it. function musicSkip(delta) { if (musicQueue.length === 0 || musicState.source.length === 0) return let next = musicQueueIndex + delta if (next >= musicQueue.length) { if (root.musicRepeatMode !== 1) return next = 0 } else if (next < 0) { if (root.musicRepeatMode !== 1) return next = musicQueue.length - 1 } musicQueueIndex = next startTrack(musicQueue[next].chatId, musicQueue[next].source, musicQueue[next].title) } // The repeat button's cycle: off, all, one, off. function cycleMusicRepeat() { root.musicRepeatMode = (root.musicRepeatMode + 1) % 3 } function stopMusic() { musicPlayer.stop() musicState.chatId = "" musicState.source = "" musicState.title = "" musicState.performer = "" musicQueue = [] musicQueueIndex = -1 } MediaPlayer { id: musicPlayer audioOutput: AudioOutput { volume: 0.9 } // The tags beat the file name: a properly titled track says so only // once the decoder has read it, so the pill's label listens here. onMetaDataChanged: { const t = musicPlayer.metaData.stringValue(MediaMetaData.Title) if (t.length > 0) musicState.title = t const artist = musicPlayer.metaData.stringValue(MediaMetaData.AlbumArtist) || musicPlayer.metaData.stringValue(MediaMetaData.ContributingArtist) if (artist.length > 0) musicState.performer = artist } // a finished track moves the queue along, wrapping on repeat-all and // staying on repeat-one; the pill stays stopped at the end. onMediaStatusChanged: (status) => { if (status !== MediaPlayer.EndOfMedia) return if (root.musicRepeatMode === 2) { musicPlayer.position = 0 musicPlayer.play() return } if (musicQueueIndex + 1 < musicQueue.length) { musicQueueIndex += 1 startTrack(musicQueue[musicQueueIndex].chatId, musicQueue[musicQueueIndex].source, musicQueue[musicQueueIndex].title) return } if (root.musicRepeatMode === 1 && musicQueue.length > 0) { musicQueueIndex = 0 startTrack(musicQueue[0].chatId, musicQueue[0].source, musicQueue[0].title) return } musicPlayer.stop() } } // the player outside its own chat: a pill under the header, because the Shortcut { sequences: [StandardKey.FullScreen, "F11"] context: Qt.ApplicationShortcut onActivated: root.toggleFullScreen() } function toggleFullScreen() { root.visibility = (root.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen } globalDrawer: Kirigami.GlobalDrawer { id: mainDrawer title: i18nc("@title:window", "KOutNet") titleIcon: "io.github.bitzuka.koutnet" // A drawer that stays put would eat a third of a narrow window. modal: true // the drawer's edge handle is the burger. Kirigami turns it into a cross // while the drawer is out, but there are already three ways to close it, // so the handle stays a burger. handleVisible: !drawerOpen && root.controlsVisible actions: [ Kirigami.Action { text: i18nc("@action:inmenu the list of conversations", "Chats") icon.name: "dialog-messages" // invisible against the dark drawer; text colour matches the label. See GlobalDrawerActionItem.qml. icon.color: ThemePalette.text onTriggered: { while (root.pageStack.layers.depth > 1) root.pageStack.layers.pop() root.pageStack.currentIndex = 0 } }, Kirigami.Action { // count goes in the label, a GlobalDrawer action has no badge of its own text: invitesModel.count > 0 ? i18nc("@action:inmenu room invitations waiting, %1 is how many", "Invitations (%1)", invitesModel.count) : i18nc("@action:inmenu room invitations waiting", "Invitations") icon.name: "mail-mark-unread" icon.color: ThemePalette.text visible: invitesModel.count > 0 onTriggered: root.showLayer(invitationsPageComponent) }, Kirigami.Action { text: i18nc("@action:inmenu open the media player", "Media player") icon.name: "multimedia-player" icon.color: ThemePalette.text onTriggered: root.showLayer(playerPageComponent) }, Kirigami.Action { separator: true }, // the profile is the first section of the settings page, so this and // the entry below it open the same layer. Kirigami.Action { text: i18nc("@action:inmenu", "My profile") icon.name: "user-identity" icon.color: ThemePalette.text onTriggered: root.showLayer(settingsPageComponent) }, Kirigami.Action { text: i18nc("@action:inmenu", "Settings") icon.name: "settings-configure" icon.color: ThemePalette.text shortcut: StandardKey.Preferences onTriggered: root.showLayer(settingsPageComponent) }, // not checkable, for the same reason as the microphone entry above. Kirigami.Action { text: root.compact ? i18nc("@action:inmenu go back to the full three-column layout", "Leave compact mode") : i18nc("@action:inmenu switch to a reduced layout for a narrow window", "Compact mode") icon.name: root.compact ? "sidebar-expand" : "sidebar-collapse" icon.color: ThemePalette.text onTriggered: root.toggleCompact() }, Kirigami.Action { text: root.visibility === Window.FullScreen ? i18nc("@action:inmenu leave full screen", "Exit full screen") : i18nc("@action:inmenu", "Full screen") icon.name: root.visibility === Window.FullScreen ? "view-restore" : "view-fullscreen" // Full screen and compact are opposite requests, and compact // resizes the window, which a full-screen window cannot honour. enabled: !root.compact onTriggered: root.toggleFullScreen() }, Kirigami.Action { text: i18nc("@action:inmenu", "Quit") icon.name: "application-exit" shortcut: StandardKey.Quit onTriggered: Qt.quit() } ] // the drawer's own way out: a modal drawer leaves nothing outside to // click, and Kirigami's drawer has no close button. header: RowLayout { spacing: Kirigami.Units.largeSpacing QQC2.Label { Layout.fillWidth: true visible: !mainDrawer.collapsed text: mainDrawer.title elide: Text.ElideRight // sized like the theme's heading without Kirigami's missing // headingFont; one font assignment, not two. font { pointSize: Kirigami.Theme.defaultFont.pointSize * 1.3 bold: true } color: ThemePalette.text } QQC2.ToolButton { display: QQC2.AbstractButton.IconOnly icon.name: "window-close" icon.color: ThemePalette.text text: i18nc("@action:button close this menu", "Close") QQC2.ToolTip.visible: hovered QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay QQC2.ToolTip.text: text onClicked: mainDrawer.close() } } } footer: ColumnLayout { spacing: 0 Kirigami.InlineMessage { id: notification Layout.fillWidth: true position: Kirigami.InlineMessage.Position.Footer showCloseButton: true visible: false type: Kirigami.MessageType.Information } // the bar itself is hidden, not just its label: the desktop style gives a // toolbar background an implicit forty pixels whatever is inside it, which // is the strip of empty grey that used to sit under every page. QQC2.ToolBar { Layout.fillWidth: true visible: !root.compact && peersModel.count > 0 position: QQC2.ToolBar.Footer contentItem: RowLayout { spacing: Kirigami.Units.largeSpacing // the empty case used to say it was searching, which is true every // second the application runs and so worth saying in none of them. QQC2.Label { Layout.fillWidth: true elide: Text.ElideRight font: Kirigami.Theme.smallFont color: AppPalette.disabledText text: i18ncp("@info:status %1 is a number of peers", "%1 peer on the network", "%1 peers on the network", peersModel.count) } // no address: this used to print the host's own IP in every shot. } } } Connections { target: networkManager function onUserOnline(peerInfo) { root.upsertPeer(peerInfo) chatList.setPresence(peerInfo.ip, true, peerInfo.last_seen || 0, peerInfo.display_name || peerInfo.username || "") } function onPeerRefreshed(ip, lastSeen) { chatList.setPresence(ip, true, lastSeen, "") } function onUserOffline(ip) { root.removePeer(ip) // the stamp is deliberately not touched: the last presence that arrived // is when the peer was last seen, and "now" grows into "just now". chatList.setPresence(ip, false, 0, "") } // A peer's picture off its TLS channel: give every surface that can show // it the same local file, and remember it here as the offline fallback. function onPeerAvatar(ip, avatarSource) { chatList.setAvatar(ip, avatarSource) root.peerAvatarMap[ip] = avatarSource for (let i = 0; i < peersModel.count; ++i) { const row = peersModel.get(i) if (row.ip === ip) { row.avatar = avatarSource peersModel.set(i, row) break } } if (root.currentIsRoom) { // a room's head icon comes from the bridge, not from here. return } if (ip === root.currentPeerIp) { chatPage.peerAvatarSource = avatarSource chatPage.peerInfo = root.peerInfoFor(root.currentPeerIp) } const model = root.modelForPeer(ip) if (typeof model.setPeerAvatar === "function") model.setPeerAvatar(avatarSource) } // A peer's banner off its TLS channel: same story, one field up the // header. The peer row carries it, the offline map remembers it, and a // profile card that is open on this peer re-reads it at once. function onPeerBanner(ip, bannerSource) { root.peerBannerMap[ip] = bannerSource for (let i = 0; i < peersModel.count; ++i) { const row = peersModel.get(i) if (row.ip === ip) { row.banner = bannerSource peersModel.set(i, row) break } } if (ip === root.currentPeerIp && !root.currentIsRoom) { chatPage.peerInfo = root.peerInfoFor(root.currentPeerIp) } } // Filed under from_ip, not the username in the packet: the peer chose that // for itself and two of them can say the same thing. function onTyping(username, chatId, fromIp) { if (fromIp.length === 0) return root.typingChatId = (chatId && chatId.length > 0) ? chatId : fromIp typingTimeout.restart() } function onGroupInvite(gid, name, fromIp) { if (gid.length === 0) return GroupManager.ensureImportedGroup(gid, name, fromIp, [networkManager.hostIp(), fromIp]) root.ensureLanGroupChat(gid, name) root.notify(i18nc("@info:status %1 is a group name", "Joined LAN group \"%1\".", root.lanGroupName(gid)), Kirigami.MessageType.Positive) } function onGroupKeyConfirmationRequired(gid, name, fromIp) { root.reportError(i18nc("@info:status %1 is a group name, %2 is a peer address or identity", "The key for LAN group \"%1\" changed (reported by %2). The new key was not applied automatically.", name && name.length > 0 ? name : gid, fromIp)) } function onMessage(msg) { if (msg.type === "private") { root.modelForPeer(msg.from_ip).receiveMessage(msg.text, msg.from_ip) if (!(msg.from_ip === root.currentPeerIp && root.chatAtBottom)) notificationManager.notifyMessage(msg.from_ip, root.peerLabel(msg.from_ip), msg.text) if (root.typingChatId === msg.from_ip) root.typingChatId = "" // A message that landed below the fold of a conversation somebody // scrolled up out of has not been read, whatever the receipt says. if (msg.from_ip === root.currentPeerIp && root.chatAtBottom) root.markChatRead(msg.from_ip) } else if (msg.type === "group" && msg.gid && msg.gid.length > 0) { const gid = msg.gid const senderIp = msg.from_ip || "" const senderName = root.peerLabel(senderIp) || senderIp if (!GroupManager.isGroup(gid)) GroupManager.ensureImportedGroup(gid, gid, senderIp, [networkManager.hostIp(), senderIp]) else if (senderIp.length > 0) GroupManager.addMember(gid, senderIp) root.ensureLanGroupChat(gid) root.modelForPeer(gid).receiveMessage(msg.text, senderName) if (!(gid === root.currentPeerIp && root.chatAtBottom)) notificationManager.notifyMessage(gid, root.lanGroupName(gid), msg.text) if (root.typingChatId === gid) root.typingChatId = "" if (gid === root.currentPeerIp && root.chatAtBottom) root.markChatRead(gid) } else if (msg.type === "edit") { // msg_ts is the stamp of the original, which is the only identifier // the two ends share - see NetworkManager::sendMessageEdit. const editModel = root.modelForPeer(msg.from_ip) const editRow = editModel.rowForStamp(msg.msg_ts) if (editRow >= 0) editModel.editMessage(editRow, msg.new_text) } else if (msg.type === "delete") { const delModel = root.modelForPeer(msg.from_ip) const delRow = delModel.rowForStamp(msg.msg_ts) if (delRow >= 0) delModel.deleteMessage(delRow) } else if (msg.type === "read") { // from_ip is the address the peer is filed under; when a // position is named, everything of ours up to it was read. const readModel = root.modelForPeer(msg.from_ip) const upTo = msg.up_to_ts || 0 if (upTo > 0) readModel.markOwnMessagesReadUpTo(upTo) else readModel.markOwnMessagesRead() } else if (msg.type === "reaction") { // chat_id is what the peer calls the conversation, which // for a one-to-one is the same address the sender is filed // under here; from_ip is the fallback when it is absent. const reactionChat = msg.chat_id.length > 0 ? msg.chat_id : msg.from_ip const reactionWho = root.peerLabel(msg.from_ip) if (msg.added) ReactionStore.add(reactionChat, msg.msg_ts, msg.emoji, reactionWho) else ReactionStore.remove(reactionChat, msg.msg_ts, msg.emoji, reactionWho) } } function onCallRequest(username, ip) { incomingCall.callerName = username incomingCall.callerSource = ip incomingCall.mediaAddress = "" incomingCall.open() // Unconditionally, unlike a message: a dialog behind whatever the // user is actually looking at is not a ringing telephone. notificationManager.notifyCall(username, ip) } function onCallAccepted(username, ip) { voiceCallManager.call(ip) root.openActiveCall(username, ip) } function onCallRejected(ip) { if (root.outgoingCallWindow) { root.outgoingCallWindow.close() root.outgoingCallWindow = null } } function onCallEnded(ip) { notificationManager.clearCall(ip) if (root.outgoingCallWindow) { root.outgoingCallWindow.close(); root.outgoingCallWindow = null } if (root.activeCallWindow) { root.activeCallWindow.close(); root.activeCallWindow = null } // the old dialog had a callRejected() nothing ever called, so a caller // giving up left the prompt sitting there. incomingCall.callRejected() voiceCallManager.hangup(ip) } // these used to go nowhere, so a bind failure looked like an idle network. function onErrorOccurred(message) { root.reportError(message) } // a file offer waits on the C++ side until the dialog consents; until // then the peer's chunks find no transfer and are dropped. function onFileMeta(host, meta) { root.pendingFiles.push({ host: host, meta: meta }) if (!incomingFile.visible) root.promptNextFile() } } // A notification is the only thing here that can be clicked while the window // is behind something else, so everything it offers raises the window first. Connections { target: notificationManager // the compositor's activation token is adopted on the C++ side before these // arrive, so requestActivate() is allowed to do something. function onChatRequested(chatId) { root.show() root.raise() root.requestActivate() root.openChat(chatId) } function onReplyRequested(chatId, text) { if (text.trim().length === 0) return if (chatTransport.serverOwnsTimeline(chatId)) { // no local row first: the server echoes the message back with // the id the whole timeline is keyed on (see the composer note // in ChatPage below). chatTransport.sendText(chatId, text) return } if (root.isLanGroup(chatId)) { const groupModel = root.modelForPeer(chatId) const groupStamp = groupModel.sendMessage(text) if (groupStamp === 0) return networkManager.sendGroupMessage(chatId, text, GroupManager.memberIps(chatId)) groupModel.markSent(groupStamp) return } const replyModel = root.modelForPeer(chatId) const replyStamp = replyModel.sendMessage(text) // the saved-messages chat has no wire to ride; everything else // marks sent only when the transport actually took the text. if (chatId !== root.kSelfChatId && !chatTransport.sendText(chatId, text)) return replyModel.markSent(replyStamp) } function onCallAnswerRequested(ip) { root.show() root.raise() root.requestActivate() networkManager.sendCallAccept(ip) voiceCallManager.call(ip) root.openActiveCall(root.peerLabel(ip), ip) incomingCall.callRejected() } function onCallRejectRequested(ip) { networkManager.sendCallReject(ip) incomingCall.callRejected() } function onCallShowRequested(ip) { root.show() root.raise() root.requestActivate() if (incomingCall.callerSource !== ip) { incomingCall.callerName = root.peerLabel(ip) incomingCall.callerSource = ip } incomingCall.open() } } Connections { target: audioDevices function onError(message) { root.reportError(message) } } Connections { target: fileTransferHandler function onTransferRejected(tid, reason) { root.reportError(reason) } function onFileSaved(meta, localPath) { const fromIp = meta.from_ip if (!fromIp) return root.modelForPeer(fromIp).receiveFile(localPath, root.looksLikeImage(localPath), fromIp) if (fromIp === root.currentPeerIp && root.chatAtBottom) root.markChatRead(fromIp) } } function looksLikeImage(path) { return /\.(png|jpg|jpeg|gif|bmp|webp)$/i.test(path) } function humanFileSize(bytes) { if (!(bytes > 0)) return "0 B" const units = ["B", "KiB", "MiB", "GiB"] let value = bytes let unit = 0 while (value >= 1024 && unit < units.length - 1) { value /= 1024 ++unit } return value.toFixed(unit === 0 ? 0 : 1) + " " + units[unit] } function promptNextFile() { if (root.pendingFiles.length === 0) return const offer = root.pendingFiles[0] const meta = offer.meta incomingFile.senderName = root.peerLabel(meta.from_ip) // the address the frame really came on, not the one the meta claims: // over TLS that is the peer the pin authenticated incomingFile.senderSource = offer.host || meta.from_ip incomingFile.fileName = meta.filename incomingFile.fileSize = root.humanFileSize(meta.size || 0) incomingFile.open() } // defaultColumnWidth is what every column gets unless it sets // ColumnView.fillWidth. Pages are handed as objects, not Components: // PageRow would otherwise instantiate them outside the scene and warn. pageStack.initialPage: [chatListPage, chatPage] pageStack.defaultColumnWidth: root.kRoomyColumnWidth pageStack.globalToolBar.style: Kirigami.ApplicationHeaderStyle.ToolBar pageStack.globalToolBar.showNavigationButtons: Kirigami.ApplicationHeaderStyle.ShowBackButton // trayIcon is null if the setting was off at start - see main.cpp on why it is // not built later - so everything that touches it is guarded. readonly property bool hasTray: typeof trayIcon !== "undefined" && trayIcon !== null // the same fold toggleCompact() applies by hand, for the window simply // being dragged narrow: a third column has nowhere to live in a one-column // stack, and without this the room page stayed open with no way back. Connections { target: root.pageStack function onWideModeChanged() { // drop the details page on any layout change; reopening is the info button root.closePeerInfo() } // the details page is a third page on the stack; in collapsed layout the back // button only steps currentIndex, so pop it when the user steps off it. // wide mode shows all columns at once, so this is collapsed-only. function onCurrentIndexChanged() { if (root.pageStack.wideMode) return if (root.peerInfoOpen && root.pageStack.currentIndex < root.pageStack.depth - 1) root.closePeerInfo() } } // Bindings rather than a Connections block: a signal handler per property // would be four places for these to fall out of step. Binding { target: root.hasTray ? trayIcon : null property: "unreadCount" value: UnreadManager.total restoreMode: Binding.RestoreNone } Binding { target: root.hasTray ? trayIcon : null property: "micMuted" value: root.micMuted restoreMode: Binding.RestoreNone } Binding { target: root.hasTray ? trayIcon : null property: "deafened" value: root.deafened restoreMode: Binding.RestoreNone } Binding { target: root.hasTray ? trayIcon : null property: "presence" value: appSettings.presence restoreMode: Binding.RestoreNone } Binding { target: root.hasTray ? trayIcon : null property: "windowVisible" value: root.visible restoreMode: Binding.RestoreNone } Connections { target: root.hasTray ? trayIcon : null function onShowHideRequested() { if (root.visible) { root.hide() return } root.show() root.raise() root.requestActivate() } function onMuteToggleRequested() { root.toggleMic() } function onDeafenToggleRequested() { root.toggleDeafen() } function onPresenceRequested(presence) { appSettings.presence = presence } function onQuitRequested() { Qt.quit() } } // main.cpp turns off quitOnLastWindowClosed, so the branch that really closes // has to call Qt.quit() itself - see the note there. onClosing: (close) => { if (root.hasTray && appSettings.minimizeToTray) { close.accepted = false root.hide() return } close.accepted = true Qt.quit() } Component.onCompleted: { // The folders are given the conversation list here because the page that // draws them is below: a folder is told what it holds by the list, and // a folder with no list cannot count its own rows. ChatFolders.chatList = chatList if (root.hasTray) trayIcon.attachWindow(root) // the setting survives a restart on its own, the size does not, so the // application used to reopen as a compact layout in a full-width window. if (root.compact) root.applyCompactSize() // Measured here rather than bound: the window has the size it opened at // by now, and a fifth of that is the default. Afterwards the width is // whatever was dragged, and resizing the window does not touch it. root.kChatListColumnWidth = appSettings.chatListWidth > 0 ? appSettings.chatListWidth : root.defaultChatListColumnWidth() // the room's panel starts at its own saved width, or at the width the // conversation list would have opened at when nothing was ever dragged. root.kInfoPanelColumnWidth = appSettings.roomInfoWidth > 0 ? appSettings.roomInfoWidth : root.defaultInfoPanelColumnWidth() if (appSettings.showWelcome) root.openWizard() else root.show() // the singleton was built before this handler could listen; if the key // store was already gone by then, say so once. if (!HistoryManager.historyEncryptionAvailable) { root.notify(i18nc("@info:status history is withheld because encryption is impossible", "Chat history cannot be encrypted and will not be saved to disk. " + "Fix the system key store to keep your conversations."), Kirigami.MessageType.Warning) } } // the seam between the list and the conversation. A DragHandler, not a // MouseArea over one: the MouseArea takes the press and the drag never // starts. The DragHandler sets the cursor, the HoverHandler the highlight. ChatListResizeHandle { id: chatListHandle parent: chatListPage page: chatListPage // Two columns at once is the only place there is a seam to grab. In // compact mode the list is the whole window, and a narrow window has one // column, so there is nothing to move there. visible: !root.compact && root.pageStack.wideMode currentWidth: root.chatListColumnWidth() onWidthRequested: (width) => root.setChatListColumnWidth(width) } ChatListPage { id: chatListPage selectedChatId: root.currentPeerIp favoritesChatId: root.kSelfChatId connectionMode: appSettings.connectionMode showChatsFromAllProtocols: appSettings.showChatsFromAllProtocols model: chatList invites: invitesModel micMuted: root.micMuted deafened: root.deafened compact: root.compact // The raw picture for the column's own blur/transparency, so it can // blur independently without sampling the window's blur and scrim again. wallpaperSource: wallpaperImage backdrop: wallpaperHost // the width below which a row becomes a strip of avatars; the page and // its rows are all given this one number. narrowBelowWidth: root.kNarrowChatListWidth onChatActivated: (chatId) => root.openChat(chatId) onInviteAccepted: (chatId) => matrixRooms.acceptInvite(chatId) onInviteDeclined: (chatId) => matrixRooms.declineInvite(chatId) onMicToggled: root.toggleMic() onDeafenToggled: root.toggleDeafen() onPeerCardRequested: (chatId, anchorItem) => root.showPeerCard(chatId, anchorItem) onNewChatRequested: root.showLayer(newChatPageComponent) onProfileRequested: (anchorItem) => root.showAccountCard(anchorItem) onSettingsRequested: root.showLayer(settingsPageComponent) onLeaveRoomRequested: (chatId) => chatTransport.leaveChat(chatId) onDeleteRequested: (chatId) => root.dropChatLocally(chatId) selfChatId: root.kSelfChatId onForgetRequested: (chatId) => { chatList.removeChat(chatId) if (root.currentPeerIp === chatId) root.currentPeerIp = "" } onClearRequested: (chatId) => { clearChatPrompt.chatId = chatId clearChatPrompt.open() } // the same two calls the settings page makes, because switching mode is // a transport change, not a setting to apply one field at a time. onConnectionModeRequested: (mode) => { if (mode === 2) { appSettings.connectionMode = 2 if (typeof telegramRooms !== "undefined" && telegramRooms.authState !== 5) root.showLayer(telegramLoginComponent) return } if (!networkManager.modeAvailable(mode)) return appSettings.connectionMode = mode networkManager.setConnectionMode(mode) } // drop the filters, Home is every conversation. onHomeRequested: { chatListPage.directOnly = false chatListPage.searchText = "" } // NeoChat's Direct Messages, not the chat with yourself. onPersonalMessagesRequested: { chatListPage.searchText = "" chatListPage.directOnly = true } onCreateRoomRequested: { if (matrixManager.loggedIn) createRoomDialog.openWithFocus() else root.notify(i18nc("@info:status creating a room needs a Matrix account", "Sign in to a Matrix account to create a room.")) } onBrowseRequested: root.showLayer(browsePageComponent) } // Emptying a chat cannot be undone, and the saved messages one is // where people keep things. Kirigami.PromptDialog { id: clearChatPrompt property string chatId: "" title: i18nc("@title:window", "Clear this chat?") subtitle: i18nc("@info", "Every message in it is deleted from this device. There is no way back.") standardButtons: Kirigami.Dialog.Cancel customFooterActions: [ Kirigami.Action { text: i18nc("@action:button", "Clear") icon.name: "edit-clear-all" onTriggered: { const model = root.chatModels[clearChatPrompt.chatId] if (model) model.clearMessages() clearChatPrompt.close() } } ] } ChatPage { id: chatPage onOpenChatRequested: (chatId) => root.openChat(chatId) readonly property bool isSelfChat: peerIp === root.kSelfChatId // without this the conversation is handed defaultColumnWidth like the list. Kirigami.ColumnView.fillWidth: true compact: root.compact isRoom: root.currentIsRoom roomInfo: root.currentRoomInfo peerIp: root.currentPeerIp // The page is what PageRow forwards Escape to; the window handler can // be bypassed there, so the conversation is closed from here as well. Keys.onEscapePressed: (event) => root.handleEscape(event) peerInfo: root.currentPeerIp.length > 0 ? root.peerInfoFor(root.currentPeerIp) : null messagesModel: root.currentPeerIp.length > 0 ? root.modelForPeer(root.currentPeerIp) : null peerTyping: root.typingChatId.length > 0 && root.typingChatId === root.currentPeerIp selfDisplayName: appSettings.displayName || appSettings.username // Same face as the account row: the transport in charge owns it. selfAvatarSource: appSettings.connectionMode === 1 && matrixManager.loggedIn ? matrixManager.avatarUrl : (appSettings.connectionMode === 2 && typeof telegramRooms !== "undefined" && telegramRooms.ownAvatarUrl.length > 0 ? telegramRooms.ownAvatarUrl : FsUtils.toSourceUrl(appSettings.avatarPath)) // non-empty once the peer's own avatar frame has landed; rooms draw // their own head icon from roomInfo and ignore this source. peerAvatarSource: isRoom ? "" : (root.peerAvatarMap[root.currentPeerIp] || "") // the single player, seen from the conversation: which track it holds, // whether it runs, and where it stands. Rows draw their controls from // these; the float under the header is the same state, shown elsewhere. musicActiveChatId: musicState.chatId musicActiveSource: musicState.source musicTitle: musicState.title musicPerformer: musicState.performer musicPlaying: musicPlayer.playbackState === MediaPlayer.PlayingState musicPositionMs: musicPlayer.position musicDurationMs: musicPlayer.duration musicRepeatMode: root.musicRepeatMode musicQueueIndex: root.musicQueueIndex musicQueueSize: root.musicQueue.length // the room's information as the side panel: the window owns whether it // is out and how wide, the page only draws it. infoPanelRequested: root.roomInfoPanelOpen && root.currentIsRoom && !root.compact // the panel's own width, not the conversation list's: dragging either // column moves only the column that was dragged, and each is stored // under its own setting. infoPanelWidth: root.infoPanelColumnWidth() onAtBottomChanged: root.chatAtBottom = atBottom Component.onCompleted: root.chatAtBottom = atBottom // a video opens the player page over every column, with this one file // as the whole queue. onVideoRequested: (source) => root.showLayer(playerPageComponent, { incomingSource: source }) onMusicActivated: (chatId, source, title) => root.playMusic(chatId, source, title) onMusicSeek: (positionMs) => musicPlayer.position = positionMs onMusicStopRequested: root.stopMusic() onMusicSkipNext: root.musicSkip(1) onMusicSkipPrevious: root.musicSkip(-1) onMusicRepeatCycle: root.cycleMusicRepeat() onCallRequested: { if (!isSelfChat) root.startOutgoingCall(peerIp) } // the row goes in first and the datagram second, or there is nothing on // screen for the hourglass to sit on; markSent() turns it into a tick. onSendRequested: function(text, replyExcerpt, replyAuthor, replyId) { if (chatTransport.serverOwnsTimeline(peerIp)) { // no local row first: the server echoes the message with the // event id the room sees, and inventing a row duplicates it. if (replyId && replyId.length > 0) { // replyId is the Matrix event id; pass it directly. matrixRooms.sendReply(peerIp, replyId, text) } else if (chatTransport.transportName(peerIp) === "matrix") { // Send formatted when the composer typed markdown; the bridge // derives the HTML body, so plain text stays plain on the wire. matrixRooms.sendRichText(peerIp, text, "") } else { chatTransport.sendText(peerIp, text) } return } // the quote is stored with the message but not put on the wire: the // protocol has no reply field. const stamp = messagesModel.sendMessage(text, replyExcerpt, replyAuthor, replyId) if (stamp === 0) return if (root.isLanGroup(peerIp)) { networkManager.sendGroupMessage(peerIp, text, GroupManager.memberIps(peerIp)) messagesModel.markSent(stamp) return } // a refused send is not a sent one: the row keeps its hourglass. if (!isSelfChat && !chatTransport.sendText(peerIp, text)) return messagesModel.markSent(stamp) } onAttachRequested: function(localFilePath) { chatPage.reviewAttachments([localFilePath]) } onSpoilerRequested: function(text) { if (chatTransport.serverOwnsTimeline(peerIp)) { // A spoiler is a Matrix construct; other server-backed transports // fall back to plain text here, where the dialect is known. if (chatTransport.transportName(peerIp) === "matrix") matrixRooms.sendSpoiler(peerIp, text) else chatTransport.sendText(peerIp, text) return } // no reply field on the LAN wire; the spoiler rides as plain text. const stamp = messagesModel.sendMessage(text, "", "", "") if (stamp === 0) return if (root.isLanGroup(peerIp)) { networkManager.sendGroupMessage(peerIp, text, GroupManager.memberIps(peerIp)) messagesModel.markSent(stamp) return } if (!isSelfChat && !chatTransport.sendText(peerIp, text)) return messagesModel.markSent(stamp) } onLocationRequested: function(latitude, longitude, label) { if (!chatTransport.serverOwnsTimeline(peerIp)) { root.notify(i18nc("@info", "Locations can only be shared over a server-backed chat."), Kirigami.MessageType.Information) return } if (chatTransport.transportName(peerIp) === "matrix") { matrixRooms.sendLocation(peerIp, latitude, longitude, label) } else { root.notify(i18nc("@info", "This chat cannot share a location yet."), Kirigami.MessageType.Information) } } onVoiceCaptured: function(filePath, durationMs) { // A voice clip is an m.audio the bridge flags as an MSC3245 voice // message; the LAN side sends it as a plain attachment. if (chatTransport.serverOwnsTimeline(peerIp)) { if (chatTransport.transportName(peerIp) === "matrix") matrixRooms.sendVoice(peerIp, filePath, durationMs) else chatTransport.sendFile(peerIp, filePath) return } if (root.isLanGroup(peerIp)) { root.notify(i18nc("@info", "Sending files to LAN groups is not supported yet."), Kirigami.MessageType.Information) return } const stamp = messagesModel.sendFile(filePath, false) if (!isSelfChat && !chatTransport.sendFile(peerIp, filePath)) return messagesModel.markSent(stamp) } onStickerRequested: function(localFilePath) { if (chatTransport.serverOwnsTimeline(peerIp)) { if (chatTransport.transportName(peerIp) === "matrix") matrixRooms.sendStickerFile(peerIp, localFilePath) else chatTransport.sendFile(peerIp, localFilePath) return } if (root.isLanGroup(peerIp)) { root.notify(i18nc("@info", "Sending files to LAN groups is not supported yet."), Kirigami.MessageType.Information) return } const stamp = messagesModel.sendFile(localFilePath, root.looksLikeImage(localFilePath)) if (!isSelfChat && !chatTransport.sendFile(peerIp, localFilePath)) return messagesModel.markSent(stamp) } onPollRequested: function(question, answers) { // Polls are a Matrix construct; other server-backed transports cannot // carry one yet, so the writer is told rather than left with a blank. if (chatTransport.serverOwnsTimeline(peerIp) && chatTransport.transportName(peerIp) === "matrix") { matrixRooms.sendPoll(peerIp, question, answers, true) } else { root.notify(i18nc("@info", "Polls can only be sent over a Matrix chat."), Kirigami.MessageType.Information) } } onTypingNotice: { if (root.isLanGroup(peerIp)) return if (!isSelfChat && chatTransport.supportsTyping(peerIp)) chatTransport.sendTyping(peerIp) } onReadReached: root.markChatRead(peerIp) onAttachmentsReady: function(localPaths) { for (let i = 0; i < localPaths.length; ++i) root.sendOneFile(peerIp, localPaths[i]) } onProfileRequested: root.showLayer(otherProfileComponent, { peer: root.peerInfoFor(peerIp) }) onInfoRequested: root.togglePeerInfo() onInvitePeerRequested: (chatId) => { invitePeerDialog.groupId = chatId invitePeerDialog.open() } onInfoPanelCloseRequested: root.roomInfoPanelOpen = false onInfoPanelWidthRequested: (width) => root.setInfoPanelColumnWidth(width) onMemberActivated: (userId, anchorItem) => root.showRoomMemberCard(userId, anchorItem) onLeaveRequested: (chatId) => chatTransport.leaveChat(chatId) onVerifySessionsRequested: deviceVerificationDialog.openForSession() onEncryptionRequested: (chatId) => matrixRooms.enableEncryption(chatId) onPeerCardRequested: (anchorItem) => root.showPeerCard(peerIp, anchorItem) // the reader's own avatar: the account card, who this account is. The // saved-messages chat's card said only "write here", and a click on // one's own face is not a question about a conversation. onOwnProfileRequested: (anchorItem) => root.showAccountCard(anchorItem) onNewChatRequested: root.showLayer(newChatPageComponent) onNotifyRequested: (text) => root.notify(text, Kirigami.MessageType.Information) onForwardRequested: root.notify(i18nc("@info", "Forwarding messages is not implemented yet."), Kirigami.MessageType.Information) // the page already changed its copy; this only tells the peer, which // needs the address the window owns. onEditCommitted: (msgId, newText) => { if (!isSelfChat && chatTransport.supportsEdits(peerIp)) chatTransport.sendEdit(peerIp, msgId, newText) } onDeleteCommitted: (msgId) => { if (!isSelfChat && chatTransport.supportsEdits(peerIp)) chatTransport.sendDelete(peerIp, msgId) } } Component { id: peerInfoComponent PeerInfoPage { peer: root.currentPeerIp.length > 0 ? root.peerInfoFor(root.currentPeerIp) : null onProfileRequested: root.showLayer(otherProfileComponent, { peer: root.peerInfoFor(root.currentPeerIp) }) } } Component { id: roomInfoComponent RoomInfoPage { onMemberActivated: (userId, anchorItem) => root.showRoomMemberCard(userId, anchorItem) onLeaveRequested: (chatId) => chatTransport.leaveChat(chatId) onNotifyRequested: (text) => root.notify(text, Kirigami.MessageType.Information) onVerifySessionsRequested: deviceVerificationDialog.openForSession() onEncryptionRequested: (chatId) => matrixRooms.enableEncryption(chatId) } } Component { id: settingsPageComponent SettingsPage { onSaved: root.notify(i18nc("@info:status", "Settings saved"), Kirigami.MessageType.Positive) onMatrixAccountRequested: root.pageStack.layers.push(matrixLoginComponent) onTelegramAccountRequested: root.pageStack.layers.push(telegramLoginComponent) onWelcomeTourRequested: { root.pageStack.layers.pop() root.openWizard() } } } Component { id: telegramLoginComponent TelegramLoginPage {} } Component { id: matrixLoginComponent MatrixLoginPage { onVerifySessionsRequested: deviceVerificationDialog.openForSession() } } Component { id: invitationsPageComponent InvitationsPage { invites: invitesModel onInviteAccepted: (chatId) => matrixRooms.acceptInvite(chatId) onInviteDeclined: (chatId) => matrixRooms.declineInvite(chatId) } } NewRoomDialog { id: createRoomDialog onCreateRequested: (name, alias, isPrivate) => { matrixRooms.createRoom(name, "", alias, [], isPrivate) root.notify(i18nc("@info:status the room was asked for and appears when the server answers", "Creating %1...", name)) } } Component { id: browsePageComponent BrowsePage { onRoomJoinRequested: (address) => { matrixRooms.joinRoom(address) root.notify(i18nc("@info:status the join was asked for and completes when the server answers", "Joining %1...", address)) } onRoomOpenRequested: (chatId) => root.openChat(chatId) } } Component { id: playerPageComponent; PlayerPage {} } Component { id: otherProfileComponent; OtherProfile {} } Component { id: newChatPageComponent NewChatPage { peers: peersModel onChatRequested: (ip) => { root.pageStack.layers.pop() root.openChat(ip) } onRoomJoinRequested: (aliasOrId) => { root.pageStack.layers.pop() matrixRooms.joinRoom(aliasOrId) } onRoomCreateRequested: (name, topic, alias, invites, isPrivate) => { root.pageStack.layers.pop() // the page hands one comma-separated string; the homeserver // wants one entry per invite. const split = invites.split(",").map((s) => s.trim()).filter((s) => s.length > 0) matrixRooms.createRoom(name, topic, alias, split, isPrivate) } onDirectChatRequested: (userId) => { root.pageStack.layers.pop() matrixRooms.openDirectChat(userId) } } } // The first-run tour, in a window of its own. It asks for a Matrix sign-in // rather than doing one, and that is handed to the same handler the settings // page uses, so the tour does not carry a second copy of the login flow. Component { id: wizardComponent WizardWindow { // Closing the tour's window with its title bar button counts as // finishing it: the main window was waiting behind it and gets the // screen back. onClosing: (close) => { close.accepted = true root.closeWizard() } onFinished: root.closeWizard() onMatrixLoginRequested: { root.closeWizard() root.pageStack.layers.push(matrixLoginComponent) } } } }