Compare commits

..

364 Commits

Author SHA1 Message Date
Tobias Fella
c65183f93a More work 2023-06-14 20:16:05 +02:00
Tobias Fella
39ee17cfa1 ? 2023-06-13 23:32:57 +02:00
Tobias Fella
12bb75e5b0 Fix various problems 2023-06-13 16:28:19 +02:00
Tobias Fella
481f12337a Always start calls with camera disabled
Simplifies the code quite a bit
WIP: Renegotiate to enable camera
2023-06-13 15:45:30 +02:00
Tobias Fella
5e533b8e03 Implement voice & video calls 2023-06-13 15:45:30 +02:00
Tobias Fella
718060c757 Re-enable accidentally disabled encryption 2023-06-13 12:22:32 +00:00
l10n daemon script
4092cd8b6a GIT_SILENT Sync po/docbooks with svn 2023-06-13 01:56:15 +00:00
Tobias Fella
ea99c26556 Fix logging 2023-06-12 13:33:38 +02:00
Tobias Fella
7527fd47cd Fix compiler warning 2023-06-12 13:29:23 +02:00
l10n daemon script
c72c9c5cba GIT_SILENT Sync po/docbooks with svn 2023-06-12 02:16:05 +00:00
Volker Krause
09ded20409 Fix location map asset check 2023-06-11 10:26:41 +02:00
l10n daemon script
0fd3de6215 GIT_SILENT Sync po/docbooks with svn 2023-06-11 01:56:11 +00:00
Tobias Fella
1de160cb19 Fix the search page
The search model needed to adapted to the changes in messageeventmodel
2023-06-10 13:57:03 +00:00
l10n daemon script
921abac3c1 GIT_SILENT Sync po/docbooks with svn 2023-06-10 01:54:53 +00:00
Volker Krause
7c75a2fd06 Create the OSM QtLocation plugin only once
Just loading that plugin already triggers an HTTP request, so lets only
do that when really needed and even more importantly, not for every single
location delegate again.
2023-06-09 18:39:38 +02:00
James Graham
105be518c7 Further improvements to the ChatBox API
Further improvements to the ChatBox API so that outside components no longer access the ChatBar item directly.
2023-06-09 15:02:42 +00:00
l10n daemon script
9425f24315 GIT_SILENT Sync po/docbooks with svn 2023-06-09 01:58:12 +00:00
Tobias Fella
47c28ce9a2 Improve QML types 2023-06-08 20:26:34 +00:00
Tobias Fella
72c85af407 Implement creating spaces 2023-06-08 20:05:53 +00:00
Volker Krause
22694fe5e4 Handle invalid model indices gracefully
data() being called with an invalid model index seems to happen during
normal operations here, with something in the proxy model chain not
catching that case (due to a row being filtered out presumably?).
2023-06-08 19:54:08 +00:00
Tobias Fella
a02232dc19 Fix custom emojis being visible in the sticker selector 2023-06-08 19:43:52 +00:00
Tobias Fella
252e099e75 Fix renaming log files > 10 2023-06-08 21:32:39 +02:00
Tobias Fella
76a697c3f6 Fix another invalid index 2023-06-08 21:23:38 +02:00
Joshua Goins
5b23593fd2 Let accounts without the emoticon account data to create emojis/stickers
This check worked for accounts that already had custom emojis, but if it
never had any added, m_images was never filled and the model would crash
when adding more.
2023-06-08 19:18:04 +00:00
Joshua Goins
c2580c1d2d Use correct placeholder message when there's no stickers
Instead of saying "No emojis" which doesn't make sense on the sticker
page.
2023-06-08 14:43:11 -04:00
Tobias Fella
3303d2c7db Keep last 50 log files
Keeping just the last two probably leads to important info being lost.
2023-06-08 17:55:45 +00:00
Tobias Fella
22107fc598 Don't try getting data for invalid indices
BUG: 470639
2023-06-08 17:55:13 +00:00
Tobias Fella
bc4c4f8519 Refactor login
BUG: 469486
2023-06-08 17:29:09 +00:00
l10n daemon script
16c63dbe93 GIT_SILENT Sync po/docbooks with svn 2023-06-08 01:56:11 +00:00
Volker Krause
9e78ab3328 Fix location markers not being shown on the map 2023-06-07 17:30:06 +02:00
l10n daemon script
e6dc1f54b3 GIT_SILENT Sync po/docbooks with svn 2023-06-07 02:00:09 +00:00
Tobias Fella
09025fa16d Remove some useless checks 2023-06-06 20:47:39 +02:00
l10n daemon script
357b148944 GIT_SILENT Sync po/docbooks with svn 2023-06-06 01:52:45 +00:00
Tobias Fella
8b71e56a5f Remove unneeded fallback 2023-06-05 21:41:13 +02:00
Tobias Fella
f5aa5ac7f4 Remove unneeded fallback for user's display name
The display name falls back to the user id internally.
2023-06-05 21:38:48 +02:00
James Graham
075d2fda4d Small chatbox api improvement
Small improvement to the chatbox api by making currentRoom explicit and removing redundant properties.
2023-06-05 18:20:12 +00:00
James Graham
b5c781212c Improve the handling of notifications
The aim is to put some additional filtering in place to better stop floods of old notifications. This is achieved with a couple of new filters and better tracking of old notifications.

- Make sure to paginate through all notification on initialization to ensure they are all added to old notifications. While we were not previously putting a limit on the number of returned notifications the server can and will do this when there are a very large amount.
- Find the newest timestamp for each connection on initialization and don't post any notifications with an earlier timestamp.
- Track old notifications on a per-connection basis.

Closes network/neochat#358 and network/neochat#423
2023-06-05 16:42:01 +00:00
l10n daemon script
af136943c3 GIT_SILENT Sync po/docbooks with svn 2023-06-05 01:48:05 +00:00
Tobias Fella
b2a29c8d45 Mark parameter as unused 2023-06-04 22:31:18 +02:00
Tobias Fella
5d16d78914 Minor cleanup in Controller::createRoom 2023-06-04 08:51:29 +00:00
Tobias Fella
94e970e15a Disable Windows Qt6 CI temporarily 2023-06-04 10:29:53 +02:00
Tobias Fella
1f4b984664 Unify emoji and sticker settings pages 2023-06-04 08:11:36 +00:00
l10n daemon script
a2a27e78d1 GIT_SILENT Sync po/docbooks with svn 2023-06-04 01:57:07 +00:00
l10n daemon script
915a5c188f GIT_SILENT made messages (after extraction) 2023-06-04 00:47:06 +00:00
Heiko Becker
e8f0420ad5 GIT_SILENT Update Appstream for new release
(cherry picked from commit 8dcc231bdc)
2023-06-02 22:05:12 +02:00
l10n daemon script
7a01b3ea28 GIT_SILENT Sync po/docbooks with svn 2023-06-01 01:55:18 +00:00
l10n daemon script
7cff2aaa97 SVN_SILENT made messages (.desktop file) - always resolve ours
In case of conflict in i18n, keep the version of the branch "ours"
To resolve a particular conflict, "git checkout --ours path/to/file.desktop"
2023-06-01 01:40:43 +00:00
l10n daemon script
9588c7d8ef GIT_SILENT made messages (after extraction) 2023-06-01 00:47:06 +00:00
James Graham
d5a6c7683e Fix missing end of comment block. 2023-05-31 17:13:18 +01:00
l10n daemon script
1de4e2ecd3 GIT_SILENT Sync po/docbooks with svn 2023-05-31 02:29:02 +00:00
James Graham
fa37f28c94 Improve Delegate Width Sizing
Create a cpp helper class to calculate the correct delegate width given it's parent width.

This is designed to be more robust and hopefully easier to understand than the current mass of javascript calcs.

BUG: 470167
2023-05-30 18:14:25 +00:00
Tobias Fella
f1be509d13 Fix loading 2023-05-30 17:14:33 +02:00
l10n daemon script
fed528c6d8 GIT_SILENT Sync po/docbooks with svn 2023-05-30 02:12:13 +00:00
James Graham
d09cd5d71b Cleanup the list of required properties for MessageDelegateContextMenu 2023-05-29 15:03:34 +00:00
James Graham
4e40f5c7d9 getUser UserDetailDialog
Use `NeoChatRoom::getUser` to provide the user properties in `UserDetailDialog`
2023-05-29 13:43:24 +00:00
l10n daemon script
3b5bb06b4a GIT_SILENT Sync po/docbooks with svn 2023-05-29 01:51:45 +00:00
Tobias Fella
8f4e5a41c5 Drop reset*Count invocations
Still coming from Spectral, where they were taken from Quaternion, where they were dropped because they don't work as expected.
Also, soon to be removed from libQuotient itself.
2023-05-28 10:24:21 +00:00
l10n daemon script
9b1005efc3 GIT_SILENT Sync po/docbooks with svn 2023-05-28 01:59:58 +00:00
James Graham
e1d4b66479 Unify getUser
Always use `NeoChatRoom::getUser` for getting user details in a room context.
- `MessageEventModel` now calls `getUser`
- `getUser` is now overloaded to also be able to take a `NeoChatUser*`
- add params to `getUser` that are needed for the model outputs
2023-05-27 18:27:28 +00:00
Tobias Fella
f2aa375b43 Rename AccountStickerModel to AccountEmoticonModel
In preparation for using it for custom emojis as well
2023-05-27 16:38:25 +00:00
James Graham
ee53793a6d Fix replying and editing from chatbox
Restore the functionality to edit or reply to the last message in the `chatbar`.

This is achieved be moving the functions `getLastLocalUserMessageEventId` and `getLatestMessageFromRow` to `NeoChatRoom` as `editLastMessage` and `replyLastMessage` as `chatbar` no longer has access to `messageEventModel`.

The functions are also simplified as they only need to find the `eventId` and always from row 0 as this was the only use of the functions.

BUG: 469733
2023-05-27 16:36:09 +00:00
James Graham
528d46be9f Fix the room timeline being dragged when selecting text by making it non...
Fix the room timeline being dragged when selecting text by making it non interactive in desktop mode.

BUG: 467163
2023-05-27 16:06:20 +00:00
Joshua Goins
cc80e69644 Add better checks when the pack is omitted from im.ponies.room_emotes
This field is omittable, and I hit it this morning. Let's check if it's
filled before using it.
2023-05-27 15:33:42 +00:00
James Graham
09ced090f2 Use replyId role for reply ID 2023-05-27 16:12:21 +01:00
James Graham
8ad23e7a40 Timeline required properties
Move to using required properties for timeline delegates.
2023-05-27 14:57:34 +00:00
Tobias Fella
a94f46f904 Fix build against libQuotient 0.8 2023-05-27 13:17:02 +00:00
l10n daemon script
41a5d2557e GIT_SILENT Sync po/docbooks with svn 2023-05-27 01:50:19 +00:00
l10n daemon script
0b36db0ecc GIT_SILENT made messages (after extraction) 2023-05-27 00:47:24 +00:00
Shubham Arora
aae5519bed NeochatMaximizeComponent.qml: Add sourceWidth and sourceHeight
Depends on: https://invent.kde.org/libraries/kirigami-addons/-/merge_requests/103
2023-05-23 16:41:14 +00:00
l10n daemon script
df849accfa GIT_SILENT Sync po/docbooks with svn 2023-05-23 02:31:17 +00:00
l10n daemon script
b098937d1b GIT_SILENT Sync po/docbooks with svn 2023-05-22 01:52:21 +00:00
l10n daemon script
fbe4fc49e1 GIT_SILENT made messages (after extraction) 2023-05-22 00:47:42 +00:00
James Graham
8741fd8fed Refactor hover actions
Refactor hover actions into their own component.
2023-05-21 15:36:43 +00:00
l10n daemon script
ccc952b65e GIT_SILENT Sync po/docbooks with svn 2023-05-21 01:50:51 +00:00
Tobias Fella
6a68375b10 Rename NameRole to DisplayNameRole in UserListModel 2023-05-20 20:03:08 +00:00
Tobias Fella
4dcb19edb7 Fix avatar source warning 2023-05-20 19:47:12 +00:00
Tobias Fella
838abc9af3 Fix binding loop in GroupChatDrawerHeader 2023-05-20 19:29:35 +00:00
Tobias Fella
7283b2dd4d Use NavigationTabButtons for Emoji and sticker categories 2023-05-20 17:03:56 +00:00
Tobias Fella
2c1f00da03 Temporarily disable android qt6 CI 2023-05-20 17:03:33 +00:00
Carl Schwan
c7caec894e Assert that index is valid 2023-05-20 17:03:33 +00:00
Tobias Fella
b254b4aa9b Use KFormat for formatting dates 2023-05-20 17:03:33 +00:00
Tobias Fella
67107959e4 Remove unneeded "using namespace Quotient" 2023-05-20 17:03:33 +00:00
Tobias Fella
26d3e16e6d Remove empty destructor 2023-05-20 17:03:33 +00:00
Tobias Fella
bb8ee4ef44 Remove unneeded qml type registrations 2023-05-20 17:03:33 +00:00
Tobias Fella
ee65ad22e6 Rename LongOperationRole to ProgressInfoRole 2023-05-20 17:03:33 +00:00
Tobias Fella
b823f2c6b9 Remove unused role 2023-05-20 17:03:33 +00:00
l10n daemon script
0901c59de9 GIT_SILENT Sync po/docbooks with svn 2023-05-20 01:52:01 +00:00
Nate Graham
69bfa1394c Focus message search window's search field by default
BUG: 469879
2023-05-19 13:16:21 +00:00
l10n daemon script
5b69a3e07c GIT_SILENT Sync po/docbooks with svn 2023-05-19 01:49:45 +00:00
James Graham
37220ab872 Fix notification state in new rooms
Make sure that the `updateNotificationState` function is called when the base state is loaded so that new rooms after startup have a valid notification state.

Fixes network/neochat#583
2023-05-18 19:23:31 +00:00
l10n daemon script
9dd7ceb966 GIT_SILENT Sync po/docbooks with svn 2023-05-18 01:50:45 +00:00
Tobias Fella
ae6056615d Add missing capture 2023-05-18 00:03:07 +02:00
Tobias Fella
d74253d149 Update copyright year 2023-05-17 23:50:57 +02:00
Tobias Fella
805332c599 Don't use implicit lambda captures 2023-05-17 23:49:56 +02:00
Tobias Fella
e42c1c1f69 Use NavigationTabBar for emoji/sticker picker 2023-05-17 14:02:03 +00:00
Tobias Fella
f7881d0661 Fix spacedrawer being visible when there are no spaces
We can't (easily) make this declarative, since there are no spaces on startup, causing the loader to be disabled,
making the repeater not load anything, which means the loader stays disabled.
We should figure out a better solution, since this means that the drawer doesn't open immediately when joining a space,
but for now this fix is better then the current bug.
2023-05-17 15:38:10 +02:00
Carl Schwan
5eb86bbc88 Add neochat mastodon account 2023-05-17 11:30:17 +02:00
l10n daemon script
53dc32fac1 GIT_SILENT Sync po/docbooks with svn 2023-05-17 01:51:56 +00:00
James Graham
a5a2c0b03e Reaction Model
Create a reaction model that provides all the required data for `ReactionDelegate` so that none need to be calculated in QML.

This also cleans up the API for `ReactionDelegate`
2023-05-16 16:44:02 +00:00
Tobias Fella
4d2e64cb80 Cleanup name handling in RoomListModel
Replace NameRole with DisplayNameRole entirely.
2023-05-16 16:38:53 +02:00
Tobias Fella
dee064a758 Fix crash in room switching 2023-05-16 14:37:07 +00:00
Tobias Fella
5bdd67dcc1 Fix background color of TypingPane 2023-05-16 14:36:37 +00:00
Tobias Fella
2ff92bea70 Fix warning for empty avatar source 2023-05-16 14:11:38 +00:00
l10n daemon script
0fbb070bf2 GIT_SILENT Sync po/docbooks with svn 2023-05-16 01:57:02 +00:00
l10n daemon script
1a1c7ef23e GIT_SILENT made messages (after extraction) 2023-05-16 00:47:11 +00:00
Tobias Fella
fabd3da5a7 Fix asan runtime error in texthandler 2023-05-15 23:36:25 +00:00
Tobias Fella
6f90d33f3a Add new messages to bottom of notifications list 2023-05-15 19:49:05 +00:00
Aleix Pol
3bb0ee17cd NotificationsManager: Group notifications per room
Instead of issuing a new notification for every message, bundle them by
room.
It looks like the code was originally designed to do that and somehow we
forgot along the way.
It also fixes the leaking in m_notifications as we were never cleaning
after it.
2023-05-15 19:49:05 +00:00
Tobias Fella
fa8164cdba Fix notifications showing up repeatedly when multiple logged-in accounts are in the same room
What happens is roughly: The notification is received in one account and marked as received locally.
In the other account, the event is marked as "read" in the json, which makes us delete it from the
received messages. Then it is received on the first account...
2023-05-15 21:28:08 +02:00
James Graham
c63f1f0452 Cache last event
Cache the last room event so that the room list can be sorted on startup

Fixes network/neochat#88 \
BUG: 455042
2023-05-15 19:11:44 +00:00
l10n daemon script
e0df447998 GIT_SILENT Sync po/docbooks with svn 2023-05-15 01:50:59 +00:00
l10n daemon script
a64d4d0989 GIT_SILENT made messages (after extraction) 2023-05-15 00:47:14 +00:00
Tobias Fella
4c575f18d1 Fix avatar name 2023-05-14 23:57:32 +02:00
Tobias Fella
b629961a70 Create account sticker editor 2023-05-14 20:33:51 +00:00
l10n daemon script
571d9780b1 GIT_SILENT Sync po/docbooks with svn 2023-05-14 02:06:27 +00:00
l10n daemon script
df2ed04f16 GIT_SILENT made messages (after extraction) 2023-05-14 00:48:05 +00:00
Akseli Lahtinen
3d687a283e Add more bottom margin
Adds more bottom margin so the Now Typing box wont cover the text

BUG: 469616
2023-05-13 17:21:31 +00:00
l10n daemon script
99479b3896 GIT_SILENT Sync po/docbooks with svn 2023-05-13 01:51:06 +00:00
James Graham
7fca14bce1 Fix Chatbar text margin
Make sure that the padding in the chatbar textarea accounts for the x offset
2023-05-12 17:13:40 +00:00
Tobias Fella
afb51497cd Fix autocompletion not working
BUG: 468967
2023-05-12 17:12:28 +00:00
James Graham
88fada89ea Limit the maximum number of avatars shown
Limit the maximum number of avatars shown for other user read markers and collapsed state events

For state events \
![image](/uploads/0d3ec7c3da02a8832dfdb18dc265db92/image.png)

For read markers \
![image](/uploads/5694f14927e5c10b2159e58445c8a0a3/image.png)
2023-05-12 15:54:15 +00:00
James Graham
023c51ac62 Fix QuickSwitcher notification count
Use `notificationcount` instead of unread count in the `quickswitcher` as unread count is removed
2023-05-12 14:09:02 +00:00
Luigi Toscano
c37fa92559 Readd some text removed by the translation system
Restore part of the contents previously introduced by
cc21f8cca9 which was partially
lost, probably due to an extra '>' outside the tags
which confused the translation system.

Credits for the text, see the original commit (Carl Schwan).
2023-05-12 12:44:24 +02:00
l10n daemon script
9dabb890dc GIT_SILENT Sync po/docbooks with svn 2023-05-12 01:55:21 +00:00
l10n daemon script
e40c3b4c03 GIT_SILENT made messages (after extraction) 2023-05-12 00:48:20 +00:00
l10n daemon script
5be7105bb8 GIT_SILENT Sync po/docbooks with svn 2023-05-11 01:50:00 +00:00
l10n daemon script
8dc9541d95 GIT_SILENT made messages (after extraction) 2023-05-11 00:46:56 +00:00
James Graham
6e5b71888d Refresh all reply roles on loadReply
Make sure that all reply roles that depend on a pointer to the reply event being available are refreshed.
2023-05-10 16:41:22 +00:00
James Graham
b362365609 Remove Unread Count
Unread count is deprecated and notification count should be used in all cases. As such remove unreadCount and use notification count in all places it was being used.

Fixes network/neochat#76 \
BUG: 466515
2023-05-10 16:23:14 +00:00
l10n daemon script
1db2e4a333 GIT_SILENT Sync po/docbooks with svn 2023-05-10 01:52:11 +00:00
l10n daemon script
6e8e40c22f GIT_SILENT made messages (after extraction) 2023-05-10 00:47:12 +00:00
Carl Schwan
cc21f8cca9 Update appstream description 2023-05-09 19:32:52 +00:00
Tobias Fella
b545a27bc6 Fix ReplyComponent warnings 2023-05-09 13:22:41 +02:00
Tobias Fella
c9d863335e Disable various tests and examples in the flatpak manifest 2023-05-09 11:14:12 +00:00
Tobias Fella
334e3ac6b4 Delete old space components 2023-05-09 09:57:08 +00:00
James Graham
d424aba0bc Document imagepacksmodel 2023-05-09 09:55:36 +00:00
James Graham
8802753de1 Custom emoji image data
Make sure the imageInfo for custom emojis is set. This ensures that all the data required by imageDelegate is available.
2023-05-09 09:15:07 +00:00
James Graham
40edfef046 Document stickermodel 2023-05-09 08:14:21 +00:00
Tobias Fella
11343e6bdf Improve spaces support 2023-05-09 08:11:47 +00:00
l10n daemon script
30c7d86045 GIT_SILENT Sync po/docbooks with svn 2023-05-09 01:57:26 +00:00
James Graham
58b7b46828 Update README.md
Update README.md ensuring that info is up to date.

The following has been changed:
- Updated about info (intro, features)
- Reference KDE standard docs for building, MRs, etc
2023-05-08 14:16:43 +00:00
James Graham
3d0c0e3ed5 Move stickermodel into the models folder 2023-05-08 09:40:26 +01:00
James Graham
77d8ec04ca Document imagepackevent 2023-05-08 08:34:32 +00:00
James Graham
72de7c6cfb Link preview messageeventmodel parameters
This move the finding of links and the creation of a `linkpreviewer` into c++.

- The links are now extracted from the text in `texthandler`
- The `messageeventmodel` now creates and stores `linkpreviewers` for events that have links in the current room.

Two new model roles have been created to let a text delegate know when the link preview should be shown (`showLinkPreview`) and pass the link previewer (`linkPreviewer`). Empty link previewer are returned where link don't exist so the qml doesn't have to have checks for whether the parameters are undefined.
2023-05-08 08:18:49 +00:00
James Graham
b82d3ab5ad TempInfo Messageeventmodel
Further improvements to the handling of `mediaInfo` in `messageeventmodel`.

`blurhash` and `thumbnailInfo` are now replaced with a single `tempInfo` object that contains a single temp source. The priority is thumbnail > `blurhash` > empty if none exist.

Fixes network/neochat#235
2023-05-08 07:50:20 +00:00
l10n daemon script
20443ba59f GIT_SILENT Sync po/docbooks with svn 2023-05-08 01:54:02 +00:00
Tobias Fella
bfdca9ca9e Fix regressions from RoomPage refactoring
Fixes 581

BUG: 469427
BUG: 469425
2023-05-07 16:17:28 +00:00
Tobias Fella
a12a44b722 Fix crash in media url 2023-05-07 15:36:59 +00:00
James Graham
8d45d4404e Move imagepacksmodel to the models folder 2023-05-07 15:11:08 +00:00
Tobias Fella
42ca128d7f Fix linking against Qt6 libQuotient 2023-05-07 15:10:32 +00:00
l10n daemon script
7cd8e70d55 GIT_SILENT Sync po/docbooks with svn 2023-05-07 01:59:27 +00:00
Tobias Fella
2982d2526a Remove logging statement
Turns out this happens a lot
2023-05-06 22:27:16 +02:00
Tobias Fella
d33a0c6644 Fix another imagepack crash 2023-05-06 20:22:27 +00:00
Tobias Fella
4a29e0d0e1 Add categorized logging to MessageEventModel 2023-05-06 17:53:01 +02:00
Tobias Fella
a89e04b92f Fix merge 2023-05-06 17:28:46 +02:00
James Graham
4b993775c6 Move Neochat specific libQuotient events to their own folder 2023-05-06 15:10:17 +00:00
Tobias Fella
e0983fcc8c Refactor RoomPage into various component 2023-05-06 15:09:00 +00:00
Tobias Fella
c9ddf2f04a Fix crash when there are no account emojis 2023-05-06 15:31:20 +02:00
Heiko Becker
b5764c4d04 GIT_SILENT Update Appstream for new release
(cherry picked from commit 41ce874f77)
2023-05-06 11:19:38 +02:00
James Graham
5f41d275e4 Document runner 2023-05-06 08:22:09 +00:00
l10n daemon script
7f707ae042 GIT_SILENT Sync po/docbooks with svn 2023-05-06 01:55:01 +00:00
James Graham
270a1e3a96 Fix room notifications settings
Make sure that the room property is set for the Push Notification room settings page.
2023-05-05 17:12:33 +00:00
James Graham
65d919876c Document trayicon_sni 2023-05-05 16:53:38 +00:00
Tobias Fella
049ae3602f Fix binding loop in ChatBar 2023-05-05 16:03:50 +00:00
Tobias Fella
d4c8e558e0 Remove empty settings pages 2023-05-05 17:42:45 +02:00
James Graham
0e4d87824e Document windowcontroller 2023-05-05 15:23:18 +00:00
James Graham
cd7f6d52dd document urlhelper 2023-05-05 14:38:48 +00:00
Tobias Fella
96c1b98d02 Implement sending stickers
MSC2545 image packs are used as source.
2023-05-05 14:29:18 +00:00
Tobias Fella
443d709eb8 Save log to file and always save e2ee debug logs
This will hopefully help us debug e2ee problems
2023-05-05 10:15:43 +00:00
James Graham
5107f0e79e document joinruleevent 2023-05-05 07:45:52 +00:00
James Graham
5567f94535 Document filetransferpseudojob 2023-05-05 07:45:05 +00:00
l10n daemon script
8e566e7326 GIT_SILENT Sync po/docbooks with svn 2023-05-05 01:59:44 +00:00
l10n daemon script
43c6172482 GIT_SILENT Sync po/docbooks with svn 2023-05-04 02:00:18 +00:00
James Graham
f453334f63 Document trayicon 2023-05-03 19:58:47 +00:00
James Graham
ac24e06ae2 Document spacehierarchycache 2023-05-03 19:58:27 +00:00
James Graham
eab5abec2f Document roommanager 2023-05-03 18:49:20 +00:00
James Graham
0fc962b147 Document stickerevent 2023-05-03 17:51:36 +00:00
James Graham
10794628ed MessageEventModel media info improvements
Create a `messageeventmodel` role for media info and reply media info that is a QMap with all the required data.

This replaces the MediaUrlRole, FileMimeTypeRole and the ContentTypeRole. The reply role no longer needs the content role.

This also ensures mxc urls are now generated for replies. All the media parameters will now have default values assigned in the model so the QML no longer needs to do this.
2023-05-03 17:50:48 +00:00
l10n daemon script
a6f108d3b8 GIT_SILENT Sync po/docbooks with svn 2023-05-03 02:02:58 +00:00
James Graham
c4e80c1d1c Document pollevent 2023-05-02 18:39:08 +00:00
James Graham
6f231fa916 Document pollhandler 2023-05-02 18:10:49 +00:00
l10n daemon script
5d5f5c4ab7 GIT_SILENT Sync po/docbooks with svn 2023-05-02 02:02:48 +00:00
Gary Wang
034453636d Use MobileForm.FormSpinBoxDelegate for SpinBox in proxy page 2023-05-01 10:00:41 +00:00
Tobias Fella
8e4da42a64 Fix crash in avatar url handling 2023-05-01 11:49:35 +02:00
James Graham
7156bf0711 Link Previewer MXC Links
- Update link preview to get valid mxc links.
- Get the connection from a room.
2023-05-01 09:12:16 +00:00
l10n daemon script
bc317514e6 GIT_SILENT Sync po/docbooks with svn 2023-05-01 02:14:22 +00:00
James Graham
26b2380bb7 Document linkpreviewer 2023-04-30 20:09:35 +00:00
James Graham
685b2a68ba Document notificationsmanager 2023-04-30 19:49:21 +00:00
James Graham
9936c7a8b6 Document login 2023-04-30 19:33:17 +00:00
James Graham
83da52582b Document matriximageprovider 2023-04-30 19:13:13 +00:00
James Graham
fbf918c7d0 Document neochatuser 2023-04-30 18:55:59 +01:00
James Graham
2281fe6f8a Improve User Avatar Model Roles
- Update the message event and user models so that the full source url is output.
- Separate the reply author into its own role
- Create an empty user object that can be passed so that the QML code no longer needs to check if certain parameters exist.
- Make avatarForMember return and empty QUrl if a valid avatar cannot be found and make use in the user and event models

As well as cleaning up the QML this should also stop the QML Image: Media id '' doesn't follow server/mediaId pattern spam in the log.
2023-04-30 13:51:06 +00:00
l10n daemon script
1bb03e115e GIT_SILENT Sync po/docbooks with svn 2023-04-30 02:48:26 +00:00
Tobias Fella
9d6ebf53a9 Fix reply loading 2023-04-29 21:39:16 +02:00
Tobias Fella
9e780b8eb2 Remove warning when event to refresh wasn't found
This can legitimitely happen, e.g. when a reaction is loaded for an event that we haven't loaded
2023-04-29 21:28:32 +02:00
Tobias Fella
01b34c5b8c Get rid of some warnings 2023-04-29 20:56:53 +02:00
Tobias Fella
11233bee3a Fix trayicon disconnect warning 2023-04-29 20:10:11 +02:00
Tobias Fella
e94b3caf51 Run tests guiless 2023-04-29 19:48:57 +02:00
James Graham
e8166f3433 Improve Invitation Flow
- Update the conatainsUser function to use memberState so that invites do not show up as being in the leave state.
- Update the InviteUser page to use Kirigami.BasicListItem and make the invite button remain visible but be untoggleable when the if user has already been invited.

closes network/neochat#202
2023-04-29 17:13:24 +00:00
Tobias Fella
d844945453 Improve RoomDrawer for direct chats
Don't show irrelevant stuff like the member list, description, alias

BUG: 466895
2023-04-29 18:39:40 +02:00
James Graham
85b40ca536 Devtools Improvements
- Now has tabs setup as more features are added
- First extra tab has basic server info
- Use mobileform to make it look nicer
- For the room data tab allow the room to be changed from within devtools
- For the room data tab allow m.room.member events to be filtered out so other event types can be found easily
- For the room data tab allow viewing room account data

network/neochat#557
2023-04-29 15:20:51 +00:00
James Graham
ca805917de Document and Cleanup userlistmodel
Document and cleanup userlist model.

- Remove unneeded enum UserTypes
- Cleanup includes and remove need to include QPointer
- make clear that it is a user or users that are being refreshed

Note: breaks libquotient 0.6 compatibility because of the changes to how m_currentRoom is handled
2023-04-29 14:53:01 +00:00
Tobias Fella
014185c4c9 Prevent crash in SyntaxHighlighter when leaving room
BUG: 467722
2023-04-28 14:14:02 +00:00
Tobias Fella
2b06679be6 Fix handling line separators
BUG: 468977
2023-04-28 13:47:25 +00:00
Tobias Fella
7d2edc7c52 Fix Ctrl+Shift+, opening settings
BUG: 469057
2023-04-28 12:47:53 +00:00
Nicolas Fella
224bc9441b Add 23.04.0 Windows artifact 2023-04-28 12:45:27 +02:00
l10n daemon script
5a7b17a31e GIT_SILENT Sync po/docbooks with svn 2023-04-28 01:54:31 +00:00
Tobias Fella
eea8950afb Fix room search field shortcut
The shortcut was stolen by the search field in the quick switcher

BUG: 469059
2023-04-28 01:03:24 +02:00
James Graham
9f15c7fc53 Fix messageeventmodel message role
Change remaining messageeventmodel message role to plainText
2023-04-27 17:38:42 +00:00
James Graham
4b879be4ea MessageEventModel plain text role
Update the message role to be named plainText and use it the message delegate for openMessageContext.
This removes the need for plainText in controller so it is removed.
2023-04-27 16:58:52 +00:00
James Graham
af078f03d0 Document filetypesingleton 2023-04-27 15:20:36 +00:00
Tobias Fella
cdf2c390ca Don't abandon job when image request is cancelled
Aborting the request causes a lot of logged messages. In theory, not stopping the job causes some overhead,
but that's negligible and the provider is on its way out anyway.
2023-04-27 11:32:46 +00:00
l10n daemon script
77b2186cb6 GIT_SILENT Sync po/docbooks with svn 2023-04-27 01:58:08 +00:00
James Graham
0664ef8ccb Document controller
Document controller and cleanup some unused functions
2023-04-26 19:56:56 +00:00
James Graham
4af7537764 Cleanup Controller
Remove unused functions and use setQuitOnLastWindowClosed as a slot for reacting to the tray icon setting change only.
2023-04-26 19:29:16 +00:00
l10n daemon script
f47e7531fc GIT_SILENT Sync po/docbooks with svn 2023-04-26 02:00:56 +00:00
Tobias Fella
e484a08e8d Fix Keys in QuickSwitcher 2023-04-25 14:54:09 +02:00
l10n daemon script
56f3d0e0d6 GIT_SILENT Sync po/docbooks with svn 2023-04-25 02:08:27 +00:00
l10n daemon script
3797854b0c GIT_SILENT Sync po/docbooks with svn 2023-04-24 02:14:01 +00:00
James Graham
931e91ddba Document emojitones 2023-04-23 18:36:50 +00:00
James Graham
25754bbe22 Document colorschemer 2023-04-23 12:44:52 +00:00
James Graham
53884949d1 Document chatdocumenthandler
Document chatdocumenthandler and cleanup includes
2023-04-23 11:12:29 +00:00
James Graham
abb2a340e2 Document blurhash
Add documentation from the blurhash reference implementation to the code.
2023-04-23 09:56:36 +00:00
James Graham
ed874ed00a Document clipboard 2023-04-23 08:24:09 +00:00
l10n daemon script
a8aec35884 GIT_SILENT Sync po/docbooks with svn 2023-04-23 02:42:19 +00:00
James Graham
0496f6552a Document blurhashimageprovider 2023-04-22 18:50:34 +00:00
James Graham
970cd5cf7a Document actionshandler
Also cleanup some unused includes
2023-04-22 18:50:17 +00:00
Carl Schwan
2fb4fdd18f Port SpellChecking setting page to mobileform 2023-04-22 11:20:37 +00:00
Carl Schwan
fc1dc5c1d6 Bump dependency to kirigami
We need the new settings action api
2023-04-22 09:49:59 +00:00
James Graham
800194c6f5 Document userdirectorylistmodel 2023-04-22 08:34:22 +00:00
James Graham
0cab7b1c85 Document webshortcutmodel 2023-04-22 08:33:12 +00:00
James Graham
983d4c9db2 Document sortfilterspacelistmodel 2023-04-22 08:32:19 +00:00
James Graham
88dfacbbb3 Document sortfilterroomlistmodel 2023-04-22 08:31:54 +00:00
James Graham
3f572c79fa Document statemodel 2023-04-22 08:31:28 +00:00
l10n daemon script
a7ee1fac3c GIT_SILENT Sync po/docbooks with svn 2023-04-22 02:08:02 +00:00
l10n daemon script
068bfc948b GIT_SILENT Sync po/docbooks with svn 2023-04-21 01:58:19 +00:00
l10n daemon script
47470f5a6d GIT_SILENT Sync po/docbooks with svn 2023-04-20 02:05:22 +00:00
James Graham
144dc1f8f4 Use kirigami-addons maximise components
Use new kirigami-addons MaximizeImage.qml to replace local FullScreenImage.qml

depends upon libraries/kirigami-addons!88

TODO
- [x] Remove the old `fullscreenimage.qml` before merging as no longer needed

Implements #571
2023-04-19 21:10:30 +00:00
Tobias Fella
4002bb804c Don't require passing tests on windows Qt6 2023-04-19 21:53:28 +02:00
Carl Schwan
760ed24b37 Add loading title to LoadingPage
Otherwise the page is a bit empty
2023-04-19 07:39:49 +00:00
Carl Schwan
489979af43 Fix Ctrl-PageUp/Down navigation 2023-04-19 07:39:23 +00:00
l10n daemon script
e482e12826 GIT_SILENT Sync po/docbooks with svn 2023-04-19 02:03:35 +00:00
Tobias Fella
fa7b9d54e2 Fix logout from account menu 2023-04-18 13:04:25 +00:00
Tobias Fella
f60114c7f6 Refactor account labels
Move them out of NeoChatUser, where they don't make any sense
2023-04-18 08:29:24 +00:00
l10n daemon script
de55253e54 GIT_SILENT Sync po/docbooks with svn 2023-04-18 01:58:53 +00:00
Shooting Star
8479e51051 Check if room is null before enter room
There will be some case, like the notify is still exist, but user have
logout their account, user leave the room, these cause the room become a
nullptr, and when click the notify message, it make neochat coredump
2023-04-17 19:25:53 +00:00
Tobias Fella
bb2fd7c9c4 Fix dialog button role 2023-04-17 19:34:43 +02:00
Nicolas Fella
a0b0a5d47f Set associated window for tray icon 2023-04-17 09:46:04 +00:00
l10n daemon script
10bdc1d3d1 GIT_SILENT Sync po/docbooks with svn 2023-04-17 02:41:30 +00:00
James Graham
6ec7d8d6b4 Use DelegateTypeRole searchmodel
Change EventTypeRole to DelegateTypeRole to match updated message event model.
2023-04-16 08:32:51 +00:00
l10n daemon script
0dca9588ff GIT_SILENT Sync po/docbooks with svn 2023-04-16 01:56:40 +00:00
Tobias Fella
ca03c530b2 Fix various warnings 2023-04-15 18:07:26 +00:00
James Graham
973ec24674 Document searchmodel 2023-04-15 17:57:21 +00:00
James Graham
1da767ff0a Document roomlistmodel 2023-04-15 17:18:33 +00:00
James Graham
89127876f9 Document serverlistmodel 2023-04-15 16:51:32 +00:00
Tobias Fella
47a738a703 Revert "Revert "Implement sending location messages""
This reverts commit 52dafbb6c8.
2023-04-15 16:01:04 +00:00
James Graham
516b1cff88 Document publicroomlistmodel 2023-04-15 09:00:49 +00:00
James Graham
6438977964 Document messagefiltermodel 2023-04-15 08:46:45 +00:00
James Graham
d750263d39 Document keywordnotificationrulemodel 2023-04-15 08:32:35 +00:00
James Graham
3ed952db9e Document emojimodel 2023-04-15 08:15:23 +00:00
James Graham
f8040a1bf6 Guard getTagType and isCloseTag
Add guard clauses for getTagType and isCloseTag to avoid crashing if the string is empty.

CCBUG: 468448
2023-04-15 07:59:05 +00:00
l10n daemon script
d83b31fd86 GIT_SILENT Sync po/docbooks with svn 2023-04-15 01:59:35 +00:00
James Graham
e0dbb657f6 Document devicesmodel 2023-04-14 13:14:39 +00:00
James Graham
a807cc6143 Document customemojimodel 2023-04-14 12:57:05 +00:00
l10n daemon script
fe064c0ef8 GIT_SILENT Sync po/docbooks with svn 2023-04-14 01:50:25 +00:00
James Graham
6cc773426f Document completionmodel
Document completionmodel and remove unnecessary includes
2023-04-13 17:35:44 +00:00
James Graham
db94408ba6 Document completionproxymodel 2023-04-13 17:15:38 +00:00
James Graham
333bd3cdb9 Document collapsestateproxymodel
Document collapsestateproxymodel and make som public functions private.
2023-04-13 16:41:41 +00:00
l10n daemon script
9a0d82eb31 GIT_SILENT Sync po/docbooks with svn 2023-04-13 01:58:59 +00:00
James Graham
0990c0507c Document actionsmodel and cleanup includes 2023-04-12 21:12:14 +00:00
Heiko Becker
9f76ce22c1 GIT_SILENT Update Appstream for new release
(cherry picked from commit 2c3ce1e88b)
2023-04-12 19:09:48 +02:00
l10n daemon script
6acd6075ff GIT_SILENT Sync po/docbooks with svn 2023-04-12 01:55:28 +00:00
Tobias Fella
57b6f00d8e Use better include for QCoroTask 2023-04-11 15:34:12 +02:00
Tobias Fella
280c9327cb Remove unused signal 2023-04-11 15:31:40 +02:00
l10n daemon script
05bcbb695f GIT_SILENT Sync po/docbooks with svn 2023-04-11 02:21:00 +00:00
James Graham
552f4e8f13 Fix Rich Emote Test Windows Qt5
Make sure that the receiveRichEmote test grabs an actual colour for the user as it can vary by platform.
2023-04-10 12:55:31 +00:00
Carl Schwan
1223c5348d Rename ConfirmLogoutDialog to Dialog.ConfirmLogout
Signed-off-by: Carl Schwan <carl@carlschwan.eu>
2023-04-10 13:54:57 +02:00
Carl Schwan
3ccff4f337 Refactor room list in multiple sub components
Also modernize the codebase where possible (e.g use required properties,
reorder properties, fix warnings, don't use Action when not needed)

Signed-off-by: Carl Schwan <carl@carlschwan.eu>
2023-04-10 13:53:42 +02:00
l10n daemon script
a67f3334ea GIT_SILENT Sync po/docbooks with svn 2023-04-10 01:50:51 +00:00
Tobias Fella
52dafbb6c8 Revert "Implement sending location messages"
This reverts commit f3a04635cf
2023-04-09 20:22:06 +00:00
James Graham
4341cc437d Handle escaped html for plain text output
Always unescape html for plain text output no matter what the input is.
2023-04-09 14:20:22 +00:00
James Graham
7bb7dd7bbb Document messageeventmodel
Document the API and cleanup some unused roles.
2023-04-09 14:02:30 +00:00
James Graham
b4090d9671 Fix Chat bubble background changing color when created
Only enable the animating of the bubble background when the temporary highlight is applied to avoid it flashing white on entry.

BUG: 468124
2023-04-09 12:13:46 +00:00
l10n daemon script
3d2bcce99a GIT_SILENT Sync po/docbooks with svn 2023-04-09 01:54:23 +00:00
Tobias Fella
f3a04635cf Implement sending location messages 2023-04-09 00:44:02 +00:00
Tobias Fella
419cb07557 Revert "Temporarily disable android Qt6 CI"
This reverts commit d6ebb1308c
2023-04-09 02:22:53 +02:00
Tobias Fella
57fccaa076 Rework QuickSwitcher
Now looks similar to the implementations in Kalendar and KXMLGui

![image](/uploads/56497b81348d553ff9b8ea30ab41fba7/image.png)

Replaces !505
2023-04-09 00:15:00 +00:00
James Graham
4bf65339f8 Texthandler edited
Move the handling of adding whether the message has been edited to texthandler.
2023-04-08 20:58:44 +00:00
l10n daemon script
e5f2e209a2 GIT_SILENT Sync po/docbooks with svn 2023-04-08 01:58:38 +00:00
James Graham
be3b5cdb8a Handle emotes in texthander
This moves the code to add the emote user pill into texthandler removing the now redundant checks from the message delegates.
2023-04-07 19:03:04 +00:00
l10n daemon script
abd56baa51 GIT_SILENT Sync po/docbooks with svn 2023-04-07 01:49:52 +00:00
l10n daemon script
ff27a1d0bb GIT_SILENT Sync po/docbooks with svn 2023-04-06 01:51:39 +00:00
Wang Zichong
8af2d4d273 Support both roomnick and myroomnick slash command
myroomnick is a more common-used command, so user can keep using
/myroomnick if they are from other matrix client.
2023-04-05 23:19:07 +08:00
Carl Schwan
f64c8e28da Use newly introduced setBadgeNumber api on Qt >= 6.6 2023-04-05 10:15:04 +02:00
l10n daemon script
4570d6350b GIT_SILENT Sync po/docbooks with svn 2023-04-05 01:59:34 +00:00
Alessio Mattiazzi
6dd51a35c5 Clear room member filter when hiding search bar
closes #575
2023-04-04 21:04:05 +00:00
l10n daemon script
2470990d75 GIT_SILENT Sync po/docbooks with svn 2023-04-04 02:01:31 +00:00
Tobias Fella
1a87e605d6 Fix formatting 2023-04-03 23:32:31 +02:00
Jan Bidler
e995740790 Text cleanup
This MR goes over text and cleans it up to be more unifying. Mostly just lowercasing words in non-titles, but it also changes the "show fancy effects" text to be clearer with its meaning.  
It also fixes the room access being printed in the room settings:  ![image](/uploads/864606de81f0f603ebb85dbe7c745491/image.png)  
I'd like to do a second pass later with another MR to unify triple dots (...) and ellipsis (…)
2023-04-03 20:47:14 +00:00
l10n daemon script
0fb8b740a4 GIT_SILENT Sync po/docbooks with svn 2023-04-03 01:53:49 +00:00
James Graham
5087161e4b Document NeoChatRoom
Add documentation to NeochatRoom and reorganise the functions in the header file in a more logical order.

For Q_PROPERTIES the documentation is on the property not the functions it calls as seems to be the convention elsewhere.
2023-04-02 17:56:03 +00:00
James Graham
918e9e492a Make sure the file delegate label fill the width and elide if needed. 2023-04-02 15:41:55 +00:00
Marc Deop i Argemí
f10805dddb feat: add background-color to <code> blocks 2023-04-02 10:54:41 +02:00
l10n daemon script
55e4d03dfe GIT_SILENT Sync po/docbooks with svn 2023-04-02 01:54:00 +00:00
James Graham
9f9086b4b0 Make the room page header span the width in compact mode with the sam emargin on both sides. 2023-04-01 17:03:53 +00:00
James Graham
e00ce79d26 Change the background colour in compact mode to achieve the same level of contrast as with bubbles. 2023-04-01 15:52:48 +00:00
James Graham
a13b2e6bd2 Cleanup Neochatroom
Remove unneeded functions, remove Q_INVOKABLE from setters that are part of a Q_PROPERTY, move inlined getters and setters to the .cpp
2023-04-01 12:49:27 +00:00
James Graham
cefe5acdaa Fix Long Topics in the RoomDrawer Overflowing
Use a scrollView for the topic so that a scrollBar is shown when it really long

BUG: 467512
2023-04-01 10:24:26 +00:00
James Graham
1438aea965 Revert "Add kquickcharts to the flatpak manifest"
This reverts commit 3cc8d32dd3
2023-04-01 08:23:48 +00:00
l10n daemon script
1b60e24c64 GIT_SILENT Sync po/docbooks with svn 2023-04-01 01:55:31 +00:00
l10n daemon script
4f1c8f6f35 GIT_SILENT Sync po/docbooks with svn 2023-03-31 01:57:59 +00:00
Carl Schwan
882945260a Fix dataChanged being sent with all roles
This is expensive so we should try to reduce it to the maximum

Signed-off-by: Carl Schwan <carl@carlschwan.eu>
2023-03-30 18:37:50 +00:00
Carl Schwan
3677088104 Remove one RoomListModel instance
Signed-off-by: Carl Schwan <carl@carlschwan.eu>
2023-03-30 18:21:03 +00:00
Akseli Lahtinen
8f141cd88d Set the mention and error color according to colorscheme
Use kirigami to set the proper link and error color for mentions and error underlining in chatbox

This is with my own colorscheme:

![image](/uploads/6269b85f936a98b02f42a9ce01da76b1/image.png)
2023-03-30 16:25:01 +00:00
l10n daemon script
0d1b35b610 GIT_SILENT Sync po/docbooks with svn 2023-03-30 01:53:26 +00:00
Tobias Fella
87c20bf03c Update .gitignore 2023-03-29 22:18:20 +02:00
l10n daemon script
77479ca22d GIT_SILENT Sync po/docbooks with svn 2023-03-29 01:56:21 +00:00
Tobias Fella
34ad743e98 Don't crash in UserListModel when there is no room
BUG: 466045
2023-03-28 11:47:14 +00:00
l10n daemon script
493e27622f GIT_SILENT Sync po/docbooks with svn 2023-03-28 02:21:27 +00:00
James Graham
b1b6c7ceed Improve location marker
Change location marker to GPS icon, make sure the point is the anchor and colour it with highlight colour

m.self \
![image](/uploads/d7136e7f70a106665fcaea0588a334f7/image.png)

m.pin \
![image](/uploads/baee5d19c098eaab1abd91533fe431e5/image.png)
2023-03-27 16:38:34 +00:00
l10n daemon script
d0b1610a9f GIT_SILENT Sync po/docbooks with svn 2023-03-27 02:44:58 +00:00
Tobias Fella
dcf520a7a9 Fix locations for geouris with uncertainty 2023-03-26 22:55:05 +02:00
James Graham
a0ae8b28b2 Handle stripnewlines for plain text list
Handle stripping new lines when the plain text input is a markdown list.
2023-03-26 20:27:23 +00:00
l10n daemon script
78a6179a11 GIT_SILENT Sync po/docbooks with svn 2023-03-26 01:58:24 +00:00
l10n daemon script
9c91557d8f GIT_SILENT Sync po/docbooks with svn 2023-03-25 01:55:18 +00:00
Tobias Fella
fb24ffd20d Show a map for location events 2023-03-24 13:52:17 +00:00
l10n daemon script
0c985a0af1 GIT_SILENT Sync po/docbooks with svn 2023-03-24 01:52:23 +00:00
Tobias Fella
787dc5ab66 Ensure that the room list subtitle is a single line 2023-03-23 20:10:35 +00:00
l10n daemon script
f11abdeebd GIT_SILENT Sync po/docbooks with svn 2023-03-22 02:16:45 +00:00
l10n daemon script
89141dddf2 GIT_SILENT Sync po/docbooks with svn 2023-03-21 02:03:28 +00:00
l10n daemon script
69f08de0ff GIT_SILENT Sync po/docbooks with svn 2023-03-20 01:59:17 +00:00
James Graham
925e20ebb8 Handle quotes in plain strings
Unescape quotes in plain strings
2023-03-19 19:58:56 +00:00
James Graham
ee254a286d Handle single quotes for links
Make sure that the text handler can handle links which use single or double quotes for the attributes.
2023-03-19 19:06:08 +00:00
James Graham
3cc8d32dd3 Add kquickcharts to the flatpak manifest 2023-03-19 18:34:45 +00:00
l10n daemon script
50cf6d9750 GIT_SILENT Sync po/docbooks with svn 2023-03-19 01:51:40 +00:00
Tobias Fella
cedbb64932 Remove unused include 2023-03-19 02:00:45 +01:00
Tobias Fella
b45898a5b6 Fix typo in actionName 2023-03-19 01:59:55 +01:00
Tobias Fella
ccb1748ab3 Only try to find sqlite on android
Cleans up the cmake output a bit
2023-03-19 01:54:16 +01:00
James Graham
11e9af15f7 Add Quick Formatting Menu in the Chatbar
Add a menu to quickly apply text effects when selecting text in the chatbar.

![image](/uploads/aa4d3b6f7e89695e1168aeee536d2df4/image.png)
2023-03-18 10:44:28 +00:00
l10n daemon script
8ad41fec92 GIT_SILENT Sync po/docbooks with svn 2023-03-18 02:12:49 +00:00
James Graham
ac5212ebb2 Update space heirarchy cache
Add functions to update the space heirarchy cache when a new space is added or removed.
2023-03-17 14:23:39 +00:00
James Graham
4e16b91f54 Hide local edit message
When a local message is edited make sure that the initial message that will be merged remains hidden so it doesn't flash up then disappear.

closes network/neochat#314
2023-03-17 10:07:31 +00:00
l10n daemon script
343f4965ed GIT_SILENT Sync po/docbooks with svn 2023-03-17 02:11:51 +00:00
James Graham
ac775c5aaf Add pie shaped progress bar for chatbar instead of busy indicator
![2023-03-15_15-06-51](/uploads/7a56d2a1696e26b87451b0951995a730/2023-03-15_15-06-51.mp4)

Closes network/neochat#151
2023-03-16 19:22:37 +00:00
James Graham
db17888d42 Add action name required propereties for the room settings. 2023-03-16 09:16:21 +00:00
l10n daemon script
f12d10baa6 GIT_SILENT Sync po/docbooks with svn 2023-03-16 02:04:44 +00:00
James Graham
4289c1345f Update about neochat actionName to "aboutNeochat" and add one for about KDE 2023-03-15 14:56:37 +00:00
James Graham
0d6a83b063 Add end state to text handler and use to ensure that in nextTokenType to stop an out of bounds access to m_databuffer 2023-03-15 11:55:50 +00:00
l10n daemon script
76b04dcba9 GIT_SILENT Sync po/docbooks with svn 2023-03-15 01:58:28 +00:00
James Graham
64dee7eb12 Add right click menu to accountlist avatar
Adds a right click menu with the following options

![image](/uploads/09a266fb609bb8f94b206eb66f09e06d/image.png)

depends upon frameworks/kirigami!933
2023-03-14 23:00:41 +00:00
Carl Schwan
bc84ad8d56 Don't focus chatbar on mobile
This popup the virtual keyboard and is quite distrubing on mobile.

Signed-off-by: Carl Schwan <carl@carlschwan.eu>
2023-03-14 22:27:44 +00:00
James Graham
afe8a2a5e4 Newline Mobile
Make return/enter create a newline on mobile. This is the traditional behaviour in other messengers as the send icon and return have are the same time to access and solves the linked issue.

Closes network/neochat#466
2023-03-14 22:26:18 +00:00
Carl Schwan
87213dc9dd Show back button when pushing the settings on mobile
To use with https://invent.kde.org/frameworks/kirigami/-/merge_requests/992

Signed-off-by: Carl Schwan <carl@carlschwan.eu>
2023-03-14 22:24:22 +00:00
James Graham
300d2428eb Remove rogue console.log statement 2023-03-14 19:38:18 +00:00
James Graham
abe7d70822 Add home and coloured notifications icons 2023-03-14 15:55:31 +00:00
l10n daemon script
d8bf26158a GIT_SILENT Sync po/docbooks with svn 2023-03-14 01:57:26 +00:00
James Graham
741cb57105 Fix state event visiblity in timeline
Rework the filtering of state events in the timeline and for lastevent. This is now consistent everywhere and includes the following:
- The timeline settings are obeyed everywhere
- A new setting is added to filter all state events
- Last event obeys the timeline setting in all cases
- The roomlist will show a state event as the latest event if it's visible in the timeline
- Names are no longer hyperlinked in eventToString if plaintext is selected.

BUG: 455048\
Closes network/neochat#148
2023-03-13 19:00:22 +00:00
James Graham
81c73037ca Room URL preview settings
- Add the ability to set the deafult url preview setting for the room if you have sufficient power level.
- Add the ability for the user to set the desired url preview setting.

network/neochat#560
2023-03-13 18:23:18 +00:00
James Graham
f6ba4f2ecd Improve Text Handling
Improve the handling of text both when sending and receiving.

The main feature is to fix the linked bug (and a host of others that are unreported but similar) which is caused by the fact that we don't properly clean html. This mr does that as per the matrix spec https://spec.matrix.org/v1.5/client-server-api/#mroommessage-msgtypes. So any disallowed tags or attributes are removed and it does the special handling for certain attributes.

Additionally the functions are also designed to cover any other text formatting required, particularly fro received strings.

The receive side is covered by 2 functions `handleRecieveRichText` and `handleRecievePlainText`. The rich/plain in the function name refers to the output type not the input type (both can take plain and rich input), so `handleRecieveRichText` is called to get a string suitable to go in a rich text control and `handleRecievePlainText` for a plain control.

The functions also handle the following some of which was previously handled by `eventToString` in `NeoChatRoom`:
- Strip and reply from the string
- Format any user mentions
- Linkify links in plain strings
- Handle mxc urls in rich text (uses the new `room->makeMediaUrl` functionality from libQuotient)
- `handleRecievePlainText` also deals with markup making `NeoChatRoom->subtitle` redundant

There is also an extensive test suite which defines the behaviour and the best way to review this is probably to look at the tests and decide whether you agree with the expected output given the inputs and/or if there is any missing behaviour.

The final aim especially with the test suite is to give us a framework to make further updates in the future easier and hopefully prevent a new feature breaking old behaviour with the tests.

BUG: 463932 \
BUG: 466330 \
BUG: 466930
2023-03-13 17:28:56 +00:00
James Graham
23303c0483 Other user read markers
Add the ability to see other user's read markers. 

![image](/uploads/a4bdc35a60ab10685c7d3ea4d9b13c87/image.png)

Implements network/neochat#133
2023-03-13 15:12:46 +00:00
l10n daemon script
5a02448326 GIT_SILENT Sync po/docbooks with svn 2023-03-13 02:08:04 +00:00
l10n daemon script
411ae25e80 GIT_SILENT Sync po/docbooks with svn 2023-03-12 03:18:42 +00:00
l10n daemon script
6e1b3fe860 GIT_SILENT Sync po/docbooks with svn 2023-03-11 02:14:41 +00:00
Albert Astals Cid
4a38d83a68 GIT_SILENT Upgrade release service version to 23.07.70. 2023-03-10 22:00:27 +01:00
270 changed files with 56225 additions and 36992 deletions

View File

@@ -41,6 +41,7 @@
{
"name": "olm",
"buildsystem": "cmake-ninja",
"config-opts": [ "-DOLM_TESTS=OFF" ],
"sources": [
{
"type": "git",
@@ -111,12 +112,14 @@
}
],
"config-opts": [
"-DQuotient_ENABLE_E2EE=ON"
"-DQuotient_ENABLE_E2EE=ON",
"-DBUILD_TESTING=OFF"
]
},
{
"name": "cmark",
"buildsystem": "cmake-ninja",
"config-opts": [ "-DCMARK_TESTS=OFF" ],
"sources": [
{
"type": "git",
@@ -133,6 +136,7 @@
{
"name": "qcoro",
"buildsystem": "cmake-ninja",
"config-opts": [ "-DQCORO_BUILD_EXAMPLES=OFF", "-DBUILD_TESTING=OFF" ],
"sources": [
{
"type": "archive",

1
.gitignore vendored
View File

@@ -10,3 +10,4 @@ kate.project.ctags.*
*.user
.flatpak-builder/
.idea/
cmake-build-*

View File

@@ -8,7 +8,7 @@ include:
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/linux.yml
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/linux-qt6.yml
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/windows.yml
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/windows-qt6.yml
# - https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/windows-qt6.yml
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/freebsd.yml
# - https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/freebsd-qt6.yml
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/flatpak.yml

View File

@@ -11,6 +11,7 @@ Dependencies:
'frameworks/kconfig': '@stable'
'frameworks/syntax-highlighting': '@stable'
'frameworks/kitemmodels': '@stable'
'frameworks/kquickcharts': '@stable'
'frameworks/knotifications': '@stable'
'libraries/kquickimageeditor': '@stable'
'frameworks/sonnet': '@stable'
@@ -38,6 +39,7 @@ Dependencies:
'frameworks/kconfig': '@latest-kf6'
'frameworks/syntax-highlighting': '@latest-kf6'
'frameworks/kitemmodels': '@latest-kf6'
'frameworks/kquickcharts': '@latest-kf6'
'frameworks/knotifications': '@latest-kf6'
'libraries/kquickimageeditor': '@latest-kf6'
'frameworks/sonnet': '@latest-kf6'
@@ -57,4 +59,4 @@ Dependencies:
'frameworks/kdbusaddons': '@latest-kf6'
Options:
require-passing-tests-on: [ 'Linux/Qt5', 'FreeBSD', 'Windows/Qt5' ]
require-passing-tests-on: [ 'Linux/Qt5', 'FreeBSD' ]

View File

@@ -8,13 +8,13 @@ cmake_minimum_required(VERSION 3.16)
# KDE Applications version, managed by release script.
set(RELEASE_SERVICE_VERSION_MAJOR "23")
set(RELEASE_SERVICE_VERSION_MINOR "04")
set(RELEASE_SERVICE_VERSION_MICRO "1")
set(RELEASE_SERVICE_VERSION_MINOR "07")
set(RELEASE_SERVICE_VERSION_MICRO "70")
set(RELEASE_SERVICE_VERSION "${RELEASE_SERVICE_VERSION_MAJOR}.${RELEASE_SERVICE_VERSION_MINOR}.${RELEASE_SERVICE_VERSION_MICRO}")
project(NeoChat VERSION ${RELEASE_SERVICE_VERSION})
set(KF_MIN_VERSION "5.91.0")
set(KF_MIN_VERSION "5.105.0")
set(QT_MIN_VERSION "5.15.2")
if (ANDROID)
set(QT_MIN_VERSION "5.15.8")
@@ -39,6 +39,7 @@ include(KDECompilerSettings NO_POLICY_SCOPE)
include(ECMAddAppIcon)
include(KDEGitCommitHooks)
include(ECMCheckOutboundLicense)
include(ECMQtDeclareLoggingCategory)
if (NOT ANDROID)
include(KDEClangFormat)
endif()
@@ -93,8 +94,12 @@ if (NOT ANDROID AND NOT WIN32 AND NOT APPLE)
find_package(KF${QT_MAJOR_VERSION}DBusAddons ${KF_MIN_VERSION} REQUIRED)
endif()
find_package(Quotient 0.6)
set_package_properties(Quotient PROPERTIES
if(QT_MAJOR_VERSION STREQUAL "6" AND NOT ANDROID AND NOT WIN32)
set(QUOTIENT_SUFFIX "Qt6")
endif()
find_package(Quotient${QUOTIENT_SUFFIX} 0.6)
set_package_properties(Quotient${QUOTIENT_SUFFIX} PROPERTIES
TYPE REQUIRED
DESCRIPTION "Qt wrapper around Matrix API"
URL "https://github.com/quotient-im/libQuotient/"
@@ -111,6 +116,7 @@ set_package_properties(cmark PROPERTIES
ecm_find_qmlmodule(org.kde.kquickimageeditor 1.0)
ecm_find_qmlmodule(org.kde.kitemmodels 1.0)
ecm_find_qmlmodule(org.kde.quickcharts 1.0)
find_package(KQuickImageEditor COMPONENTS)
set_package_properties(KQuickImageEditor PROPERTIES
@@ -130,16 +136,23 @@ set_package_properties(KF${QT_MAJOR_VERSION}DocTools PROPERTIES DESCRIPTION
TYPE OPTIONAL
)
find_package(Sqlite3)
if(NOT Quotient_VERSION_MINOR GREATER 6)
if(NOT Quotient${QUOTIENT_SUFFIX}_VERSION_MINOR GREATER 6)
cmake_policy(SET CMP0063 OLD)
endif()
if(ANDROID)
find_package(Sqlite3)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/android/version.gradle.in ${CMAKE_BINARY_DIR}/version.gradle)
endif()
include(FindPkgConfig)
pkg_check_modules(GSTREAMER IMPORTED_TARGET gstreamer-sdp-1.0>1.18 gstreamer-webrtc-1.0>=1.18)
if (TARGET PkgConfig::GSTREAMER)
add_feature_info(voip ON "GStreamer found. Call support is enabled.")
else()
add_feature_info(voip OFF "GStreamer not found. Call support is disabled.")
endif()
ki18n_install(po)
install(FILES org.kde.neochat.desktop DESTINATION ${KDE_INSTALL_APPDIR})
@@ -150,7 +163,7 @@ install(FILES org.kde.neochat.tray.svg DESTINATION ${KDE_INSTALL_FULL_ICONDIR}/h
add_definitions(-DQT_NO_FOREACH)
add_subdirectory(src)
if (BUILD_TESTING AND Quotient_VERSION_MINOR GREATER 6)
if (BUILD_TESTING AND Quotient${QUOTIENT_SUFFIX}_VERSION_MINOR GREATER 6)
find_package(Qt${QT_MAJOR_VERSION} ${QT_MIN_VERSION} NO_MODULE COMPONENTS Test)
add_subdirectory(autotests)
endif()

100
README.md
View File

@@ -1,24 +1,51 @@
<!--
SPDX-FileCopyrightText: 2020-2021 Carl Schwan <carlschwan@kde.org>
SPDX-FileCopyrightText: 2020-2021 Tobias Fella <tobias.fella@kde.org>
SPDX-FileCopyrightText: 2023 James Graham <james.h.graham@protonmail.com>
SPDX-License-Identifier: CC0-1.0
-->
# NeoChat
NeoChat is a client for Matrix, the decentralized communication protocol for instant
messaging. It is a fork of Spectral, using KDE frameworks, most notably Kirigami,
KConfig and KI18n.
A Qt/QML based Matrix client.
<a href='https://matrix.org'><img src='https://matrix.org/docs/projects/images/made-for-matrix.png' alt='Made for Matrix' height=64 target=_blank /></a>
<a href='https://flathub.org/apps/details/org.kde.neochat'><img width='190px' alt='Download on Flathub' src='https://flathub.org/assets/badges/flathub-badge-i-en.png'/></a>
## Introduction
NeoChat is a client for [Matrix](https://matrix.org), the decentralized communication protocol for instant
messaging. It is a fork of Spectral, using KDE frameworks, most notably [Kirigami](https://invent.kde.org/frameworks/kirigami)
to provide a convergent experience across multiple platforms.
NeoChat also make use of other KDE Frameworks as well as [libQuotient](https://github.com/quotient-im/libQuotient), a
Qt-based SDK for the [Matrix Protocol](https://spec.matrix.org/).
![Timeline](https://cdn.kde.org/screenshots/neochat/application.png)
## Features
NeoChat aims to be a fully featured application for the Matrix specification. As such everything in the current stable specification with the notable exceptions
of VoIP, threads and some aspects of End-to-End Encryption are supported. There are a few other smaller omissions due to the fact that the Matrix spec is constantly
evolving but the aim remains to provide eventual support for the entire spec.
Due to the nature of the Matrix specification development NeoChat also supports numerous unstable features. Currently these are:
- Polls - MSC3381
- Sticker Packs - MSC2545
- Location Events - MSC3488
## Get it
A stable release [is available](https://apps.kde.org/neochat) for download for Linux distributions.
Details where to find stable releases for NeoChat can be found on its [homepage](https://apps.kde.org/neochat).
In addition to the stable builds, unstable nightly builds are available for all platforms. These can be downloaded
from the [binary factory](https://binary-factory.kde.org/). There are unstable versions for the following platforms
in addition to stable ones:
- Android
- MacOS
- Windows
Along with the stable release, a Flatpak version is available for the nightly
version:
Additionally the nightly Flatpak version can be obtained from the nightly Flatpak repo using the following commands in your terminal:
```
flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
@@ -26,42 +53,53 @@ flatpak remote-add --if-not-exists kdeapps --from https://distribute.kde.org/kde
flatpak install kdeapps org.kde.neochat
```
A nightly build is also available for Android in the [KDE nightly F-Droid repo](https://community.kde.org/Android/FDroid)
and can also directly be downloaded from the [binary factory](https://binary-factory.kde.org/view/Android/job/NeoChat_Nightly_android-arm64/).
The unstable Android version can also be obtained from the [KDE nightly F-Droid repo](https://community.kde.org/Android/FDroid).
Nightly builds for [Windows](https://binary-factory.kde.org/job/NeoChat_Nightly_win64/), [MacOS](https://binary-factory.kde.org/job/NeoChat_Nightly_macos/) and [AppImages](https://binary-factory.kde.org/job/NeoChat_Nightly_appimage/) can also be downloaded from the [binary factory](https://binary-factory.kde.org/search/?q=neochat).
## Running
![Timeline](https://cdn.kde.org/screenshots/neochat/application.png)
Just start the executable in your preferred way - either from the build directory or from the installed location.
## Features
## Building NeoChat
* Sending messages
* Sending files from clipboard and filesystem
* Reply to message (right-click on a message to access menu)
* Start a private chat (but not encrypted)
* Show notifications, for the moment there is only a global switch
to disable it. We plan to implement the configuration part of the
specification soon.
* Autocompletion of usernames in chat
* Emoji picker
* Basic room setting page
* Send and accept invitations
* /rainbow <message> (very important)
* /me <message>
The best way to build KDE apps during development is to use `kdesrc-build`. The full instructions for this can be found on
the KDE community website's get involved section under [development](https://community.kde.org/Get_Involved/development). This
is primarily aimed at Linux development.
NeoChat is still missing a few features to become a full-featured
Matrix client (most notably encryption support and video chat support).
We welcome contributions in this direction.
For Windows and Android [Craft](https://invent.kde.org/packaging/craft) is the primary choice. There are guides for setting up
development environments for [Windows](https://community.kde.org/Get_Involved/development/Windows) and [Android](https://develop.kde.org/docs/packaging/android/building_applications/).
## Tests
Tests are in the repository under [autotests](autotests) and should all pass for any contribution.
The project has CI setup to test new commits to the repository. All tests are expected to pass for a merge request to
be complete.
Current build status
![coverage](https://invent.kde.org/network/neochat/badges/master/pipeline.svg)
Currently the number of tests is limited, but growing. If anyone wants to help improve this, those
contributions would be especially welcome.
## Contributing
As is the case throughout the KDE ecosystem contributions are welcome from all. The code base is managed in the
[NeoChat repository](https://invent.kde.org/network/neochat) of the KDE Gitlab instance.
- [Code of Conduct](https://kde.org/code-of-conduct)
- [Report a Bug](https://bugs.kde.org/enter_bug.cgi?format=guided&product=neochat)
- [Feature Request](https://community.kde.org/Infrastructure/GitLab#Submitting_a_merge_request)
- [Create a Merge Request](https://community.kde.org/Infrastructure/GitLab#Submitting_a_merge_request)
- [Translation](https://community.kde.org/Get_Involved/translation)
## Contact
You can reach the maintainers at [#neochat:kde.org](https://matrix.to/#/#neochat:kde.org), if you are already on Matrix.
Development happens in http://invent.kde.org/network/neochat (not in GitHub).
The best place to reach the maintainers is on the KDE Matrix instance in the NeoChat channel, [#neochat:kde.org](https://matrix.to/#/#neochat:kde.org).
## Acknowledgement
This program utilizes [libQuotient](https://github.com/quotient-im/libQuotient/)
library and some C++ models from [Quaternion](https://github.com/quotient-im/Quaternion/).
This program utilizes [libQuotient](https://github.com/quotient-im/libQuotient/) as its Matrix SDK.
This program is a fork of [Spectral](https://gitlab.com/spectral-im/spectral/).

View File

@@ -5,7 +5,7 @@ enable_testing()
ecm_add_test(
neochatroomtest.cpp
LINK_LIBRARIES neochat Qt::Test Quotient
LINK_LIBRARIES neochat Qt::Test
TEST_NAME neochatroomtest
)
@@ -14,3 +14,9 @@ ecm_add_test(
LINK_LIBRARIES neochat Qt::Test
TEST_NAME texthandlertest
)
ecm_add_test(
delegatesizehelpertest.cpp
LINK_LIBRARIES neochat Qt::Test
TEST_NAME delegatesizehelpertest
)

View File

@@ -0,0 +1,156 @@
// SPDX-FileCopyrightText: 2023 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#include <QObject>
#include <QTest>
#include "delegatesizehelper.h"
class DelegateSizeHelperTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void risingPercentage_data();
void risingPercentage();
void fallingPercentage_data();
void fallingPercentage();
void equalPercentage_data();
void equalPercentage();
void equalBreakpoint_data();
void equalBreakpoint();
};
void DelegateSizeHelperTest::risingPercentage_data()
{
QTest::addColumn<qreal>("parentWidth");
QTest::addColumn<int>("currentPercentageWidth");
QTest::addColumn<qreal>("currentWidth");
QTest::newRow("zero") << qreal(0) << int(0) << qreal(0);
QTest::newRow("one hundred") << qreal(100) << int(0) << qreal(0);
QTest::newRow("one fifty") << qreal(150) << int(50) << qreal(75);
QTest::newRow("two hundred") << qreal(200) << int(100) << qreal(200);
QTest::newRow("three hundred") << qreal(300) << int(100) << qreal(300);
}
void DelegateSizeHelperTest::risingPercentage()
{
QFETCH(qreal, parentWidth);
QFETCH(int, currentPercentageWidth);
QFETCH(qreal, currentWidth);
DelegateSizeHelper delegateSizeHelper;
delegateSizeHelper.setStartBreakpoint(100);
delegateSizeHelper.setEndBreakpoint(200);
delegateSizeHelper.setStartPercentWidth(0);
delegateSizeHelper.setEndPercentWidth(100);
delegateSizeHelper.setParentWidth(parentWidth);
QCOMPARE(delegateSizeHelper.currentPercentageWidth(), currentPercentageWidth);
QCOMPARE(delegateSizeHelper.currentWidth(), currentWidth);
}
void DelegateSizeHelperTest::fallingPercentage_data()
{
QTest::addColumn<qreal>("parentWidth");
QTest::addColumn<int>("currentPercentageWidth");
QTest::addColumn<qreal>("currentWidth");
QTest::newRow("zero") << qreal(0) << int(100) << qreal(0);
QTest::newRow("one hundred") << qreal(100) << int(100) << qreal(100);
QTest::newRow("one fifty") << qreal(150) << int(50) << qreal(75);
QTest::newRow("two hundred") << qreal(200) << int(0) << qreal(0);
QTest::newRow("three hundred") << qreal(300) << int(0) << qreal(0);
}
void DelegateSizeHelperTest::fallingPercentage()
{
QFETCH(qreal, parentWidth);
QFETCH(int, currentPercentageWidth);
QFETCH(qreal, currentWidth);
DelegateSizeHelper delegateSizeHelper;
delegateSizeHelper.setStartBreakpoint(100);
delegateSizeHelper.setEndBreakpoint(200);
delegateSizeHelper.setStartPercentWidth(100);
delegateSizeHelper.setEndPercentWidth(0);
delegateSizeHelper.setParentWidth(parentWidth);
QCOMPARE(delegateSizeHelper.currentPercentageWidth(), currentPercentageWidth);
QCOMPARE(delegateSizeHelper.currentWidth(), currentWidth);
}
void DelegateSizeHelperTest::equalPercentage_data()
{
QTest::addColumn<qreal>("parentWidth");
QTest::addColumn<int>("currentPercentageWidth");
QTest::addColumn<qreal>("currentWidth");
QTest::newRow("zero") << qreal(0) << int(50) << qreal(0);
QTest::newRow("one hundred") << qreal(100) << int(50) << qreal(50);
QTest::newRow("one fifty") << qreal(150) << int(50) << qreal(75);
QTest::newRow("two hundred") << qreal(200) << int(50) << qreal(100);
QTest::newRow("three hundred") << qreal(300) << int(50) << qreal(150);
}
void DelegateSizeHelperTest::equalPercentage()
{
QFETCH(qreal, parentWidth);
QFETCH(int, currentPercentageWidth);
QFETCH(qreal, currentWidth);
DelegateSizeHelper delegateSizeHelper;
delegateSizeHelper.setStartBreakpoint(100);
delegateSizeHelper.setEndBreakpoint(200);
delegateSizeHelper.setStartPercentWidth(50);
delegateSizeHelper.setEndPercentWidth(50);
delegateSizeHelper.setParentWidth(parentWidth);
QCOMPARE(delegateSizeHelper.currentPercentageWidth(), currentPercentageWidth);
QCOMPARE(delegateSizeHelper.currentWidth(), currentWidth);
}
void DelegateSizeHelperTest::equalBreakpoint_data()
{
QTest::addColumn<int>("startPercentageWidth");
QTest::addColumn<int>("endPercentageWidth");
QTest::addColumn<int>("currentPercentageWidth");
QTest::addColumn<qreal>("currentWidth");
QTest::newRow("start higher") << int(100) << int(0) << int(-1) << qreal(0);
QTest::newRow("equal") << int(50) << int(50) << int(50) << qreal(500);
QTest::newRow("end higher") << int(0) << int(100) << int(-1) << qreal(0);
}
/**
* We expect a default return except in the case where the the two percentages are
* equal as that case can be calculated without dividing by zero.
*/
void DelegateSizeHelperTest::equalBreakpoint()
{
QFETCH(int, startPercentageWidth);
QFETCH(int, endPercentageWidth);
QFETCH(int, currentPercentageWidth);
QFETCH(qreal, currentWidth);
DelegateSizeHelper delegateSizeHelper;
delegateSizeHelper.setStartBreakpoint(100);
delegateSizeHelper.setEndBreakpoint(100);
delegateSizeHelper.setStartPercentWidth(startPercentageWidth);
delegateSizeHelper.setEndPercentWidth(endPercentageWidth);
delegateSizeHelper.setParentWidth(1000);
QCOMPARE(delegateSizeHelper.currentPercentageWidth(), currentPercentageWidth);
QCOMPARE(delegateSizeHelper.currentWidth(), currentWidth);
}
QTEST_GUILESS_MAIN(DelegateSizeHelperTest)
#include "delegatesizehelpertest.moc"

View File

@@ -144,5 +144,5 @@ void NeoChatRoomTest::eventTest()
QCOMPARE(room->timelineSize(), 1);
}
QTEST_MAIN(NeoChatRoomTest)
QTEST_GUILESS_MAIN(NeoChatRoomTest)
#include "neochatroomtest.moc"

View File

@@ -6,7 +6,7 @@
#include "texthandler.h"
#include <connection.h>
#include <qnamespace.h>
#include <quotient_common.h>
#include <syncdata.h>
@@ -49,7 +49,8 @@ private Q_SLOTS:
void receiveStripReply();
void receivePlainTextIn();
void recieveRichInPlainOut();
void receiveRichInPlainOut_data();
void receiveRichInPlainOut();
void receivePlainStripHtml();
void receivePlainStripMarkup();
void receiveStripNewlines();
@@ -59,8 +60,15 @@ private Q_SLOTS:
void receiveRichtextIn();
void receiveRichMxcUrl();
void receiveRichPlainUrl();
void receiveRichEmote();
void receiveRichEdited_data();
void receiveRichEdited();
void receiveLineSeparator();
void linkPreviewsMatch_data();
void linkPreviewsMatch();
void linkPreviewsReject_data();
void linkPreviewsReject();
};
#ifdef QUOTIENT_07
@@ -148,7 +156,44 @@ void TextHandlerTest::initTestCase()
"sender": "@example:example.org",
"type": "m.room.message",
"unsigned": {
"age": 1235
"age": 1232
}
},
{
"content": {
"body": "/me This is an emote.",
"format": "org.matrix.custom.html",
"formatted_body": "This is an emote.",
"msgtype": "m.emote"
},
"event_id": "$153273582443PhrSn:example.org",
"origin_server_ts": 1532735824654,
"room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"sender": "@example:example.org",
"type": "m.room.message",
"unsigned": {
"age": 1231
}
},
{
"content": {
"body": "tested",
"msgtype": "m.text"
},
"event_id": "$zrCiBxBnqqTn0Z5FY78qSZAszno_w8nJJXzfBULG-3E",
"origin_server_ts": 1680948575928,
"room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"sender": "@example:example.org",
"type": "m.room.message",
"unsigned": {
"age": 1747776,
"m.relations": {
"m.replace": {
"event_id": "$UX0PlpyI7vYO32iHMuuYEP7ECMh4sX3XLGiB2SwM4mQ",
"origin_server_ts": 1680948580992,
"sender": "@example:example.org"
}
}
}
}
],
@@ -311,15 +356,24 @@ void TextHandlerTest::receiveStripReply()
QCOMPARE(testTextHandler.handleRecievePlainText(), testOutputString);
}
void TextHandlerTest::recieveRichInPlainOut()
void TextHandlerTest::receiveRichInPlainOut_data()
{
const QString testInputString = QStringLiteral("a &amp; b");
const QString testOutputString = QStringLiteral("a & b");
QTest::addColumn<QString>("testInputString");
QTest::addColumn<QString>("testOutputString");
QTest::newRow("ampersand") << QStringLiteral("a &amp; b") << QStringLiteral("a & b");
QTest::newRow("quote") << QStringLiteral("&quot;a and b&quot;") << QStringLiteral("\"a and b\"");
}
void TextHandlerTest::receiveRichInPlainOut()
{
QFETCH(QString, testInputString);
QFETCH(QString, testOutputString);
TextHandler testTextHandler;
testTextHandler.setData(testInputString);
QCOMPARE(testTextHandler.handleRecievePlainText(), testOutputString);
QCOMPARE(testTextHandler.handleRecievePlainText(Qt::RichText), testOutputString);
}
void TextHandlerTest::receivePlainTextIn()
@@ -441,7 +495,7 @@ void TextHandlerTest::receiveRichMxcUrl()
TextHandler testTextHandler;
testTextHandler.setData(testInputString);
QCOMPARE(testTextHandler.handleRecieveRichText(Qt::RichText, room, room->messageEvents().back().get()), testOutputString);
QCOMPARE(testTextHandler.handleRecieveRichText(Qt::RichText, room, room->messageEvents().at(0).get()), testOutputString);
}
#endif
@@ -500,6 +554,45 @@ void TextHandlerTest::receiveRichPlainUrl()
QCOMPARE(testTextHandler.handleRecieveRichText(Qt::RichText), testOutputStringMxId);
}
// Test that user pill is add to an emote message.
// N.B. The second message in the test timeline is marked as an emote.
void TextHandlerTest::receiveRichEmote()
{
auto event = room->messageEvents().at(1).get();
auto author = static_cast<NeoChatUser *>(room->user(event->senderId()));
const QString testInputString = QStringLiteral("This is an emote.");
const QString testOutputString = QStringLiteral("* <a href=\"https://matrix.to/#/@example:example.org\" style=\"color:") + author->color().name()
+ QStringLiteral("\">@example:example.org</a> This is an emote.");
TextHandler testTextHandler;
testTextHandler.setData(testInputString);
QCOMPARE(testTextHandler.handleRecieveRichText(Qt::RichText, room, event), testOutputString);
}
void TextHandlerTest::receiveRichEdited_data()
{
QTest::addColumn<QString>("testInputString");
QTest::addColumn<QString>("testOutputString");
QTest::newRow("basic") << QStringLiteral("Edited") << QStringLiteral("Edited <span style=\"color:#000000\">(edited)</span>");
QTest::newRow("multiple paragraphs") << QStringLiteral("<p>Edited</p>\n<p>Edited</p>")
<< QStringLiteral("<p>Edited</p>\n<p>Edited <span style=\"color:#000000\">(edited)</span></p>");
QTest::newRow("blockquote") << QStringLiteral("<blockquote>Edited</blockquote>")
<< QStringLiteral("<blockquote>Edited</blockquote><p> <span style=\"color:#000000\">(edited)</span></p>");
}
void TextHandlerTest::receiveRichEdited()
{
QFETCH(QString, testInputString);
QFETCH(QString, testOutputString);
TextHandler testTextHandler;
testTextHandler.setData(testInputString);
QCOMPARE(testTextHandler.handleRecieveRichText(Qt::RichText, room, room->messageEvents().at(2).get()), testOutputString);
}
void TextHandlerTest::receiveLineSeparator()
{
auto text = QStringLiteral("foo\u2028bar");
@@ -508,5 +601,52 @@ void TextHandlerTest::receiveLineSeparator()
QCOMPARE(textHandler.handleRecievePlainText(Qt::PlainText, true), QStringLiteral("foo bar"));
}
QTEST_MAIN(TextHandlerTest)
void TextHandlerTest::linkPreviewsMatch_data()
{
QTest::addColumn<QString>("testInputString");
QTest::addColumn<QList<QUrl>>("testOutputLinks");
QTest::newRow("plainHttps") << QStringLiteral("https://kde.org") << QList<QUrl>({QUrl("https://kde.org")});
QTest::newRow("richHttps") << QStringLiteral("<a href=\"https://kde.org\">Rich Link</a>") << QList<QUrl>({QUrl("https://kde.org")});
QTest::newRow("plainWww") << QStringLiteral("www.example.org") << QList<QUrl>({QUrl("www.example.org")});
QTest::newRow("multipleHttps") << QStringLiteral("https://kde.org www.example.org")
<< QList<QUrl>({
QUrl("https://kde.org"),
QUrl("www.example.org"),
});
}
void TextHandlerTest::linkPreviewsMatch()
{
QFETCH(QString, testInputString);
QFETCH(QList<QUrl>, testOutputLinks);
TextHandler testTextHandler;
testTextHandler.setData(testInputString);
QCOMPARE(testTextHandler.getLinkPreviews(), testOutputLinks);
}
void TextHandlerTest::linkPreviewsReject_data()
{
QTest::addColumn<QString>("testInputString");
QTest::addColumn<QList<QUrl>>("testOutputLinks");
QTest::newRow("mxc") << QStringLiteral("mxc://example.org/SEsfnsuifSDFSSEF") << QList<QUrl>();
QTest::newRow("matrixTo") << QStringLiteral("https://matrix.to/#/@alice:example.org") << QList<QUrl>();
QTest::newRow("noSpace") << QStringLiteral("testhttps://kde.org") << QList<QUrl>();
}
void TextHandlerTest::linkPreviewsReject()
{
QFETCH(QString, testInputString);
QFETCH(QList<QUrl>, testOutputLinks);
TextHandler testTextHandler;
testTextHandler.setData(testInputString);
QCOMPARE(testTextHandler.getLinkPreviews(), testOutputLinks);
}
QTEST_GUILESS_MAIN(TextHandlerTest)
#include "texthandlertest.moc"

View File

@@ -22,6 +22,7 @@
<name xml:lang="eu">NeoChat</name>
<name xml:lang="fi">NeoChat</name>
<name xml:lang="fr">NeoChat</name>
<name xml:lang="gl">NeoChat</name>
<name xml:lang="hu">NeoChat</name>
<name xml:lang="ia">Neochat</name>
<name xml:lang="id">NeoChat</name>
@@ -47,8 +48,8 @@
<summary>A client for matrix, the decentralized communication protocol</summary>
<summary xml:lang="ar">عميل لماتركس، ميفاق الاتصال اللامركزي</summary>
<summary xml:lang="az">Matrix üçün müştəri, mərkəzləşməmiş kommunikasiya protokolu</summary>
<summary xml:lang="ca">Un client per al Matrix, el protocol de comunicacions descentralitzat</summary>
<summary xml:lang="ca-valencia">Un client per a Matrix, el protocol de comunicacions descentralitzat</summary>
<summary xml:lang="ca">Un client de Matrix, el protocol de comunicacions descentralitzat</summary>
<summary xml:lang="ca-valencia">Un client de Matrix, el protocol de comunicacions descentralitzat</summary>
<summary xml:lang="cs">Klient pro decentralizovaný komunikační protokol matrix</summary>
<summary xml:lang="de">Ein Programm für Matrix, das dezentrale Kommunikationsprotokoll</summary>
<summary xml:lang="el">Ένας πελάτης για το Matrix, το αποκεντρωμένο πρωτόκολλο επικοινωνίας</summary>
@@ -57,6 +58,7 @@
<summary xml:lang="eu">Matrix, deszentralizatutako komunikazio protokolorako bezero bat</summary>
<summary xml:lang="fi">Asiakas Matrixille, hajautetulle viestintäyhteyskäytännölle</summary>
<summary xml:lang="fr">Un client pour « Matrix », le protocole décentralisé de communications.</summary>
<summary xml:lang="gl">Un cliente para Matrix, o protocolo de comunicación descentralizada</summary>
<summary xml:lang="hu">Kliens a matrixhoz, a decentralizált kommunikációs protokollhoz</summary>
<summary xml:lang="ia">Un cliente per Matrix, le protocollo de communication decentralisate</summary>
<summary xml:lang="id">Klien untuk matrix, protokol komunikasi terdesentralisasi</summary>
@@ -74,104 +76,123 @@
<summary xml:lang="sk">Klient pre matrix, decentralizovaný komunikačný protokol</summary>
<summary xml:lang="sl">Odjemalec za matrix, decentralizirani komunikacijski protokol</summary>
<summary xml:lang="sv">En klient för Matrix, det decentraliserade kommunikationsprotokollet</summary>
<summary xml:lang="ta">மையமில்லா தகவல் பரிமாற்ற நெறிமுறையான மேட்ரிக்ஸுக்கான செயலி</summary>
<summary xml:lang="tr">Merkezi olmayan iletişim protokolü Matrix için bir istemci</summary>
<summary xml:lang="uk">Клієнт matrix, децентралізованого протоколу обміну даними</summary>
<summary xml:lang="x-test">xxA client for matrix, the decentralized communication protocolxx</summary>
<summary xml:lang="zh-CN">分布式通讯协议 Matrix 的客户端</summary>
<description>
<p>NeoChat is a Matrix client. It allows you to send text messages, videos and audio files to your family, colleagues and friends using the Matrix protocol.</p>
<p xml:lang="ar">نيوتشات هو عميل ماتركس Matrix. يتيح لك إرسال رسائل نصية ومقاطع فيديو وملفات صوتية إلى عائلتك وزملائك وأصدقائك باستخدام بروتوكول ماتركس</p>
<p xml:lang="az">NeoChat Mtrix müştərisidir. O, Matrix protokolundan istifadə edərək, ailənizə, dostlarınıza, iş yoldaşlarınıza mətn, səsli və görüntülü ismarıclar göndərməyə imkan verir.</p>
<p xml:lang="ca">El NeoChat és un client de Matrix. Permet enviar missatges de text, fitxers de vídeo i d'àudio a la família, col·legues i amics usant el protocol Matrix.</p>
<p xml:lang="ca-valencia">NeoChat és un client de Matrix. Permet enviar missatges de text, fitxers de vídeo i d'àudio a la família, col·legues i amics utilitzant el protocol Matrix.</p>
<p xml:lang="de">NeoChat ist ein Matrix-Client. Er ermöglicht Ihnen das Senden von Textnachrichten, Videos und Audiodateien an Ihre Familie, Kollegen und Freunde unter Verwendung des Matrix-Protokolls.</p>
<p xml:lang="el">Το NeoChat είναι μια εφαρμογή του Matrix. Σας επιτρέπει να στέλνετε μηνύματα κειμένου, βίντεο και ήχο στην οικογένειά σας, σε συναδέλφους και φίλους με το πρωτόκολλο Matrix.</p>
<p xml:lang="en-GB">NeoChat is a Matrix client. It allows you to send text messages, videos and audio files to your family, colleagues and friends using the Matrix protocol.</p>
<p xml:lang="es">NeoChat es un cliente para Matrix. Le permite enviar mensajes de texto, vídeos y archivos de sonido a su familia, compañeros de trabajo y amigos usando el protocolo Matrix.</p>
<p xml:lang="eu">NeoChat Matrix bezero bat da. Familiari, lankideei eta lagunei testu-mezuak, bideoak eta audio-fitxategiak bidaltzeko aukera ematen du, Matrix protokoloa erabiliz.</p>
<p xml:lang="fi">NeoChat on Matrix-asiakas. Sillä voi lähettää perheelle, tuttaville ja kavereille tekstiviestejä sekä video- ja äänitiedostoja Matrix-yhteyskäytännöllä.</p>
<p xml:lang="fr">NeoChat est un client Matrix. Il vous permet d'envoyer des messages de texte, des vidéos et des fichiers audio à votre famille, vos collègues et vos amis en utilisant le protocole Matrix.</p>
<p xml:lang="hu">A NeoChat egy Matrix kliens. Szöveges üzeneteket, videókat ésaudio fájlokat küldhet családjának, kollégáinak és barátainak a Matrix protokoll használatával.</p>
<p xml:lang="ia">NeoChat es un cliente de Matrix. Illo te permitte inviar messager de texto, files de video e audio a tu familia, collegas e amicos usante le protocollo de Matrix.</p>
<p xml:lang="id">NeoChat adalah sebuah klien Matrix. Memungkinkan Anda untuk mengirim pesan teks, file video dan audio ke keluarga, kolega dan teman Anda menggunakan protokol Matrix.</p>
<p xml:lang="ie">NeoChat es un cliente de Matrix. On posse usar it por inviar missages textual, video- e audiofiles a su familie, colegos e amics med li protocol Matrix.</p>
<p xml:lang="it">NeoChat è un client Matrix. Ti consente di inviare messaggi di testo, file video e audio a familiari, colleghi e amici utilizzando il protocollo Matrix.</p>
<p>NeoChat is a client for Matrix, the decentralized communication protocol for instant messaging. It allows you to send text messages, videos and audio files to your family, colleagues and friends. It uses KDE frameworks and most notably Kirigami
to provide a convergent experience across multiple platforms.</p>
<p xml:lang="ar">نيوتشات هو عميل ماتركس Matrix، (ميفاق الاتصال اللامركزي للمراسلة الفورية). يتيح لك نيوتشات إرسال رسائل نصية ومقاطع فيديو وملفات صوتية إلى عائلتك وزملائك وأصدقائك. يستخدم أطر عمل كيدي وأبرزها Kirigami لتوفير تجربة متقاربة عبر منصات متعددة.</p>
<p xml:lang="ca">El NeoChat és un client de Matrix, el protocol descentralitzat de comunicacions de missatgeria instantània. Permet enviar missatges de text, fitxers de vídeo i d'àudio a la família, col·legues i amics. Fa servir els Frameworks de KDE i, sobretot, el Kirigami per a proporcionar una experiència convergent a través de diverses plataformes.</p>
<p xml:lang="ca-valencia">NeoChat és un client de Matrix, el protocol descentralitzat de comunicacions de missatgeria instantània. Permet enviar missatges de text, fitxers de vídeo i d'àudio a la família, col·legues i amics. Utilitza els Frameworks de KDE i, sobretot, Kirigami per a proporcionar una experiència convergent a través de diverses plataformes.</p>
<p xml:lang="en-GB">NeoChat is a client for Matrix, the decentralised communication protocol for instant messaging. It allows you to send text messages, videos and audio files to your family, colleagues and friends. It uses KDE frameworks and most notably Kirigami to provide a convergent experience across multiple platforms.</p>
<p xml:lang="es">NeoChat es un cliente para Matrix, el protocolo de comunicaciones descentralizado para mensajería instantánea. Le permite enviar mensajes de texto, vídeos y archivos de sonido a su familia, compañeros de trabajo y amigos. Usa la infraestructura de KDE y, en particular, Kirigami para proporcionar una experiencia convergente en muchas plataformas.</p>
<p xml:lang="fr">NeoChat est un client pour le protocole Matrix, un protocole décentralisé de communications pour messagerie instantané. Il vous permet d'envoyer des messages de texte, des vidéos et des fichiers audio à votre famille, vos collègues et vos amis. Il utilise les environnements de développement et plus précisément Kirigami pour fournir une expérience convergente sur plusieurs plate-formes. </p>
<p xml:lang="gl">NeoChat é un cliente para Matrix, o protocolo de comunicación descentralizada para mensaxería instantánea. Podes enviar mensaxes de texto, vídeos e ficheiros de son á túa familia, colegas e amizades. Usas infraestruturas de KDE e principalmente Kirigami para proporcionar unha experiencia de uso converxente para varias plataformas.</p>
<p xml:lang="ia">NeoChat es un cliente per Matrix, le protocollo de communication decentralisate per messager instantanee. Illo te permitte inviar messager de texto, files de video e audio a tu familia, collegas e amicos usante. Illo usa KDE frameworks e super toto Kirigamii forni un experientia convergente trans platteforme multiple.</p>
<p xml:lang="it">NeoChat è un client per Matrix, il protocollo di comunicazione decentralizzato per la messaggistica istantanea. Ti consente di inviare messaggi di testo, video e file audio a familiari, colleghi e amici. Utilizza i framework KDE e in particolare Kirigami per fornire un'esperienza convergente su più piattaforme.</p>
<p xml:lang="ka">NeoChat არის Matrix კლიენტი. ის საშუალებას გაძლევთ გაგზავნოთ ტექსტური შეტყობინებები, ვიდეოები და აუდიო ფაილები თქვენს ოჯახს, კოლეგებსა და მეგობრებს მატრიქსის პროტოკოლის გამოყენებით.</p>
<p xml:lang="ko">NeoChat은 Matrix 클라이언트입니다. Matrix 프로토콜을 사용하여 가족, 동료, 친구에게 텍스트 메시지, 동영상, 오디오 파일을 전송할 수 있습니다.</p>
<p xml:lang="nl">NeoChat is een Matrix-client. Het biedt u het verzenden van tekstberichten, video's en geluidsbestanden naar uw familie, collega's en vrienden met het Matrix-protocol.</p>
<p xml:lang="pl">NeoChat jest programem do Matrisa. Umożliwia wysyłanie wiadomości tekstowych, filmów oraz dźwięku do twojej rodziny, znajomych oraz przyjaciół poprzez protokół Matriksa.</p>
<p xml:lang="pt">O NeoChat é um cliente do Matrix. O mesmo permite-lhe enviar mensagens de texto, ficheiros de vídeo e áudio para a sua família, colegas e amigos com o protocolo Matrix.</p>
<p xml:lang="pt-BR">O NeoChat é um cliente Matrix. Ele permite a você enviar mensagens de texto, arquivos de vídeo e áudio para seus familiares, colegas e amigos usando o protocolo Matrix.</p>
<p xml:lang="ru">NeoChat — это клиент, поддерживающий работу с протоколом Matrix. Он позволяет отправлять текстовые сообщения, видео и аудиофайлы.</p>
<p xml:lang="sk">NeoChat je Matrix klient. Umožňuje vám posielať textové správy, videá a zvukové súbory rodine, kolegom a priateľom pomocou protokolu Matrix.</p>
<p xml:lang="sl">NeoChat je odjemalec Matrixa. Dovoljuje vam pošiljanje besedilnih sporočil, videoposnetkov in zvočnih datotek vaši družini, kolegom in prijateljem z uporabo protokola Matrix.</p>
<p xml:lang="sv">NeoChat är en Matrix-klient. Den låter dig skicka textmeddelanden, videor och ljudfiler till din familj, kollegor och vänner med användning av Matrix-protokollet.</p>
<p xml:lang="tr">NeoChat, bir Matrix istemcisidir. Matrix protokolünü kullanarak ailenize, iş arkadaşlarınıza, arkadaşlarınıza ve başkalarına metin iletileri, video ve ses dosyaların göndermenize olanak verir.</p>
<p xml:lang="uk">NeoChat — клієнт мережі обміну повідомленнями Matrix. За допомогою цієї програми ви зможете надсилати текстові повідомлення, відео та звукові файли вашій родині, колегам та друзям за допомогою протоколу Matrix.</p>
<p xml:lang="x-test">xxNeoChat is a Matrix client. It allows you to send text messages, videos and audio files to your family, colleagues and friends using the Matrix protocol.xx</p>
<p xml:lang="zh-CN">NeoChat 是一个 Matrix 客户端。 它允许您使用 Matrix 协议向您的家人、同事和朋友发送文本消息、视频和音频文件。</p>
<p>Matrix is a decentralized communication protocol, putting the user back in control. Currently NeoChat implements large part of the protocol with the exception of encrypted chats and video chat.</p>
<p xml:lang="ar">ماتريكس هو بروتوكول اتصال لامركزي ، يعيد المستخدم إلى السيطرة. يطبق نيوتشات حاليًا جزءًا كبيرًا من الميفاق باستثناء الدردشات المشفرة ودردشة الفيديو.</p>
<p xml:lang="az">Matrix, istifadəçini nəzarətdə saxlayan, mərkəzləşməmişi rabitə protokoludur. NeoChat, söhbətin və video əlaqəsinin şifrələnməsindən başqa bir çox protokolları həyata keçirə bilir.</p>
<p xml:lang="ca">Matrix és un protocol de comunicacions descentralitzat, que retorna el control a l'usuari. Actualment el NeoChat implementa una gran part del protocol amb l'excepció dels xats encriptats i els xats de vídeo.</p>
<p xml:lang="ca-valencia">Matrix és un protocol de comunicacions descentralitzat, que retorna el control a l'usuari. Actualment NeoChat implementa una gran part del protocol amb l'excepció dels xats encriptats i els xats de vídeo.</p>
<p xml:lang="de">Matrix ist ein dezentralisiertes Kommunikationsprotokoll, das dem Benutzer wieder die Kontrolle zurückgibt. Derzeit implementiert NeoChat einen großen Teil des Protokolls mit der Ausnahme von verschlüsselten Chats und Video-Chat.</p>
<p xml:lang="el">Το Matrix είναι ένα αποκεντρωμένο πρωτόκολλο επικοινωνίας, δίνοντας πίσω στον χρήστη τον έλεγχο. Προς το παρόν το NeoChat υλοποιεί ένα μεγάλο μέρος του πρωτοκόλλου με εξαίρεση τις κρυπτογραφημένες συνομιλίες και τη συνομιλία με βίντεο.</p>
<p xml:lang="en-GB">Matrix is a decentralised communication protocol, putting the user back in control. Currently NeoChat implements large part of the protocol with the exception of encrypted chats and video chat.</p>
<p xml:lang="es">Matrix es un protocolo de comunicaciones descentralizado, que devuelve el control al usuario. En la actualidad, NeoChat implementa gran parte del protocolo con la excepción de chats cifrados y chats de vídeo.</p>
<p xml:lang="eu">Matrix komunikazio-protokolo deszentralizatu bat da, erabiltzaileari kontrola itzultzen diona. Gaur egun, NeoChat-ek protokoloaren zati handi bat inplementatzen du, berriketa zifratuak eta bideo berriketak izan ezik.</p>
<p xml:lang="fi">Matrix on hajautettu viestintäyhteyskäytäntö, joka antaa hallinnan takaisin käyttäjille. NeoChat tarjoaa nykyisellään valtaosan yhteyskäytännöstä salattuja keskustelu- ja videokeskusteluja lukuun ottamatta.</p>
<p xml:lang="fr">Matrix est un protocole de communication décentralisé, donnant le contrôle à l'utilisateur. Actuellement, NeoChat met en œuvre une grande partie du protocole, à l'exception des discussions chiffrées et du chat vidéo.</p>
<p xml:lang="hu">A Matrix egy decentralizált kommunikációs protokoll, amely a felhasználók kezébe adja az irányítást.</p>
<p xml:lang="ia">Matrix es un protocollo de communication decentrate, ponente le usator in le controlo. Currentemente NeoChat implementa un grande parte del protocollo con le exception de conversationes cryptate e conversationes video.</p>
<p xml:lang="id">Matrix adalah protokol komunikasi terdesentralisasi, menempatkan pengguna kembali dalam kendali. Saat ini NeoChat mengimplementasikan sebagian besar protokol dengan pengecualian obrolan terenkripsi dan obrolan video.</p>
<p xml:lang="ie">Matrix es un decentralisat protocol de communication quel retroda li control a un usator. Actualmen, NeoChat implementa un grand parte del protocol except ciffrat conversationes e videotelefonada.</p>
<p xml:lang="it">Matrix è un protocollo di comunicazione decentralizzato, che restituisce all'utente il controllo. Attualmente NeoChat implementa gran parte del protocollo ad eccezione delle chat cifrate e delle chat video.</p>
<p xml:lang="ka">Matrix -ი დეცენტრალიზებული კომუნიკაციის პროტოკოლია, რომელიც მომხმარებელს კონტროლის უფლებას უბრუნებს. ამჟამად NeoChat-ს პროტოკოლის ძირითადი ნაწილის მხარდაჭერა გააჩნია, დაშიფვრისა და ვიდეოჩატის გამოკლებით.</p>
<p xml:lang="ko">Matrix는 사용자에게 제어권을 돌려 주는 분산 통신 프로토콜입니다. NeoChat은 암호화된 대화 및 영상 통화를 제외한 프로토콜의 대부분 기능을 구현합니다.</p>
<p xml:lang="nl">Matrix is een gedecentraliseerd communicatieprotocol, dat de gebruiker de controle teruggeeft. Op dit moment implementeert NeoChat grote delen van het protocol met de uitzondering van versleutelde chats en video-chat.</p>
<p xml:lang="pl">Matrix jest protokołem rozproszonego porozumiewania się oddający użytkownikowi jego władzę. Obecnie NeoChat obsługuje dużą część protokołu poza szyfrowanymi rozmowami tekstowymi i z obrazem.</p>
<p xml:lang="pt">O Matrix é um protocolo de comunicações descentralizado, colocando de novo o utilizador no poder. De momento, o NeoChat implementa uma boa parte do protocolo, com a excepção das conversas encriptadas e as conversas de vídeo.</p>
<p xml:lang="pt-BR">O Matrix é um protocolo de comunicação descentralizado, colocando o usuário de volta no controle. Atualmente o NeoChat implementa grande parte do protocolo com a exceção de bate-papos criptografados e bate-papo por vídeo.</p>
<p xml:lang="ru">Matrix — это децентрализованный коммуникационный протокол, возвращающий пользователю контроль над своими данными. В настоящее время в приложении NeoChat реализована поддержка большей части протокола, за исключением зашифрованных чатов и видеочата.</p>
<p xml:lang="sk">Matrix je decentralizovaný komunikačný protokol, ktorý používateľovi vracia kontrolu. V súčasnosti NeoChat implementuje veľkú časť protokolu s výnimkou šifrovaných chatov a videohovorov.</p>
<p xml:lang="sl">Matrix je decentraliziran komunikacijski protokol, kjer ima uporabnik uporabnik kontrolo rabe. Trenutno ima NeoChat izveden velik del protokola z izjemo šifriranih klepetov in video klepetov.</p>
<p xml:lang="sv">Matrix är ett decentraliserat kommunikationsprotokoll, som ger tillbaka kontrollen till användaren. För närvarande implementerar NeoChat en stor del av protokollet, med undantag för krypterad chatt och videochatt.</p>
<p xml:lang="tr">Matrix; tam denetimi kullanıcıya bırakan, merkezi olmayan bir iletişim protokolüdür. Şu anda NeoChat, uçtan uca şifrelenmiş metin ve video sohbetleri dışında protokolün büyük bir bölümünü bünyesinde bulundurur.</p>
<p xml:lang="uk">Matrix — протокол децентралізованого спілкування, який передає контроль над даними користувачеві. У поточній версії NeoChat реалізовано більшу частину протоколу, окрім зашифрованого спілкування та відеоспілкування.</p>
<p xml:lang="x-test">xxMatrix is a decentralized communication protocol, putting the user back in control. Currently NeoChat implements large part of the protocol with the exception of encrypted chats and video chat.xx</p>
<p xml:lang="zh-CN">Matrix 是一个分布式通讯协议,使用户重新得到控制权。 目前NeoChat 实现了协议的大部分,除了加密聊天和视频聊天。</p>
<p>NeoChat works both on mobile and desktop while providing a consistent user experience.</p>
<p xml:lang="ar">يعمل نيوتشات على كل من الأجهزة المحمولة وسطح المكتب مع توفير تجربة مستخدم متسقة.</p>
<p xml:lang="az">Vahid istifadəçi interfeysi ilə təmin olunan NeoChat, həm mobil telefonda həm də kompyuterlərdə işləyir.</p>
<p xml:lang="ca">El NeoChat funciona en els mòbils i a l'escriptori, proporcionant una experiència d'usuari coherent.</p>
<p xml:lang="ca-valencia">NeoChat funciona en els mòbils i en l'escriptori, proporcionant una experiència d'usuari coherent.</p>
<p xml:lang="de">NeoChat funktioniert sowohl auf Mobilgeräten als auch auf dem PC und bietet ein einheitliches Benutzererlebnis.</p>
<p xml:lang="el">Το NeoChat λειτουργεί και στα κινητά και στους υπολογιστές γραφείου παρέχοντας μια αδιάλειπτη εμπειρία χρήσης.</p>
<p xml:lang="en-GB">NeoChat works both on mobile and desktop while providing a consistent user experience.</p>
<p xml:lang="es">NeoChat funciona en móviles y en el escritorio a la vez que proporciona una experiencia de usuario consistente.</p>
<p xml:lang="eu">NeoChat mugikorretan eta mahaigainean dabil, erabiltzaile esperientzia koherentea eskainiz.</p>
<p xml:lang="fi">NeoChat toimii sekä mobiili- että työpöytäalustoilla tarjoten yhdenmukaisen käyttökokemuksen.</p>
<p xml:lang="fr">NeoChat fonctionne aussi bien sur les mobiles que sur les ordinateurs de bureau, tout en offrant une expérience utilisateur cohérente.</p>
<p xml:lang="hu">A NeoChat mobilon és asztali számítógépen is működik, egységes felhasználói élményt nyújtva.</p>
<p xml:lang="ia">NeoChat functiona sia sur mobile que ur scriptorio durante que forni un experientia de usator consistente.</p>
<p xml:lang="id">NeoChat berfungsi baik di ponsel dan desktop sambil memberikan pengalaman pengguna yang konsisten.</p>
<p xml:lang="ie">NeoChat supporta amb computatores e aparates mobil, ancor providente un consistent experientie de usator.</p>
<p xml:lang="it">NeoChat funziona sia su dispositivi mobili che desktop, fornendo un'esperienza utente coerente.</p>
<p xml:lang="ka">NeoChat მუშაობს როგორც მობილურ, ისე ჩვეულებრივ კომპიუტერებზე იმ დროს, როცა მომხმარებლის ინტერფეისი არ იცვლება.</p>
<p xml:lang="ko">NeoChat은 모바일과 데스크톱 모두에서 일관된 사용자 경험을 제공합니다.</p>
<p xml:lang="nl">NeoChat werkt zowel op de mobiel en het bureaublad met het leveren van een consistente gebruikerservaring.</p>
<p xml:lang="pl">NeoChat działa zarówno na urządzeniach przenośnych jak i biurkowych, zapewniając spójne wrażenia użytkownika</p>
<p xml:lang="pt">O NeoChat funciona tanto em dispositivos móveis como no computador, fornecendo uma experiência de utilizador consistente.</p>
<p xml:lang="pt-BR">O NeoChat funciona tanto no celular como no computador enquanto fornece uma experiência consistente ao usuário.</p>
<p xml:lang="ru">NeoChat работает как на мобильных устройствах, так и на настольных компьютерах, обеспечивая единый пользовательский интерфейс.</p>
<p xml:lang="sk">NeoChat funguje na mobilných aj stolových počítačoch a poskytuje konzistentný používateľský zážitok.</p>
<p xml:lang="sl">NeoChat deluje tako na mobilnih kot na namiznih platformah z zagotavljanjem konsistentne uporabniške izkušnje.</p>
<p xml:lang="sv">NeoChat fungerar både på mobil och skrivbord och tillhandahåller en konsekvent användarupplevelse.</p>
<p xml:lang="tr">NeoChat, hem masaüstü hem de taşınabilir ortamlarda çalışarak tutarlı bir kullanıcı deneyimi sunar.</p>
<p xml:lang="uk">NeoChat працює на мобільних пристроях та звичайних комп'ютерах, маючи однорідний інтерфейс на усіх підтримуваних пристроях.</p>
<p xml:lang="x-test">xxNeoChat works both on mobile and desktop while providing a consistent user experience.xx</p>
<p xml:lang="zh-CN">NeoChat 在移动设备和桌面上均可用,并提供一致的用户体验。</p>
<p xml:lang="nl">NeoChat is een client voor Matrix, het gedecentraliseerde communicatieprotocol voor instant messages. Het biedt u het verzenden van tekstberichten, video's en geluidsbestanden naar uw familie, collega's en vrienden. Het gebruik KDE frameworks en het meest opmerkelijk Kirigami om een convergente ervaring te leveren op meerdere platforms.</p>
<p xml:lang="pl">NeoChat jest programem do Matriksa, protokołu rozproszonego porozumiewania się w czasie rzeczywistym. Umożliwia wysyłanie wiadomości tekstowych, filmów oraz dźwięku do twojej rodziny, znajomych oraz przyjaciół. Używa szkieletów KDE i głównie Kirigami, aby zapewnić spójne wrażenia na wielu platformach</p>
<p xml:lang="pt">O NeoChat é um cliente do Matrix. O mesmo permite-lhe enviar mensagens de texto, ficheiros de vídeo e áudio para a sua família, colegas e amigos com o protocolo Matrix. Usa as plataformas do KDE, e principalmente o Kirigami, para oferecer uma experiência convergente entre várias plataformas.</p>
<p xml:lang="sl">Neochat je odjemalec za Matrix, decentralizirani komunikacijski protokol za takojšnje sporočanje. Omogoča vam pošiljanje besedilnih sporočil, videoposnetkov in zvočnih datotek svoji družini, sodelavcem in prijateljem. Uporablja okvire ogrodje KDE frameworks in predvsem Kirigami za zagotavljanje konvergentne izkušnje na več platformah.</p>
<p xml:lang="tr">NeoChat, anlık iletileşme için merkezi olmayan iletişim protokolü olan Matrix için bir istemcidir. Ailenize, iş arkadaşlarınıza ve arkadaşlarınıza metin iletiler, videolar ve ses dosyaları göndermenize olanak tanır. Birden çok platformda yakınsak bir deneyim sağlamak için KDE Frameworks ve en önemlilerinden Kirigami'yi kullanır.</p>
<p xml:lang="uk">NeoChat — клієнт Matrix, децентралізованого протоколу спілкування для миттєвого обміну повідомленнями. За його допомогою ви можете надсилати текстові повідомлення, відео та звукові файли вашій родин, колегами та друзям. У програмі використано бібліотеки KDE, зокрема Kirigami, для надання однорідного середовища на декількох програмних та апаратних платформах.</p>
<p xml:lang="x-test">xxNeoChat is a client for Matrix, the decentralized communication protocol for instant messaging. It allows you to send text messages, videos and audio files to your family, colleagues and friends. It uses KDE frameworks and most notably Kirigami to provide a convergent experience across multiple platforms.xx</p>
<p>NeoChat aims to be a fully featured application for the Matrix specification. As such everything in the current stable specification with the notable exceptions of VoIP, threads and some aspects of End-to-End Encryption are supported. There are a few other smaller omissions due to the fact that the Matrix spec is constantly evolving but the aim remains to provide eventual support for the entire spec.</p>
<p xml:lang="ar">يهدف نيوتشات إلى أن يكون تطبيقًا كامل الميزات لمواصفات ماتركس. على هذا النحو يتم دعم كل شيء في المواصفات المستقرة الحالية مع الاستثناءات الملحوظة لـ VoIP والخيوط وبعض جوانب التشفير من طرف إلى طرف. هناك عدد قليل من الإغفالات الصغيرة الأخرى بسبب حقيقة أن مواصفات ماتركس تتطور باستمرار ، ولكن يبقى الهدف توفير الدعم النهائي للمواصفات بأكملها.</p>
<p xml:lang="ca">NeoChat pretén ser una aplicació amb totes les característiques per a l'especificació de Matrix. Com a tal, s'ha implementat tota l'especificació actual estable amb les notables excepcions de la VoIP, fils i alguns aspectes de l'encriptatge d'extrem a extrem. Hi ha algunes altres omissions més petites a causa del fet que l'especificació de Matrix està evolucionant constantment, però l'objectiu segueix sent proporcionar suport eventual per a tota l'especificació.</p>
<p xml:lang="ca-valencia">NeoChat pretén ser una aplicació amb totes les característiques per a l'especificació de Matrix. Com a tal, s'ha implementat tota l'especificació actual estable amb les notables excepcions de VoIP, fils i alguns aspectes de l'encriptació d'extrem a extrem. Hi ha algunes altres omissions més xicotetes a causa del fet que l'especificació de Matrix està evolucionant constantment, però l'objectiu seguix sent proporcionar suport eventual per a tota l'especificació.</p>
<p xml:lang="en-GB">NeoChat aims to be a fully featured application for the Matrix specification. As such everything in the current stable specification with the notable exceptions of VoIP, threads and some aspects of End-to-End Encryption are supported. There are a few other smaller omissions due to the fact that the Matrix spec is constantly evolving but the aim remains to provide eventual support for the entire spec.</p>
<p xml:lang="es">NeoChat pretende ser una aplicación con todas las funciones para la especificación de Matrix. Como tal, admite todo en la especificación estable actual, con las notables excepciones de VoIP, subprocesos y algunas funciones de cifrado de extremo a extremo. Existen algunas omisiones menos importantes debido al hecho de que la especificación de Matrix está en constante evolución, pero el objetivo sigue siendo brindar compatibilidad final con toda la especificación.</p>
<p xml:lang="fr">L'objectif de NeoChat est d'être une application complète pour le protocole Matrix. En tant que tel, tout dans la spécification stable actuelle avec les exceptions notables de VoIP, les processus et certains aspects du chiffrement de bout en bout sont pris en charge. Il y a quelques autres petites omissions en raison du fait que la spécification du protocole Matrix est en constante évolution. Cependant, l'objectif reste de fournir un soutien éventuel pour l'ensemble de la spécification.</p>
<p xml:lang="gl">NeoChat pretende ser unha aplicación completa para a especificación de Matrix. Coas excepcións de VoIP, conversas fiadas e algúns aspectos da cifraxe de extremo a extremo, a versión estábel segue as especificacións. Existen algunhas outras pequenas omisións debido ao feito de que Matrix está en continua evolución pero a intención é implementar a especificación completa.</p>
<p xml:lang="ia">NeoChat aspira a esser un application plenemente eminente per le specification de Matrix. Tal como omne cosas in le specification currentemente stabile con le exceptiones notabile de VOIP, threads e alcun aspectos del cryptation End-to-End es supportate. Il ha ltere pauc omissiones, debite al facto que le specification de Matrix es in evolution constante ma le aspiration remane a fornir supporto eventual per le integre specification.</p>
<p xml:lang="it">NeoChat mira ad essere un'applicazione completa per le specifiche Matrix. Pertanto, sono supportati tutti gli elementi dell'attuale specifica stabile con le notevoli eccezioni di VoIP, conversazioni e alcuni aspetti della cifratura end-to-end. Ci sono alcune altre piccole omissioni dovute al fatto che le specifiche Matrix sono in continua evoluzione, ma l'obiettivo rimane quello di fornire un eventuale supporto per l'intera specifica.</p>
<p xml:lang="ka">NeoChat-ი მიზნად ისახავს Matrix სპეციფიკაციის სრული განხორციელება ჰქონდეს. როგორც ასეთი, ყველაფერი მიმდინარე სპეციფიკაციიდან, VoIP-ის, ძაფებისა და გამჭოლი დაშიფვრის ზოგიერთი ასპექტის გარდა, მხარდაჭერილია. შეძლება ასევე იყოს მცირე ლაფსუსებიც იმის გამო, რომ Matrix-ის სპეციფიკაცია მუდმივად ვითარგდება, მაგრამ ჩვენი მიზანი მისი სრული მხარდაჭერაა.</p>
<p xml:lang="nl">NeoChat richt zich op het volledig bieden van alle mogelijkheden van de Matrix-specificatie. Alles in de huidige stabiele specificatie met merkbare uitzondering van VoIP, gekoppelde discussies en sommige aspecten van eind-tot-eind versleuteling worden ondersteund. Er zijn een paar andere kleinere omissies vanwege het feit dat de Matrix specificatie constant evolueert maar het doel blijft het eventueel bieden van ondersteuning van de gehele specificatie.</p>
<p xml:lang="pl">NeoChat w zamyśle ma być pełnowartościową aplikacją wg wytycznych Matriksa. Z tego powodu, wszystko, co jest obecnie w stabilnych wytycznych z pominięciem VoIP, wątków i niektórych części szyfrowania Użytkownik-do-Użytkownika są obecnie obsługiwane. Pominięto też kilka mniejszych rzeczy ze względu na ciągły rozwój wytycznych Matriksa, lecz celem nadal jest zapewnienie obsługi wszystkich wytycznych.</p>
<p xml:lang="pt">O NeoChat pretende ser uma aplicação completa para a especificação do Matrix. Como tal, tudo o que existe na especificação estável actual, com as notáveis excepções do VoIP, tópicos e alguns aspectos da Encriptação Ponto-a-Ponto, são suportados. Existem mais algumas omissões, devido ao facto que a norma do Matrix está em constante evolução, mas o objectivo continua a ser oferecer o suporte eventual para a norma por inteiro.</p>
<p xml:lang="sl">Neochat cilja, da bi bila popolna aplikacija po specifikaciji Matrixa. Kot takšna vsebuje vse v trenutni stabilni specifikaciji z pomembnimi izjemami pri VoIP, nitih in nekaterih vidikov šifriranja od konca do konca. Obstaja nekaj drugih manjših opustitev zaradi dejstva, da se specifikacija Matrix nenehno razvija, vendar cilj ostaja zagotoviti morebitno podporo celotni specifikaciji.</p>
<p xml:lang="tr">NeoChat, Matrix belirtimi için tam özellikli bir uygulama olmayı hedefler. Bu nedenle; VoIP, ileti zincirleri ve Uçtan Uca Şifreleme'nin bazı yönleri gibi dikkate değer istisnalar dışında var olan kararlı belirtimdeki her şey desteklenir. Matrix belirtiminin sürekli gelişmesi nedeniyle birkaç küçük eksiklik daha var; ancak amaç tüm belirtim için nihai destek sağlamak olmayı sürdürüyor.</p>
<p xml:lang="uk">Метою створення NeoChat є повноцінна реалізація програми для специфікації Matrix. Як наслідок, реалізовано усе у поточній стабільній специфікації, окрім голосового інтернет-зв'язку, потоків та деяких аспектів міжвузлового шифрування. Є також декілька інших незначних прогалин через те, що специфікація Matrix постійно змінюється, але метою лишається повна підтримка специфікації.</p>
<p xml:lang="x-test">xxNeoChat aims to be a fully featured application for the Matrix specification. As such everything in the current stable specification with the notable exceptions of VoIP, threads and some aspects of End-to-End Encryption are supported. There are a few other smaller omissions due to the fact that the Matrix spec is constantly evolving but the aim remains to provide eventual support for the entire spec.xx</p>
<p>Due to the nature of the Matrix specification development NeoChat also supports numerous unstable features. Currently these are:</p>
<p xml:lang="ar">نظرًا لطبيعة تطوير مواصفات ماتركس، يدعم نيوتشات أيضًا العديد من الميزات غير المستقرة وهي:</p>
<p xml:lang="ca">A causa de la naturalesa del desenvolupament de l'especificació de Matrix, el NeoChat també implementa nombroses característiques inestables. Actualment són:</p>
<p xml:lang="ca-valencia">A causa de la naturalea del desenvolupament de l'especificació de Matrix, NeoChat també implementa nombroses característiques inestables. Actualment són:</p>
<p xml:lang="en-GB">Due to the nature of the Matrix specification development NeoChat also supports numerous unstable features. Currently these are:</p>
<p xml:lang="es">Debido a la naturaleza del desarrollo de la especificación de Matrix, NeoChat también permite numerosas funciones no estables, como:</p>
<p xml:lang="fr">En raison de la nature du développement des spécifications du protocole Matrix, NeoChat prend également en charge de nombreuses fonctionnalités instables. Actuellement, ce sont :</p>
<p xml:lang="gl">Debido á natureza do desenvolvemento da especificación de Matrix, NeoChat tamén inclúe varias funcionalidades non estábeis:</p>
<p xml:lang="ia">Debite al natura del disveloppamento de specification de Matrix NeoChat tamben supporta numerose characteristicas instabile. Currentemente istes es:</p>
<p xml:lang="it">A causa della natura dello sviluppo delle specifiche Matrix, NeoChat supporta anche numerose funzionalità instabili. Attualmente queste sono:</p>
<p xml:lang="ka">Matrix-ის სპეციფიკაციის განვითარების ბუნების გამო NeoChat-ს ასევე აქვს უამრავი არასტაბილური ფუნქციაც. ახლა ისინია:</p>
<p xml:lang="nl">Vanwege de aard van de ontwikkeling van de Matrix specificatie ondersteunt NeoChat ook talloze onstabiele mogelijkheden. Dit zijn nu:</p>
<p xml:lang="pl">Ze względu na sposób rozwoju Matriksa, NeoChat obsługuje także kilka niestabilnych możliwości. Obecnie są to:</p>
<p xml:lang="pt">Devido à natureza do desenvolvimento da especificação do Matrix, o NeoChat também suporta diversas funcionalidades instáveis. De momento são:</p>
<p xml:lang="sl">Zaradi narave razvoja specifikacije Matrixa NeoChat podpira tudi številne nestabilne zmožnosti. Trenutno so to:</p>
<p xml:lang="tr">NeoChat, Matrix belirtimi geliştirmesinin doğası gereği çok sayıda kararsız özelliği de destekler. Şu anda bunlar:</p>
<p xml:lang="uk">Через природу розробки специфікації Matrix, у NeoChat також передбачено підтримку численних нестабільних можливостей. У поточній версії цими можливостями є:</p>
<p xml:lang="x-test">xxDue to the nature of the Matrix specification development NeoChat also supports numerous unstable features. Currently these are:xx</p>
<ul>
<li>Polls - MSC3381</li>
<li xml:lang="ar">التصويت - MSC3381</li>
<li xml:lang="ca">Enquestes - MSC3381</li>
<li xml:lang="ca-valencia">Enquestes - MSC3381</li>
<li xml:lang="en-GB">Polls - MSC3381</li>
<li xml:lang="es">Encuestas - MSC3381</li>
<li xml:lang="fr">Sondages - MSC3381</li>
<li xml:lang="gl">Enquisas - MSC3381</li>
<li xml:lang="ia">Inquestas - MSC3381</li>
<li xml:lang="it">Sondaggi - MSC3381</li>
<li xml:lang="ka">Polls - MSC3381</li>
<li xml:lang="nl">Polls - MSC3381</li>
<li xml:lang="pt">Inquéritos - MSC3381</li>
<li xml:lang="sl">Polls - MSC3381</li>
<li xml:lang="ta">வாக்கெடுப்புகள் - MSC3381</li>
<li xml:lang="tr">Anketler - MSC3381</li>
<li xml:lang="uk">Опитування - MSC3381</li>
<li xml:lang="x-test">xxPolls - MSC3381xx</li>
<li>Sticker Packs - MSC2545</li>
<li xml:lang="ar">حزم الملصقات - MSC2545</li>
<li xml:lang="ca">Paquets d'adhesius - MSC2545</li>
<li xml:lang="ca-valencia">Paquets d'adhesius - MSC2545</li>
<li xml:lang="en-GB">Sticker Packs - MSC2545</li>
<li xml:lang="es">Paquetes de pegatinas - MSC2545</li>
<li xml:lang="fr">Paquets d'auto-collants - MSC2545</li>
<li xml:lang="gl">Paquetes de adhesivos - MSC2545</li>
<li xml:lang="ia">Etiquetta gummate (sticker) -MSC2545</li>
<li xml:lang="it">Pacchetti di adesivi - MSC2545</li>
<li xml:lang="ka">სტიკერების პაკეტები - MSC2545</li>
<li xml:lang="nl">Sticker Packs - MSC2545</li>
<li xml:lang="pt">Pacotes de Autocolantes - MSC2545</li>
<li xml:lang="sl">Sticker Packs - MSC2545</li>
<li xml:lang="ta">ஒட்டி தொகுப்புகள் - MSC2545</li>
<li xml:lang="tr">Yapışkan Paketleri - MSC2545</li>
<li xml:lang="uk">Пакунки наліпок - MSC2545</li>
<li xml:lang="x-test">xxSticker Packs - MSC2545xx</li>
<li>Location Events - MSC3488</li>
<li xml:lang="ar">موقع الأحداث - MSC3488</li>
<li xml:lang="ca">Esdeveniments d'ubicació - MSC3488</li>
<li xml:lang="ca-valencia">Esdeveniments d'ubicació - MSC3488</li>
<li xml:lang="en-GB">Location Events - MSC3488</li>
<li xml:lang="es">Eventos de ubicación - MSC3488</li>
<li xml:lang="fr">Événements de lieu - MSC3488</li>
<li xml:lang="gl">Localización de eventos - MSC3488</li>
<li xml:lang="ia">Eventos de Location - MSC3488</li>
<li xml:lang="it">Località eventi - MSC3488</li>
<li xml:lang="ka">მდებარეობის მოვლენები - MSC3488</li>
<li xml:lang="nl">Locatie gebeurtenissen - MSC3488</li>
<li xml:lang="pt">Eventos com Localizações - MSC3488</li>
<li xml:lang="sl">Location Events - MSC3488</li>
<li xml:lang="ta">இட நிகழ்வுகள் - MSC3488</li>
<li xml:lang="tr">Konum Etkinlikleri - MSC3488</li>
<li xml:lang="uk">Місцеві зустрічі - MSC3488</li>
<li xml:lang="x-test">xxLocation Events - MSC3488xx</li>
</ul>
</description>
<url type="homepage">https://apps.kde.org/neochat/</url>
<url type="bugtracker">https://bugs.kde.org/buglist.cgi?component=General&amp;product=NeoChat</url>
@@ -191,6 +212,7 @@
<developer_name xml:lang="eu">KDE komunitatea</developer_name>
<developer_name xml:lang="fi">KDE-yhteisö</developer_name>
<developer_name xml:lang="fr">La communauté de KDE</developer_name>
<developer_name xml:lang="gl">A comunidade KDE</developer_name>
<developer_name xml:lang="hu">A KDE Közösség</developer_name>
<developer_name xml:lang="ia">Le communitate de KDE</developer_name>
<developer_name xml:lang="id">Komunitas KDE</developer_name>
@@ -208,6 +230,7 @@
<developer_name xml:lang="sk">KDE Komunita</developer_name>
<developer_name xml:lang="sl">Skupnost KDE</developer_name>
<developer_name xml:lang="sv">KDE-gemenskapen</developer_name>
<developer_name xml:lang="ta">கே.டீ.யீ. சமூகம்</developer_name>
<developer_name xml:lang="tr">KDE Topluluğu</developer_name>
<developer_name xml:lang="uk">Спільнота KDE</developer_name>
<developer_name xml:lang="x-test">xxThe KDE Communityxx</developer_name>
@@ -217,6 +240,7 @@
<custom>
<value key="KDE::matrix">#neochat:kde.org</value>
<value key="KDE::windows_store">https://www.microsoft.com/store/apps/9PNXWVNRC29H</value>
<value key="KDE::mastodon">https://kde.social/@neochat</value>
</custom>
<launchable type="desktop-id">org.kde.neochat.desktop</launchable>
<screenshots>
@@ -231,8 +255,17 @@
<content_attribute id="social-chat">intense</content_attribute>
</content_rating>
<releases>
<release version="23.04.2" date="2023-06-08"/>
<release version="23.04.1" date="2023-05-11"/>
<release version="23.04.0" date="2023-04-20"/>
<release version="23.04.0" date="2023-04-20">
<artifacts>
<artifact type="binary" platform="x86_64-windows-msvc">
<location>https://download.kde.org/stable/release-service/23.04.0/windows/neochat-23.04.0-512-windows-cl-msvc2019-x86_64.exe</location>
<checksum type="sha256">85e17fdd9b128bfdd171a93b11f7a95febeff0a00df9261df11f6ff67637686d</checksum>
<size type="download">58032464</size>
</artifact>
</artifacts>
</release>
<release version="23.01" date="2023-01-30">
<url>https://plasma-mobile.org/2023/01/30/january-blog-post/</url>
<description>

View File

@@ -15,6 +15,7 @@ Name[es]=NeoChat
Name[eu]=NeoChat
Name[fi]=NeoChat
Name[fr]=NeoChat
Name[gl]=NeoChat
Name[hu]=NeoChat
Name[ia]=Neochat
Name[id]=NeoChat
@@ -52,6 +53,7 @@ GenericName[es]=Cliente para Matrix
GenericName[eu]=Matrix bezeroa
GenericName[fi]=Matrix-asiakas
GenericName[fr]=Client « Matrix »
GenericName[gl]=Cliente de Matrix
GenericName[hu]=Matrix kliens
GenericName[ia]=Cliente de Matrice
GenericName[id]=Klien Matrix
@@ -88,6 +90,7 @@ Comment[es]=Cliente para el protocolo Matrix
Comment[eu]=Matrix protokolorako bezeroa
Comment[fi]=Asiakas Matrix-yhteyskäytännölle
Comment[fr]=Client pour le protocole « Matrix »
Comment[gl]=Cliente para o protocolo Matrix
Comment[hu]=Kliens a Matrix protokollhoz
Comment[ia]=Cliente per le protocollo de Matrix
Comment[id]=Klien untuk protokol Matrix

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -15,6 +15,7 @@ add_library(neochat STATIC
models/messagefiltermodel.cpp
models/roomlistmodel.cpp
models/sortfilterspacelistmodel.cpp
models/accountemoticonmodel.cpp
spacehierarchycache.cpp
roommanager.cpp
neochatroom.cpp
@@ -24,17 +25,16 @@ add_library(neochat STATIC
models/publicroomlistmodel.cpp
models/userdirectorylistmodel.cpp
models/keywordnotificationrulemodel.cpp
models/emoticonfiltermodel.cpp
notificationsmanager.cpp
models/sortfilterroomlistmodel.cpp
chatdocumenthandler.cpp
models/devicesmodel.cpp
filetypesingleton.cpp
login.cpp
stickerevent.cpp
models/webshortcutmodel.cpp
blurhash.cpp
blurhashimageprovider.cpp
joinrulesevent.cpp
models/collapsestateproxymodel.cpp
urlhelper.cpp
windowcontroller.cpp
@@ -44,9 +44,31 @@ add_library(neochat STATIC
models/actionsmodel.cpp
models/serverlistmodel.cpp
models/statemodel.cpp
models/statefiltermodel.cpp
filetransferpseudojob.cpp
models/searchmodel.cpp
texthandler.cpp
logger.cpp
models/stickermodel.cpp
models/imagepacksmodel.cpp
events/imagepackevent.cpp
events/joinrulesevent.cpp
events/stickerevent.cpp
models/reactionmodel.cpp
delegatesizehelper.cpp
)
ecm_qt_declare_logging_category(neochat
HEADER "messageeventmodel_logging.h"
IDENTIFIER "MessageEvent"
CATEGORY_NAME "org.kde.neochat.messageeventmodel"
DEFAULT_SEVERITY Info
)
ecm_qt_declare_logging_category(neochat
HEADER "voip_logging.h"
IDENTIFIER "voip"
CATEGORY_NAME "org.kde.neochat.voip"
)
add_executable(neochat-app
@@ -60,11 +82,11 @@ target_link_libraries(neochat-app PRIVATE
neochat
)
if(Quotient_VERSION_MINOR GREATER 6)
if(Quotient${QUOTIENT_SUFFIX}_VERSION_MINOR GREATER 6)
target_compile_definitions(neochat PUBLIC QUOTIENT_07)
target_sources(neochat PRIVATE pollevent.cpp pollhandler.cpp)
target_sources(neochat PRIVATE events/pollevent.cpp pollhandler.cpp)
else()
target_compile_definitions(neochat PUBLIC QUOTIENT_VERSION=\"${Quotient_VERSION}\")
target_compile_definitions(neochat PUBLIC QUOTIENT_VERSION=\"${Quotient${QUOTIENT_SUFFIX}_VERSION}\")
target_sources(neochat PRIVATE neochataccountregistry.cpp)
endif()
@@ -94,7 +116,21 @@ else()
endif()
target_include_directories(neochat PRIVATE ${CMAKE_BINARY_DIR})
target_link_libraries(neochat PUBLIC Qt::Core Qt::Quick Qt::Qml Qt::Gui Qt::Multimedia Qt::Network Qt::QuickControls2 KF${QT_MAJOR_VERSION}::I18n KF${QT_MAJOR_VERSION}::Kirigami2 KF${QT_MAJOR_VERSION}::Notifications KF${QT_MAJOR_VERSION}::ConfigCore KF${QT_MAJOR_VERSION}::ConfigGui KF${QT_MAJOR_VERSION}::CoreAddons KF${QT_MAJOR_VERSION}::SonnetCore KF${QT_MAJOR_VERSION}::ItemModels Quotient cmark::cmark ${QTKEYCHAIN_LIBRARIES} QCoro::Core)
target_link_libraries(neochat PUBLIC Qt::Core Qt::Quick Qt::Qml Qt::Gui Qt::Multimedia Qt::Network Qt::QuickControls2 KF${QT_MAJOR_VERSION}::I18n KF${QT_MAJOR_VERSION}::Kirigami2 KF${QT_MAJOR_VERSION}::Notifications KF${QT_MAJOR_VERSION}::ConfigCore KF${QT_MAJOR_VERSION}::ConfigGui KF${QT_MAJOR_VERSION}::CoreAddons KF${QT_MAJOR_VERSION}::SonnetCore KF${QT_MAJOR_VERSION}::ItemModels Quotient${QUOTIENT_SUFFIX} cmark::cmark ${QTKEYCHAIN_LIBRARIES} QCoro::Core)
if (TARGET PkgConfig::GSTREAMER)
target_link_libraries(neochat PUBLIC PkgConfig::GSTREAMER)
target_sources(neochat PRIVATE
call/callmanager.cpp
call/callsession.cpp
call/audiosources.cpp
call/videosources.cpp
call/devicemonitor.cpp
models/callparticipantsmodel.cpp
call/callparticipant.cpp
)
target_compile_definitions(neochat PUBLIC GSTREAMER_AVAILABLE)
endif()
kconfig_add_kcfg_files(neochat GENERATE_MOC neochatconfig.kcfgc)
if(NEOCHAT_FLATPAK)
@@ -175,6 +211,10 @@ if(ANDROID)
"window-new"
"globe"
"visibility"
"home"
"preferences-desktop-notification"
"computer-symbolic"
"gps"
)
else()
target_link_libraries(neochat PUBLIC Qt::Widgets KF${QT_MAJOR_VERSION}::KIOWidgets)

View File

@@ -3,8 +3,6 @@
#include "actionshandler.h"
#include "controller.h"
#include <csapi/joining.h>
#include <events/roommemberevent.h>
@@ -13,13 +11,10 @@
#include <KLocalizedString>
#include <QStringBuilder>
#include "controller.h"
#include "models/actionsmodel.h"
#include "models/customemojimodel.h"
#include "neochatconfig.h"
#include "neochatroom.h"
#include "neochatuser.h"
#include "roommanager.h"
#include "texthandler.h"
using namespace Quotient;

View File

@@ -12,13 +12,31 @@
class CustomEmojiModel;
class NeoChatRoom;
/// \brief Handles user interactions with NeoChat (joining room, creating room,
/// sending message). Account management is handled by Controller.
/**
* @class ActionsHandler
*
* This class handles chat messages ready for posting to a room.
*
* Everything that needs to be done to prepare the message for posting in a room
* including:
* - File handling
* - User mentions
* - Quick edits
* - Chat actions
* - Custom emojis
*
* @note A chat action is a message starting with /, resulting in something other
* than a normal message being sent (e.g. /me, /join).
*
* @sa ActionsModel, NeoChatRoom
*/
class ActionsHandler : public QObject
{
Q_OBJECT
/// \brief The room that messages will be sent to.
/**
* @brief The room that messages will be sent to.
*/
Q_PROPERTY(NeoChatRoom *room READ room WRITE setRoom NOTIFY roomChanged)
public:

View File

@@ -5,6 +5,24 @@
#include <stdint.h>
/**
* @brief Returns the pixel array of the result image given the blurhash string.
*
* @param blurhash a string representing the blurhash to be decoded.
* @param width the width of the resulting image.
* @param height the height of the resulting image.
* @param punch the factor to improve the contrast, default = 1.
* @param nChannels the number of channels in the resulting image array, 3 = RGB, 4 = RGBA.
*
* @return A pointer to memory region where pixels are stored in (H, W, C) format.
*/
uint8_t *decode(const char *blurhash, int width, int height, int punch, int nChannels);
/**
* @brief Checks if the Blurhash is valid or not.
*
* @param blurhash a string representing the blurhash.
*
* @return A bool (true if it is a valid blurhash, else false).
*/
bool isValidBlurhash(const char *blurhash);

View File

@@ -5,9 +5,22 @@
#include <QQuickImageProvider>
/**
* @class BlurhashImageProvider
*
* A QQuickImageProvider for blurhashes.
*
* @sa QQuickImageProvider
*/
class BlurhashImageProvider : public QQuickImageProvider
{
public:
BlurhashImageProvider();
/**
* @brief Return an image for a given ID.
*
* @sa QQuickImageProvider::requestImage
*/
QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override;
};
};

99
src/call/audiosources.cpp Normal file
View File

@@ -0,0 +1,99 @@
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "audiosources.h"
#include <gst/gst.h>
#include <QDebug>
#include <QString>
#include "devicemonitor.h"
#include "neochatconfig.h"
int AudioSources::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return DeviceMonitor::instance().audioSources().size();
}
QVariant AudioSources::data(const QModelIndex &index, int role) const
{
if (index.row() >= DeviceMonitor::instance().audioSources().size()) {
return QVariant(QStringLiteral("DEADBEEF"));
}
if (role == TitleRole) {
return DeviceMonitor::instance().audioSources()[index.row()]->title;
}
return QVariant();
}
QHash<int, QByteArray> AudioSources::roleNames() const
{
return {
{TitleRole, "title"},
};
}
AudioSources::AudioSources()
: QAbstractListModel()
{
connect(&DeviceMonitor::instance(), &DeviceMonitor::audioSourceAdded, this, [this]() {
beginResetModel();
endResetModel();
Q_EMIT currentIndexChanged();
});
connect(&DeviceMonitor::instance(), &DeviceMonitor::audioSourceRemoved, this, [this]() {
beginResetModel();
endResetModel();
Q_EMIT currentIndexChanged();
});
}
GstDevice *AudioSources::currentDevice() const
{
const auto config = NeoChatConfig::self();
const QString name = config->microphone();
for (const auto &audioSource : DeviceMonitor::instance().audioSources()) {
if (audioSource->title == name) {
qDebug() << "WebRTC: microphone:" << name;
return audioSource->device;
}
}
return DeviceMonitor::instance().audioSources()[0]->device;
}
void AudioSources::setCurrentIndex(int index) const
{
if (DeviceMonitor::instance().audioSources().size() == 0) {
return;
}
NeoChatConfig::setMicrophone(DeviceMonitor::instance().audioSources()[index]->title);
NeoChatConfig::self()->save();
}
int AudioSources::currentIndex() const
{
const auto config = NeoChatConfig::self();
const QString name = config->microphone();
if (name.isEmpty()) {
return getDefaultDeviceIndex();
}
for (auto i = 0; i < DeviceMonitor::instance().audioSources().size(); i++) {
if (DeviceMonitor::instance().audioSources()[i]->title == name) {
return i;
}
}
return 0;
}
int AudioSources::getDefaultDeviceIndex() const
{
for (auto i = 0; i < DeviceMonitor::instance().audioSources().size(); i++) {
if (DeviceMonitor::instance().audioSources()[i]->isDefault) {
return i;
}
}
return 0;
}

41
src/call/audiosources.h Normal file
View File

@@ -0,0 +1,41 @@
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <QtCore/QAbstractListModel>
#include <gst/gst.h>
class AudioSources : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
public:
enum Roles {
TitleRole = Qt::UserRole + 1,
};
static AudioSources &instance()
{
static AudioSources _instance;
return _instance;
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QHash<int, QByteArray> roleNames() const override;
GstDevice *currentDevice() const;
void setCurrentIndex(int index) const;
int currentIndex() const;
Q_SIGNALS:
void currentIndexChanged();
private:
AudioSources();
int getDefaultDeviceIndex() const;
};

199
src/call/calldevices.cpp Normal file
View File

@@ -0,0 +1,199 @@
// SPDX-FileCopyrightText: 2021 Nheko Contributors
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-FileCopyrightText: 2021 Carl Schwan <carl@carlschwan.eu>
//
// SPDX-License-Identifier: GPL-3.0-or-later
#include "calldevices.h"
#include "audiodevicesmodel.h"
#include "neochatconfig.h"
#include "videodevicesmodel.h"
#include <QStringView>
#include <cstring>
#include <optional>
#include "voiplogging.h"
#ifdef GSTREAMER_AVAILABLE
extern "C" {
#include "gst/gst.h"
}
#endif
#ifdef GSTREAMER_AVAILABLE
CallDevices::CallDevices()
: QObject()
, m_audioDevicesModel(new AudioDevicesModel(this))
, m_videoDevicesModel(new VideoDevicesModel(this))
{
init();
}
AudioDevicesModel *CallDevices::audioDevicesModel() const
{
return m_audioDevicesModel;
}
VideoDevicesModel *CallDevices::videoDevicesModel() const
{
return m_videoDevicesModel;
}
void CallDevices::addDevice(GstDevice *device)
{
if (!device)
return;
gchar *type = gst_device_get_device_class(device);
bool isVideo = !std::strncmp(type, "Video", 5);
g_free(type);
if (isVideo) {
m_videoDevicesModel->addDevice(device);
m_videoDevicesModel->setDefaultDevice();
} else {
m_audioDevicesModel->addDevice(device);
m_audioDevicesModel->setDefaultDevice();
}
}
void CallDevices::removeDevice(GstDevice *device, bool changed)
{
if (device) {
if (m_audioDevicesModel->removeDevice(device, changed) || m_videoDevicesModel->removeDevice(device, changed))
return;
}
}
namespace
{
gboolean newBusMessage(GstBus *bus, GstMessage *msg, gpointer user_data)
{
Q_UNUSED(bus)
Q_UNUSED(user_data)
switch (GST_MESSAGE_TYPE(msg)) {
case GST_MESSAGE_DEVICE_ADDED: {
GstDevice *device;
gst_message_parse_device_added(msg, &device);
CallDevices::instance().addDevice(device);
Q_EMIT CallDevices::instance().devicesChanged();
break;
}
case GST_MESSAGE_DEVICE_REMOVED: {
GstDevice *device;
gst_message_parse_device_removed(msg, &device);
CallDevices::instance().removeDevice(device, false);
Q_EMIT CallDevices::instance().devicesChanged();
break;
}
case GST_MESSAGE_DEVICE_CHANGED: {
GstDevice *device;
GstDevice *oldDevice;
gst_message_parse_device_changed(msg, &device, &oldDevice);
CallDevices::instance().removeDevice(oldDevice, true);
CallDevices::instance().addDevice(device);
Q_EMIT CallDevices::instance().devicesChanged();
break;
}
default:
break;
}
return true;
}
}
void CallDevices::init()
{
static GstDeviceMonitor *monitor = nullptr;
if (!monitor) {
monitor = gst_device_monitor_new();
Q_ASSERT(monitor);
GstCaps *caps = gst_caps_new_empty_simple("audio/x-raw");
gst_device_monitor_add_filter(monitor, "Audio/Source", caps);
gst_device_monitor_add_filter(monitor, "Audio/Duplex", caps);
gst_caps_unref(caps);
caps = gst_caps_new_empty_simple("video/x-raw");
gst_device_monitor_add_filter(monitor, "Video/Source", caps);
gst_device_monitor_add_filter(monitor, "Video/Duplex", caps);
gst_caps_unref(caps);
GstBus *bus = gst_device_monitor_get_bus(monitor);
gst_bus_add_watch(bus, newBusMessage, nullptr);
gst_object_unref(bus);
if (!gst_device_monitor_start(monitor)) {
qCCritical(voip) << "Failed to start device monitor";
return;
} else {
qCDebug(voip) << "Device monitor started";
}
}
}
bool CallDevices::hasMicrophone() const
{
return m_audioDevicesModel->hasMicrophone();
}
bool CallDevices::hasCamera() const
{
return m_videoDevicesModel->hasCamera();
}
QStringList CallDevices::resolutions(const QString &cameraName) const
{
return m_videoDevicesModel->resolutions(cameraName);
}
QStringList CallDevices::frameRates(const QString &cameraName, const QString &resolution) const
{
if (auto s = m_videoDevicesModel->getVideoSource(cameraName); s) {
if (auto it = std::find_if(s->caps.cbegin(),
s->caps.cend(),
[&](const auto &c) {
return c.resolution == resolution;
});
it != s->caps.cend())
return it->frameRates;
}
return {};
}
GstDevice *CallDevices::audioDevice() const
{
return m_audioDevicesModel->currentDevice();
}
GstDevice *CallDevices::videoDevice(QPair<int, int> &resolution, QPair<int, int> &frameRate) const
{
return m_videoDevicesModel->currentDevice(resolution, frameRate);
}
#else
bool CallDevices::hasMicrophone() const
{
return false;
}
bool CallDevices::hasCamera() const
{
return false;
}
QStringList CallDevices::names(bool, const QString &) const
{
return {};
}
QStringList CallDevices::resolutions(const QString &) const
{
return {};
}
QStringList CallDevices::frameRates(const QString &, const QString &) const
{
return {};
}
#endif

64
src/call/calldevices.h Normal file
View File

@@ -0,0 +1,64 @@
// SPDX-FileCopyrightText: 2021 Contributors
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-FileCopyrightText: 2021 Carl Schwan <carl@carlschwan.eu>
//
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <string>
#include <utility>
#include <vector>
#include <QObject>
typedef struct _GstDevice GstDevice;
class CallDevices;
class AudioDevicesModel;
class VideoDevicesModel;
class CallDevices : public QObject
{
Q_OBJECT
Q_PROPERTY(AudioDevicesModel *audioDevices READ audioDevicesModel CONSTANT);
Q_PROPERTY(VideoDevicesModel *videoDevices READ videoDevicesModel CONSTANT);
public:
static CallDevices &instance()
{
static CallDevices instance;
return instance;
}
CallDevices(CallDevices const &) = delete;
void operator=(CallDevices const &) = delete;
bool hasMicrophone() const;
bool hasCamera() const;
QStringList names(bool isVideo, const QString &defaultDevice) const;
QStringList resolutions(const QString &cameraName) const;
QStringList frameRates(const QString &cameraName, const QString &resolution) const;
AudioDevicesModel *audioDevicesModel() const;
VideoDevicesModel *videoDevicesModel() const;
void addDevice(GstDevice *device);
void removeDevice(GstDevice *device, bool changed);
Q_SIGNALS:
void devicesChanged();
private:
CallDevices();
void init();
GstDevice *audioDevice() const;
GstDevice *videoDevice(QPair<int, int> &resolution, QPair<int, int> &frameRate) const;
AudioDevicesModel *m_audioDevicesModel;
VideoDevicesModel *m_videoDevicesModel;
friend class CallSession;
friend class Audio;
};

617
src/call/callmanager.cpp Normal file
View File

@@ -0,0 +1,617 @@
// SPDX-FileCopyrightText: 2020-2021 Nheko Authors
// SPDX-FileCopyrightText: 2021-2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "callmanager.h"
#include "controller.h"
#include <gst/gst.h>
#include "voiplogging.h"
#include <KLocalizedString>
#include <QDateTime>
#include <QMediaPlaylist>
#include <QMimeDatabase>
#include <qcoro/qcorosignal.h>
#include <qt_connection_util.h>
#include "neochatconfig.h"
#define CALL_VERSION "1"
CallManager::CallManager()
{
init();
connect(&Controller::instance(), &Controller::activeConnectionChanged, this, [this] {
updateTurnServers();
});
}
QCoro::Task<void> CallManager::updateTurnServers()
{
if (m_cachedTurnUrisValidUntil > QDateTime::currentDateTime()) {
co_return;
}
Controller::instance().activeConnection()->getTurnServers();
auto servers = co_await qCoro(Controller::instance().activeConnection(), &Connection::turnServersChanged);
m_cachedTurnUrisValidUntil = QDateTime::currentDateTime().addSecs(servers["ttl"].toInt());
const auto password = servers["password"].toString();
const auto username = servers["username"].toString();
const auto uris = servers["uris"].toArray();
m_cachedTurnUris.clear();
for (const auto &u : uris) {
QString uri = u.toString();
auto c = uri.indexOf(':');
if (c == -1) {
qCWarning(voip) << "Invalid TURN URI:" << uri;
continue;
}
QString scheme = uri.left(c);
if (scheme != "turn" && scheme != "turns") {
qCWarning(voip) << "Invalid TURN scheme:" << scheme;
continue;
}
m_cachedTurnUris += QStringLiteral("%1://%2:%3@%4").arg(scheme, QUrl::toPercentEncoding(username), QUrl::toPercentEncoding(password), uri.mid(c + 1));
}
}
QString CallManager::callId() const
{
return m_callId;
}
void CallManager::handleCallEvent(NeoChatRoom *room, const Quotient::RoomEvent *event)
{
if (const auto &inviteEvent = eventCast<const CallInviteEvent>(event)) {
handleInvite(room, inviteEvent);
} else if (const auto &hangupEvent = eventCast<const CallHangupEvent>(event)) {
handleHangup(room, hangupEvent);
} else if (const auto &candidatesEvent = eventCast<const CallCandidatesEvent>(event)) {
handleCandidates(room, candidatesEvent);
} else if (const auto &answerEvent = eventCast<const CallAnswerEvent>(event)) {
handleAnswer(room, answerEvent);
} else if (const auto &negotiateEvent = eventCast<const CallNegotiateEvent>(event)) {
handleNegotiate(room, negotiateEvent);
}
}
void CallManager::checkStartCall()
{
if ((m_incomingCandidates.isEmpty() && !m_incomingSdp.contains("candidates"_ls)) || m_incomingSdp.isEmpty()) {
qCDebug(voip) << "Not ready to start this call yet";
return;
}
m_session->acceptAnswer(m_incomingSdp, m_incomingCandidates, m_remoteUser->id());
m_incomingCandidates.clear();
m_incomingSdp.clear();
setGlobalState(ACTIVE);
}
void CallManager::handleAnswer(NeoChatRoom *room, const Quotient::CallAnswerEvent *event)
{
if (globalState() != OUTGOING) {
qCDebug(voip) << "Ignoring answer while in state" << globalState();
return;
}
if (event->callId() != m_callId) {
qCDebug(voip) << "Ignoring answer for unknown call id" << event->callId() << ". Our call id is" << m_callId;
return;
}
if (event->senderId() == room->localUser()->id() && partyId() == event->contentJson()["party_id"].toString()) {
qCDebug(voip) << "Ignoring echo for answer";
return;
}
if (event->senderId() == room->localUser()->id()) {
qCDebug(voip) << "Call was accepted on a different device";
// Show the user that call was accepted on a different device
// Stop ringing
return;
}
// TODO handle that MSC wrt to accepting on other devices
m_session->setMetadata(event->contentJson()["org.matrix.msc3077.sdp_stream_metadata"].toObject());
m_remotePartyId = event->contentJson()["party_id"].toString();
m_incomingSdp = event->sdp();
checkStartCall();
}
void CallManager::handleCandidates(NeoChatRoom *room, const Quotient::CallCandidatesEvent *event)
{
// TODO what if candidates come before invite? this looks wrong
if (globalState() == IDLE) {
qCDebug(voip) << "Ignoring candidates in state" << globalState();
return;
}
if (event->senderId() == room->localUser()->id()) {
qCDebug(voip) << "Ignoring candidates sent by ourself";
return;
}
if (globalState() == ACTIVE) {
QVector<Candidate> candidates;
for (const auto &candidate : event->candidates()) {
candidates += Candidate{candidate.toObject()["candidate"].toString(),
candidate.toObject()["sdpMLineIndex"].toInt(),
candidate.toObject()["sdpMid"].toString()};
}
m_session->acceptCandidates(candidates);
return;
}
qCDebug(voip) << "Storing" << event->candidates().size() << "incoming candidates";
for (const auto &candidate : event->candidates()) {
m_incomingCandidates +=
Candidate{candidate.toObject()["candidate"].toString(), candidate.toObject()["sdpMLineIndex"].toInt(), candidate.toObject()["sdpMid"].toString()};
}
if (globalState() == OUTGOING) {
checkStartCall();
}
}
void CallManager::handleInvite(NeoChatRoom *room, const Quotient::CallInviteEvent *event)
{
if (event->senderId() == room->localUser()->id()) {
qCDebug(voip) << "Igoring invite sent by ourself";
return;
}
if (globalState() != IDLE) {
// TODO handle glare
qCDebug(voip) << "Ignoring invite while already in a call";
return;
}
if (event->originTimestamp() < QDateTime::currentDateTime().addSecs(-60)) {
qCDebug(voip) << "Ignoring outdated invite; sent at:" << event->originTimestamp() << "current:" << QDateTime::currentDateTime();
return;
}
setGlobalState(INCOMING);
m_incomingSdp = event->sdp();
setRemoteUser(dynamic_cast<NeoChatUser *>(room->user(event->senderId())));
setRoom(room);
setCallId(event->callId());
setPartyId(generatePartyId());
m_remotePartyId = event->contentJson()["party_id"].toString();
setLifetime(event->lifetime());
Q_EMIT incomingCall(remoteUser(), room, event->lifetime(), callId());
ring(event->lifetime());
}
void CallManager::handleNegotiate(NeoChatRoom *room, const Quotient::CallNegotiateEvent *event)
{
Q_UNUSED(room);
if (event->callId() != m_callId) {
qCDebug(voip) << "Ignoring negotiate for unknown call id" << event->callId() << ". Our call id is" << m_callId;
return;
}
if (event->partyId() != m_remotePartyId) {
qCDebug(voip) << "Ignoring negotiate for unknown party id" << event->partyId() << ". Remote party id is" << m_remotePartyId;
return;
}
if (event->senderId() != m_remoteUser->id()) {
qCDebug(voip) << "Ignoring negotiate for unknown user id" << event->senderId() << ". Remote user id is" << m_remoteUser->id();
return;
}
// TODO DUPLICATES FFS
m_session->setMetadata(event->contentJson()["org.matrix.msc3077.sdp_stream_metadata"].toObject());
m_session->renegotiateOffer(event->sdp(), m_remoteUser->id(), event->contentJson()["description"]["type"] == QStringLiteral("answer"));
}
void CallManager::ring(int lifetime)
{
// TODO put a better default ringtone in the kcfg
// TODO which one? ship one? plasma-mobile-sounds?
if (!QFileInfo::exists(NeoChatConfig::ringtone())) {
qCWarning(voip) << "Ringtone file doesn't exist. Not audibly ringing";
return;
}
auto ringtone = QUrl::fromLocalFile(NeoChatConfig::ringtone());
m_playlist.setPlaybackMode(QMediaPlaylist::Loop);
m_playlist.clear();
m_ringPlayer.setPlaylist(&m_playlist);
m_playlist.addMedia(ringtone);
m_ringPlayer.play();
QTimer::singleShot(lifetime, this, [this]() {
stopRinging();
Q_EMIT callEnded();
});
}
void CallManager::stopRinging()
{
m_ringPlayer.stop();
}
void CallManager::handleHangup(NeoChatRoom *room, const Quotient::CallHangupEvent *event)
{
if (globalState() == IDLE) {
qCDebug(voip) << "Ignoring hangup since we're not in a call";
return;
}
if (event->senderId() == room->localUser()->id()) {
qCDebug(voip) << "Ignoring hangup we sent ourselves";
// TODO hangup-to-decline by different device?
return;
}
if (event->callId() != m_callId) {
qCDebug(voip) << "Hangup not for this call. Event's call id:" << event->callId() << ". Our call id" << m_callId;
return;
}
stopRinging();
if (m_session) {
m_session->end();
delete m_session;
}
setGlobalState(IDLE);
Q_EMIT callEnded();
}
void CallManager::acceptCall()
{
// TODO metadata for this case
if (globalState() != INCOMING) {
qCWarning(voip) << "Not accepting call while state is" << globalState();
return;
}
stopRinging();
if (!checkPlugins()) {
qCCritical(voip) << "Missing plugins; can't accept call";
}
updateTurnServers();
// TODO wait until candidates are here
m_session = CallSession::acceptCall(m_incomingSdp, m_incomingCandidates, m_cachedTurnUris, m_remoteUser->id(), this);
m_participants->clear();
connect(m_session.data(), &CallSession::stateChanged, this, [this] {
Q_EMIT stateChanged();
if (state() == CallSession::ICEFAILED) {
Q_EMIT callEnded();
}
}); // TODO refactor away?
m_incomingCandidates.clear();
connectSingleShot(m_session.data(), &CallSession::answerCreated, this, [this](const QString &_sdp, const QVector<Candidate> &candidates) {
const auto &[uuids, sdp] = mangleSdp(_sdp);
QVector<std::pair<QString, QString>> msidToPurpose;
for (const auto &uuid : uuids) {
msidToPurpose += {uuid, "m.usermedia"}; // TODO
}
auto answer = createAnswer(m_callId, sdp, msidToPurpose);
m_room->postJson("m.call.answer", answer);
qCWarning(voip) << "Sending Answer";
auto c = createCandidates(m_callId, candidates);
auto cand = createCandidates(m_callId, candidates);
m_room->postJson("m.call.candidates", cand);
qCWarning(voip) << "Sending Candidates";
setGlobalState(ACTIVE);
});
}
void CallManager::hangupCall()
{
qCDebug(voip) << "Ending call";
if (m_session) {
m_session->end();
delete m_session;
m_session = nullptr;
}
stopRinging();
m_room->postJson("m.call.hangup", createHangup(m_callId));
setGlobalState(IDLE);
Q_EMIT callEnded();
}
NeoChatUser *CallManager::remoteUser() const
{
return m_remoteUser;
}
NeoChatRoom *CallManager::room() const
{
return m_room;
}
CallSession::State CallManager::state() const
{
if (!m_session) {
return CallSession::DISCONNECTED;
}
return m_session->state();
}
int CallManager::lifetime() const
{
return m_lifetime;
}
void CallManager::ignoreCall()
{
setLifetime(0);
setCallId({});
setRoom(nullptr);
setRemoteUser(nullptr);
}
void CallManager::startCall(NeoChatRoom *room)
{
if (m_session) {
// Don't start calls if there already is one
Q_EMIT Controller::instance().errorOccured(i18n("A call is already started"));
return;
}
if (room->users().size() != 2) {
// Don't start calls if the room doesn't have exactly two members
Q_EMIT Controller::instance().errorOccured(i18n("Calls are limited to 1:1 rooms"));
return;
}
auto missingPlugins = CallSession::missingPlugins();
if (!missingPlugins.isEmpty()) {
qCCritical(voip) << "Missing GStreamer plugins:" << missingPlugins;
Q_EMIT Controller::instance().errorOccured("Missing GStreamer plugins.");
return;
}
setLifetime(60000);
setRoom(room);
setRemoteUser(otherUser(room));
updateTurnServers();
setCallId(generateCallId());
setPartyId(generatePartyId());
m_participants->clear();
for (const auto &user : m_room->users()) {
auto participant = new CallParticipant(m_session);
participant->m_user = dynamic_cast<NeoChatUser *>(user);
m_participants->addParticipant(participant);
}
m_session = CallSession::startCall(m_cachedTurnUris, this);
setGlobalState(OUTGOING);
connect(m_session, &CallSession::stateChanged, this, [this] {
Q_EMIT stateChanged();
if (state() == CallSession::ICEFAILED) {
Q_EMIT callEnded();
}
});
connectSingleShot(m_session.data(), &CallSession::offerCreated, this, [this](const QString &_sdp, const QVector<Candidate> &candidates) {
const auto &[uuids, sdp] = mangleSdp(_sdp);
QVector<std::pair<QString, QString>> msidToPurpose;
for (const auto &uuid : uuids) {
msidToPurpose += {uuid, "m.usermedia"}; // TODO
}
qCWarning(voip) << "Sending Invite";
qCWarning(voip) << "Sending Candidates";
auto invite = createInvite(m_callId, sdp, msidToPurpose);
auto c = createCandidates(m_callId, candidates);
m_room->postJson("m.call.invite", invite);
m_room->postJson("m.call.candidates", c);
});
connect(m_session, &CallSession::renegotiate, this, [this](const QString &sdp, const QString &type) {
QVector<std::pair<QString, QString>> msidToPurpose;
const auto &[uuids, _sdp] = mangleSdp(sdp);
for (const auto &uuid : uuids) {
msidToPurpose += {uuid, "m.usermedia"}; // TODO
}
QJsonObject json{
{QStringLiteral("lifetime"), 60000},
{QStringLiteral("version"), 1},
{QStringLiteral("description"), QJsonObject{{QStringLiteral("type"), type}, {QStringLiteral("sdp"), _sdp}}}, // AAAAA
{QStringLiteral("party_id"), m_partyId},
{QStringLiteral("call_id"), m_callId},
};
QJsonObject metadata;
for (const auto &[stream, purpose] : msidToPurpose) {
QJsonObject data = {{"purpose", purpose}};
metadata[stream] = data;
}
json["org.matrix.msc3077.sdp_stream_metadata"] = metadata;
m_room->postJson("m.call.negotiate", json);
});
}
QString CallManager::generateCallId() const
{
return QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz");
}
QString CallManager::generatePartyId() const
{
return QUuid::createUuid().toString();
}
void CallManager::setCallId(const QString &callId)
{
m_callId = callId;
Q_EMIT callIdChanged();
}
void CallManager::setPartyId(const QString &partyId)
{
m_partyId = partyId;
}
void CallManager::setMuted(bool muted)
{
if (!m_session) {
return;
}
m_session->setMuted(muted);
Q_EMIT mutedChanged();
}
bool CallManager::muted() const
{
if (!m_session) {
return false;
}
return m_session->muted();
}
bool CallManager::init()
{
qRegisterMetaType<Candidate>();
qRegisterMetaType<QVector<Candidate>>();
GError *error = nullptr;
if (!gst_init_check(nullptr, nullptr, &error)) {
QString strError;
if (error) {
strError += error->message;
g_error_free(error);
}
qCCritical(voip) << "Failed to initialize GStreamer:" << strError;
return false;
}
gchar *version = gst_version_string();
qCDebug(voip) << "GStreamer version" << version;
g_free(version);
// Required to register the qml types
auto _sink = gst_element_factory_make("qmlglsink", nullptr);
Q_ASSERT(_sink);
gst_object_unref(_sink);
return true;
}
void CallManager::setLifetime(int lifetime)
{
m_lifetime = lifetime;
Q_EMIT lifetimeChanged();
}
void CallManager::setRoom(NeoChatRoom *room)
{
m_room = room;
Q_EMIT roomChanged();
}
void CallManager::setRemoteUser(NeoChatUser *user)
{
m_remoteUser = user;
Q_EMIT roomChanged();
}
NeoChatUser *CallManager::otherUser(NeoChatRoom *room)
{
return dynamic_cast<NeoChatUser *>(room->users()[0]->id() == room->localUser()->id() ? room->users()[1] : room->users()[0]);
}
QJsonObject CallManager::createCandidates(const QString &callId, const QVector<Candidate> &candidates) const
{
QJsonArray candidatesJson;
for (const auto &candidate : candidates) {
candidatesJson += QJsonObject{{"candidate", candidate.candidate}, {"sdpMid", candidate.sdpMid}, {"sdpMLineIndex", candidate.sdpMLineIndex}};
}
return QJsonObject{{"call_id", callId}, {"candidates", candidatesJson}, {"version", CALL_VERSION}, {"party_id", "todopartyid"}};
}
void CallManager::setGlobalState(GlobalState globalState)
{
if (m_globalState == globalState) {
return;
}
m_globalState = globalState;
Q_EMIT globalStateChanged();
}
CallManager::GlobalState CallManager::globalState() const
{
return m_globalState;
}
CallParticipantsModel *CallManager::callParticipants() const
{
return m_participants;
}
std::pair<QStringList, QString> CallManager::mangleSdp(const QString &_sdp)
{
QString sdp = _sdp;
QRegularExpression regex("msid:user[0-9]+@host-[0-9a-f]+ webrtctransceiver([0-9])");
auto iter = regex.globalMatch(sdp);
QStringList uuids;
while (iter.hasNext()) {
auto uuid = QUuid::createUuid();
auto match = iter.next();
uuids += uuid.toString();
sdp.replace(match.captured(), QStringLiteral("msid:") + uuid.toString() + QStringLiteral(" foo"));
}
return {uuids, sdp};
}
QJsonObject CallManager::createInvite(const QString &callId, const QString &sdp, const QVector<std::pair<QString, QString>> &msidToPurpose) const
{
QJsonObject metadata;
for (const auto &[msid, purpose] : msidToPurpose) {
metadata[msid] = QJsonObject{{"purpose", purpose}};
}
return {{"call_id", callId},
{"party_id", "todopartyid"},
{"lifetime", 60000},
{"capabilities", QJsonObject{{"m.call.transferee", false}}},
{"offer", QJsonObject{{"sdp", sdp}, {"type", "offer"}}},
{"org.matrix.msc3077.sdp_stream_metadata", metadata},
{"version", CALL_VERSION}};
}
QJsonObject CallManager::createHangup(const QString &callId) const
{
return {{"call_id", callId}, {"party_id", "todopartyid"}, {"version", CALL_VERSION}};
}
QJsonObject CallManager::createAnswer(const QString &callId, const QString &sdp, const QVector<std::pair<QString, QString>> &msidToPurpose) const
{
Q_ASSERT(!callId.isEmpty());
QJsonObject metadata;
for (const auto &[msid, purpose] : msidToPurpose) {
metadata[msid] = QJsonObject{{"purpose", purpose}};
}
return {{"call_id", callId},
{"party_id", "todopartyid"},
{"lifetime", "lifetime"},
{"capabilities", QJsonObject{{"m.call.transferee", false}}},
{"offer", QJsonObject{{"sdp", sdp}, {"type", "offer"}}},
{"org.matrix.msc3077.sdp_stream_metadata", metadata},
{"version", CALL_VERSION}};
}
void CallManager::toggleCamera()
{
m_session->toggleCamera();
}
QString CallManager::partyId() const
{
return m_partyId;
}
bool CallManager::checkPlugins() const
{
auto missingPlugins = m_session->missingPlugins();
if (!missingPlugins.isEmpty()) {
qCCritical(voip) << "Missing GStreamer plugins:" << missingPlugins;
Q_EMIT Controller::instance().errorOccured("Missing GStreamer plugins.");
}
return !missingPlugins.isEmpty();
}

159
src/call/callmanager.h Normal file
View File

@@ -0,0 +1,159 @@
// SPDX-FileCopyrightText: 2020-2021 Nheko Authors
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "neochatroom.h"
#include "neochatuser.h"
#include <QAbstractListModel>
#include <QObject>
#include <QString>
#include <events/roomevent.h>
#include "callsession.h"
#include "models/callparticipantsmodel.h"
#include <events/callevents.h>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QTimer>
#include <qcoro/task.h>
#include <qobjectdefs.h>
class CallSession;
class QQuickItem;
using namespace Quotient;
class CallManager : public QObject
{
Q_OBJECT
public:
enum GlobalState {
IDLE,
INCOMING,
OUTGOING,
ACTIVE,
};
Q_ENUM(GlobalState);
Q_PROPERTY(GlobalState globalState READ globalState NOTIFY globalStateChanged)
Q_PROPERTY(NeoChatUser *remoteUser READ remoteUser NOTIFY remoteUserChanged)
Q_PROPERTY(QString callId READ callId NOTIFY callIdChanged)
Q_PROPERTY(NeoChatRoom *room READ room NOTIFY roomChanged)
Q_PROPERTY(int lifetime READ lifetime NOTIFY lifetimeChanged)
Q_PROPERTY(bool muted READ muted WRITE setMuted NOTIFY mutedChanged)
Q_PROPERTY(QQuickItem *item MEMBER m_item) // TODO allow for different devices for each session
Q_PROPERTY(CallSession::State state READ state NOTIFY stateChanged)
Q_PROPERTY(CallParticipantsModel *callParticipants READ callParticipants CONSTANT)
static CallManager &instance()
{
static CallManager _instance;
return _instance;
}
[[nodiscard]] QString callId() const;
[[nodiscard]] QString partyId() const;
CallSession::State state() const;
NeoChatUser *remoteUser() const;
NeoChatRoom *room() const;
int lifetime() const;
bool muted() const;
void setMuted(bool muted);
CallManager::GlobalState globalState() const;
void handleCallEvent(NeoChatRoom *room, const RoomEvent *event);
Q_INVOKABLE void startCall(NeoChatRoom *room);
Q_INVOKABLE void acceptCall();
Q_INVOKABLE void hangupCall();
Q_INVOKABLE void ignoreCall();
Q_INVOKABLE void toggleCamera();
QCoro::Task<void> updateTurnServers();
[[nodiscard]] CallParticipantsModel *callParticipants() const;
QQuickItem *m_item = nullptr;
Q_SIGNALS:
void currentCallIdChanged();
void incomingCall(NeoChatUser *user, NeoChatRoom *room, int timeout, const QString &callId);
void callEnded();
void remoteUserChanged();
void callIdChanged();
void roomChanged();
void stateChanged();
void lifetimeChanged();
void mutedChanged();
void globalStateChanged();
private:
CallManager();
QString m_callId;
QVector<Candidate> m_incomingCandidates;
QString m_incomingSdp;
[[nodiscard]] bool checkPlugins() const;
QStringList m_cachedTurnUris;
QDateTime m_cachedTurnUrisValidUntil = QDateTime::fromSecsSinceEpoch(0);
NeoChatUser *m_remoteUser = nullptr;
NeoChatRoom *m_room = nullptr;
QString m_remotePartyId;
QString m_partyId;
int m_lifetime = 0;
GlobalState m_globalState = IDLE;
void handleInvite(NeoChatRoom *room, const CallInviteEvent *event);
void handleHangup(NeoChatRoom *room, const CallHangupEvent *event);
void handleCandidates(NeoChatRoom *room, const CallCandidatesEvent *event);
void handleAnswer(NeoChatRoom *room, const CallAnswerEvent *event);
void handleNegotiate(NeoChatRoom *room, const CallNegotiateEvent *event);
void checkStartCall();
void ring(int lifetime);
void stopRinging();
[[nodiscard]] QString generateCallId() const;
[[nodiscard]] QString generatePartyId() const;
bool init();
bool m_initialised = false;
QPointer<CallSession> m_session = nullptr;
void setLifetime(int lifetime);
void setRoom(NeoChatRoom *room);
void setRemoteUser(NeoChatUser *user);
void setCallId(const QString &callId);
void setPartyId(const QString &partyId);
void setGlobalState(GlobalState state);
std::pair<QStringList, QString> mangleSdp(const QString &sdp);
CallParticipantsModel *m_participants = new CallParticipantsModel();
NeoChatUser *otherUser(NeoChatRoom *room);
[[nodiscard]] QJsonObject createCandidates(const QString &callId, const QVector<Candidate> &candidates) const;
[[nodiscard]] QJsonObject createInvite(const QString &callId, const QString &sdp, const QVector<std::pair<QString, QString>> &msidToPurpose) const;
[[nodiscard]] QJsonObject createHangup(const QString &callId) const;
[[nodiscard]] QJsonObject createAnswer(const QString &callId, const QString &sdp, const QVector<std::pair<QString, QString>> &msidToPurpose) const;
QMediaPlayer m_ringPlayer;
QMediaPlaylist m_playlist;
};

View File

@@ -0,0 +1,51 @@
// SPDX-FileCopyrightText: 2022 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "callnegotiateevent.h"
using namespace Quotient;
CallNegotiateEvent::CallNegotiateEvent(const QString &callId,
const QString &partyId,
int lifetime,
const QString &sdp,
bool answer,
QVector<std::pair<QString, QString>> msidToPurpose)
: EventTemplate(callId,
{
{QStringLiteral("lifetime"), lifetime},
{QStringLiteral("version"), 1},
{QStringLiteral("description"),
QJsonObject{{QStringLiteral("type"), answer ? QStringLiteral("answer") : QStringLiteral("offer")}, {QStringLiteral("sdp"), sdp}}},
{QStringLiteral("party_id"), partyId},
})
{
QJsonObject metadata;
for (const auto &[stream, purpose] : msidToPurpose) {
QJsonObject data = {{"purpose", purpose}};
metadata[stream] = purpose;
}
auto content = editJson();
content["org.matrix.msc3077.sdp_stream_metadata"] = metadata;
editJson()["content"] = content;
}
CallNegotiateEvent::CallNegotiateEvent(const QJsonObject &json)
: EventTemplate(json)
{
}
QString CallNegotiateEvent::partyId() const
{
return contentJson()["party_id"].toString();
}
QString CallNegotiateEvent::sdp() const
{
return contentJson()["description"]["sdp"].toString();
}
QJsonObject CallNegotiateEvent::sdpStreamMetadata() const
{
return contentJson()["org.matrix.msc3077.sdp_stream_metadata"].toObject();
}

View File

@@ -0,0 +1,30 @@
// SPDX-FileCopyrightText: 2022 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <events/callevents.h>
namespace Quotient
{
class CallNegotiateEvent : public EventTemplate<CallNegotiateEvent, CallEvent>
{
public:
QUO_EVENT(CallNegotiateEvent, "m.call.negotiate")
explicit CallNegotiateEvent(const QJsonObject &obj);
explicit CallNegotiateEvent(const QString &callId,
const QString &partyId,
int lifetime,
const QString &sdp,
bool answer,
QVector<std::pair<QString, QString>> msidToPurpose);
QString partyId() const;
QString sdp() const;
// TODO make this a struct instead
QJsonObject sdpStreamMetadata() const;
};
}

View File

@@ -0,0 +1,26 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#include "callparticipant.h"
NeoChatUser *CallParticipant::user() const
{
return m_user;
}
bool CallParticipant::hasCamera() const
{
return m_hasCamera;
}
CallParticipant::CallParticipant(QObject *parent)
: QObject(parent)
{
}
void CallParticipant::initCamera(QQuickItem *item)
{
QTimer::singleShot(500, this, [=] {
Q_EMIT initialized(item);
});
}

View File

@@ -0,0 +1,36 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <QObject>
#include <QTimer>
#include "neochatuser.h"
class QQuickItem;
class CallParticipant : public QObject
{
Q_OBJECT
Q_PROPERTY(NeoChatUser *user READ user CONSTANT)
Q_PROPERTY(bool hasCamera READ hasCamera NOTIFY hasCameraChanged)
public:
NeoChatUser *m_user = nullptr;
bool m_hasCamera = false;
Q_INVOKABLE void initCamera(QQuickItem *item);
[[nodiscard]] NeoChatUser *user() const;
[[nodiscard]] bool hasCamera() const;
explicit CallParticipant(QObject *parent = nullptr);
Q_SIGNALS:
void initialized(QQuickItem *item);
void heightChanged();
void widthChanged();
void hasCameraChanged();
};

916
src/call/callsession.cpp Normal file
View File

@@ -0,0 +1,916 @@
// SPDX-FileCopyrightText: 2021 Nheko Contributors
// SPDX-FileCopyrightText: 2021 Carl Schwan <carl@carlschwan.eu>
// SPDX-FileCopyrightText: 2021-2022 Tobias Fella <fella@posteo.de>
//
// SPDX-License-Identifier: GPL-3.0-or-later
#include "calldevices.h"
#include <QDebug>
#include <QThread>
#include <gst/gst.h>
#define GST_USE_UNSTABLE_API
#include <gst/webrtc/webrtc.h>
#undef GST_USE_UNSTABLE_API
#include "voiplogging.h"
#include "audiosources.h"
#include "videosources.h"
#include <qcoro/qcorosignal.h>
#define private public
#include "callsession.h"
#undef private
#include "callmanager.h"
#include <qt_connection_util.h>
#define STUN_SERVER "stun://turn.matrix.org:3478" // TODO make STUN server configurable
#define INSTANCE \
Q_ASSERT(user_data); \
auto instance = static_cast<CallSession *>(user_data);
GstElement *createElement(const char *type, GstElement *pipe, const char *name = nullptr)
{
auto element = gst_element_factory_make(type, name);
Q_ASSERT_X(element, __FUNCTION__, QStringLiteral("Failed to create element %1 %2").arg(type, name).toLatin1());
if (pipe) {
gst_bin_add_many(GST_BIN(pipe), element, nullptr);
}
return element;
}
GstElement *binGetByName(GstElement *bin, const char *name)
{
auto element = gst_bin_get_by_name(GST_BIN(bin), name);
Q_ASSERT_X(element, __FUNCTION__, QStringLiteral("Failed to get element by name: %1").arg(name).toLatin1());
return element;
}
struct KeyFrameRequestData {
GstElement *pipe = nullptr;
GstElement *decodeBin = nullptr;
gint packetsLost = 0;
guint timerId = 0;
QString statsField;
} keyFrameRequestData;
std::pair<int, int> getResolution(GstPad *pad)
{
std::pair<int, int> ret;
auto caps = gst_pad_get_current_caps(pad);
auto structure = gst_caps_get_structure(caps, 0);
gst_structure_get_int(structure, "width", &ret.first);
gst_structure_get_int(structure, "height", &ret.second);
gst_caps_unref(caps);
return ret;
}
std::pair<int, int> getResolution(GstElement *pipe, const gchar *elementName, const gchar *padName)
{
auto element = binGetByName(pipe, elementName);
auto pad = gst_element_get_static_pad(element, padName);
auto ret = getResolution(pad);
gst_object_unref(pad);
gst_object_unref(element);
return ret;
}
void setLocalDescription(GstPromise *promise, gpointer user_data)
{
INSTANCE
qCDebug(voip) << "Setting local description";
const GstStructure *reply = gst_promise_get_reply(promise);
gboolean isAnswer = gst_structure_id_has_field(reply, g_quark_from_string("answer"));
GstWebRTCSessionDescription *gstsdp = nullptr;
gst_structure_get(reply, isAnswer ? "answer" : "offer", GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &gstsdp, nullptr);
gst_promise_unref(promise);
auto webrtcbin = binGetByName(instance->m_pipe, "webrtcbin");
Q_ASSERT(gstsdp);
g_signal_emit_by_name(webrtcbin, "set-local-description", gstsdp, nullptr);
gchar *sdp = gst_sdp_message_as_text(gstsdp->sdp);
if (!instance->m_localSdp.isEmpty()) {
// This is a renegotiation
qWarning() << "emitting renegotiate";
Q_EMIT instance->renegotiate(QString(sdp), isAnswer ? QStringLiteral("answer") : QStringLiteral("offer"));
}
instance->m_localSdp = QString(sdp);
g_free(sdp);
gst_webrtc_session_description_free(gstsdp);
qCDebug(voip) << "Local description set:" << isAnswer;
}
bool contains(std::string_view str1, std::string_view str2)
{
return std::search(str1.cbegin(),
str1.cend(),
str2.cbegin(),
str2.cend(),
[](unsigned char c1, unsigned char c2) {
return std::tolower(c1) == std::tolower(c2);
})
!= str1.cend();
}
void createOffer(GstElement *webrtc, CallSession *session)
{
// TODO ?!?
if (!session->m_localSdp.isEmpty()) {
return;
}
qCWarning(voip) << "Creating Offer";
auto promise = gst_promise_new_with_change_func(setLocalDescription, session, nullptr);
g_signal_emit_by_name(webrtc, "create-offer", nullptr, promise);
}
void createAnswer(GstPromise *promise, gpointer user_data)
{
INSTANCE
qCDebug(voip) << "Creating Answer";
gst_promise_unref(promise);
promise = gst_promise_new_with_change_func(setLocalDescription, instance, nullptr);
auto webrtcbin = binGetByName(instance->m_pipe, "webrtcbin");
g_signal_emit_by_name(webrtcbin, "create-answer", nullptr, promise);
}
bool getMediaAttributes(const GstSDPMessage *sdp, const char *mediaType, const char *encoding, int &payloadType, bool &receiveOnly, bool &sendOnly)
{
payloadType = -1;
receiveOnly = false;
sendOnly = false;
for (guint mlineIndex = 0; mlineIndex < gst_sdp_message_medias_len(sdp); mlineIndex++) {
const GstSDPMedia *media = gst_sdp_message_get_media(sdp, mlineIndex);
if (!strcmp(gst_sdp_media_get_media(media), mediaType)) {
receiveOnly = gst_sdp_media_get_attribute_val(media, "recvonly") != nullptr;
sendOnly = gst_sdp_media_get_attribute_val(media, "sendonly") != nullptr;
const gchar *rtpval = nullptr;
for (guint n = 0; n == 0 || rtpval; n++) {
rtpval = gst_sdp_media_get_attribute_val_n(media, "rtpmap", n);
if (rtpval && contains(rtpval, encoding)) {
payloadType = QString::fromLatin1(rtpval).toInt();
break;
}
}
return true;
}
}
return false;
}
GstWebRTCSessionDescription *parseSDP(const QString &sdp, GstWebRTCSDPType type)
{
GstSDPMessage *message;
gst_sdp_message_new(&message);
if (gst_sdp_message_parse_buffer((guint8 *)sdp.toLatin1().data(), sdp.size(), message) == GST_SDP_OK) {
return gst_webrtc_session_description_new(type, message);
} else {
qCCritical(voip) << "Failed to parse remote SDP";
gst_sdp_message_free(message);
return nullptr;
}
}
void addLocalICECandidate(GstElement *webrtc, guint mlineIndex, const gchar *candidate, gpointer user_data)
{
Q_UNUSED(webrtc);
INSTANCE
// qCWarning(voip) << "Adding local ICE Candidates";
instance->m_localCandidates += Candidate{candidate, static_cast<int>(mlineIndex), QString()};
}
void iceConnectionStateChanged(GstElement *webrtc, GParamSpec *pspec, gpointer user_data)
{
Q_UNUSED(pspec);
INSTANCE
GstWebRTCICEConnectionState newState;
g_object_get(webrtc, "ice-connection-state", &newState, nullptr);
switch (newState) {
case GST_WEBRTC_ICE_CONNECTION_STATE_NEW:
case GST_WEBRTC_ICE_CONNECTION_STATE_CHECKING:
instance->setState(CallSession::CONNECTING);
break;
case GST_WEBRTC_ICE_CONNECTION_STATE_FAILED:
instance->setState(CallSession::ICEFAILED);
break;
case GST_WEBRTC_ICE_CONNECTION_STATE_CONNECTED:
instance->setState(CallSession::CONNECTED);
case GST_WEBRTC_ICE_CONNECTION_STATE_COMPLETED:
case GST_WEBRTC_ICE_CONNECTION_STATE_DISCONNECTED:
case GST_WEBRTC_ICE_CONNECTION_STATE_CLOSED:
default:
break;
}
}
GstElement *newAudioSinkChain(GstElement *pipe)
{
qCWarning(voip) << "New Audio Sink Chain";
GstElement *queue = createElement("queue", pipe);
GstElement *convert = createElement("audioconvert", pipe);
GstElement *resample = createElement("audioresample", pipe);
GstElement *sink = createElement("autoaudiosink", pipe);
gst_element_link_many(queue, convert, resample, sink, nullptr);
gst_element_sync_state_with_parent(queue);
gst_element_sync_state_with_parent(convert);
gst_element_sync_state_with_parent(resample);
gst_element_sync_state_with_parent(sink);
return queue;
}
void sendKeyFrameRequest()
{
auto sinkpad = gst_element_get_static_pad(keyFrameRequestData.decodeBin, "sink");
if (!gst_pad_push_event(sinkpad, gst_event_new_custom(GST_EVENT_CUSTOM_UPSTREAM, gst_structure_new_empty("GstForceKeyUnit")))) {
qCWarning(voip) << "Keyframe request failed";
}
gst_object_unref(sinkpad);
}
void onGetStats(GstPromise *promise, gpointer)
{
auto reply = gst_promise_get_reply(promise);
GstStructure *rtpStats;
if (!gst_structure_get(reply, keyFrameRequestData.statsField.toLatin1().data(), GST_TYPE_STRUCTURE, &rtpStats, nullptr)) {
gst_promise_unref(promise);
return;
}
auto packetsLost = 0;
gst_structure_get_int(rtpStats, "packets-lost", &packetsLost);
gst_structure_free(rtpStats);
gst_promise_unref(promise);
if (packetsLost > keyFrameRequestData.packetsLost) {
qCWarning(voip) << "inbound video lost packet count:" << packetsLost;
keyFrameRequestData.packetsLost = packetsLost;
sendKeyFrameRequest();
}
}
// TODO port to QTimer?
gboolean testPacketLoss(gpointer)
{
if (!keyFrameRequestData.pipe) {
return false;
}
auto webrtc = binGetByName(keyFrameRequestData.pipe, "webrtcbin");
auto promise = gst_promise_new_with_change_func(onGetStats, nullptr, nullptr);
g_signal_emit_by_name(webrtc, "get-stats", nullptr, promise);
gst_object_unref(webrtc);
return true;
}
GstElement *newVideoSinkChain(GstElement *pipe, QQuickItem *quickItem)
{
Q_ASSERT(pipe);
Q_ASSERT(quickItem);
qCWarning(voip) << "Creating Video Sink Chain";
auto queue = createElement("queue", pipe);
auto compositor = createElement("compositor", pipe);
auto glupload = createElement("glupload", pipe);
auto glcolorconvert = createElement("glcolorconvert", pipe);
auto qmlglsink = createElement("qmlglsink", nullptr);
auto glsinkbin = createElement("glsinkbin", pipe);
g_object_set(qmlglsink, "widget", quickItem, nullptr);
g_object_set(glsinkbin, "sink", qmlglsink, nullptr);
gst_element_link_many(queue, compositor, glupload, glcolorconvert, glsinkbin, nullptr);
gst_element_sync_state_with_parent(queue);
gst_element_sync_state_with_parent(compositor);
gst_element_sync_state_with_parent(glupload);
gst_element_sync_state_with_parent(glcolorconvert);
gst_element_sync_state_with_parent(glsinkbin);
return queue;
}
static GstPadProbeReturn pad_cb(GstPad *pad, GstPadProbeInfo *info, gpointer user_data)
{
Q_UNUSED(pad);
// auto stream = static_cast<VideoStream *>(user_data);
auto event = GST_PAD_PROBE_INFO_EVENT(info);
if (GST_EVENT_CAPS == GST_EVENT_TYPE(event)) {
GstCaps *caps = gst_caps_new_any();
int width, height;
gst_event_parse_caps(event, &caps);
auto structure = gst_caps_get_structure(caps, 0);
gst_structure_get_int(structure, "width", &width);
gst_structure_get_int(structure, "height", &height);
// stream->setWidth(width);
// stream->setHeight(height);
// TODO needed?
}
return GST_PAD_PROBE_OK;
}
void linkNewPad(GstElement *decodeBin, GstPad *newpad, gpointer user_data)
{
INSTANCE
qCWarning(voip) << "Linking New Pad";
auto sinkpad = gst_element_get_static_pad(decodeBin, "sink");
auto sinkcaps = gst_pad_get_current_caps(sinkpad);
auto structure = gst_caps_get_structure(sinkcaps, 0);
gchar *mediaType = nullptr;
guint ssrc = 0;
gst_structure_get(structure, "media", G_TYPE_STRING, &mediaType, "ssrc", G_TYPE_UINT, &ssrc, nullptr);
gst_caps_unref(sinkcaps);
gst_object_unref(sinkpad);
GstElement *queue = nullptr;
if (!strcmp(mediaType, "audio")) {
qCWarning(voip) << "Receiving audio stream";
queue = newAudioSinkChain(instance->m_pipe);
} else if (!strcmp(mediaType, "video")) {
qCWarning(voip) << "Receiving video stream";
auto fake = createElement("fakesink", instance->m_pipe);
auto selector = createElement("output-selector", instance->m_pipe);
auto selectorSink = gst_element_get_static_pad(selector, "sink");
auto selectorSrc1 = gst_element_request_pad_simple(selector, "src_%u");
gst_pad_link(newpad, selectorSink);
auto fakepad = gst_element_get_static_pad(fake, "sink");
gst_pad_link(selectorSrc1, fakepad);
g_object_set(selector, "active-pad", selectorSrc1, nullptr);
auto msid = instance->ssrcToMsid[ssrc];
// gst_pad_add_probe(newpad, GST_PAD_PROBE_TYPE_EVENT_BOTH, pad_cb, stream, nullptr);
auto manager = dynamic_cast<CallManager *>(instance->parent());
auto participants = manager->callParticipants();
auto user = dynamic_cast<NeoChatUser *>(manager->room()->user(instance->msidToUserId[msid]));
participants->setHasCamera(user, true);
auto participant = participants->callParticipantForUser(user);
// gst_pad_add_probe(newpad, GST_PAD_PROBE_TYPE_EVENT_BOTH, pad_cb, nullptr, nullptr);
connectSingleShot(participant, &CallParticipant::initialized, instance, [=](QQuickItem *item) {
gst_pad_unlink(newpad, fakepad);
auto queue = newVideoSinkChain(instance->m_pipe, item);
auto queuepad = gst_element_get_static_pad(queue, "sink");
Q_ASSERT(queuepad);
auto selectorSrc = gst_element_request_pad_simple(selector, "src_%u");
auto ok = GST_PAD_LINK_SUCCESSFUL(gst_pad_link(selectorSrc, queuepad));
Q_ASSERT(ok);
g_object_set(selector, "active-pad", selectorSrc, nullptr);
instance->setState(CallSession::CONNECTED);
keyFrameRequestData.pipe = instance->m_pipe;
keyFrameRequestData.decodeBin = decodeBin;
keyFrameRequestData.timerId = g_timeout_add_seconds(3, testPacketLoss, nullptr);
keyFrameRequestData.statsField = QStringLiteral("rtp-inbound-stream-stats_") + QString::number(ssrc);
gst_object_unref(queuepad);
g_free(mediaType);
});
return;
} else {
g_free(mediaType);
qCWarning(voip) << "Unknown pad type:" << GST_PAD_NAME(newpad);
return;
}
auto queuepad = gst_element_get_static_pad(queue, "sink");
Q_ASSERT(queuepad);
auto ok = GST_PAD_LINK_SUCCESSFUL(gst_pad_link(newpad, queuepad));
Q_ASSERT(ok);
gst_object_unref(queuepad);
g_free(mediaType);
}
void setWaitForKeyFrame(GstBin *decodeBin, GstElement *element, gpointer)
{
Q_UNUSED(decodeBin);
if (!strcmp(gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(gst_element_get_factory(element))), "rtpvp8depay")) {
g_object_set(element, "wait-for-keyframe", TRUE, nullptr);
}
}
void addDecodeBin(GstElement *webrtc, GstPad *newpad, gpointer user_data)
{
Q_UNUSED(webrtc);
if (GST_PAD_DIRECTION(newpad) != GST_PAD_SRC) {
return;
}
INSTANCE
auto decodeBin = createElement("decodebin", instance->m_pipe);
// Investigate hardware, see nheko source
g_object_set(decodeBin, "force-sw-decoders", TRUE, nullptr);
g_signal_connect(decodeBin, "pad-added", G_CALLBACK(linkNewPad), instance);
g_signal_connect(decodeBin, "element-added", G_CALLBACK(setWaitForKeyFrame), nullptr);
gst_element_sync_state_with_parent(decodeBin);
auto sinkpad = gst_element_get_static_pad(decodeBin, "sink");
if (GST_PAD_LINK_FAILED(gst_pad_link(newpad, sinkpad))) {
// TODO: Error handling
qCWarning(voip) << "Unable to link decodebin";
}
gst_object_unref(sinkpad);
}
void iceGatheringStateChanged(GstElement *webrtc, GParamSpec *pspec, gpointer user_data)
{
Q_UNUSED(pspec);
INSTANCE
GstWebRTCICEGatheringState newState;
g_object_get(webrtc, "ice-gathering-state", &newState, nullptr);
if (newState == GST_WEBRTC_ICE_GATHERING_STATE_COMPLETE) {
qCWarning(voip) << "GstWebRTCICEGatheringState -> Complete";
if (instance->m_isOffering) {
Q_EMIT instance->offerCreated(instance->m_localSdp, instance->m_localCandidates);
instance->setState(CallSession::OFFERSENT);
} else {
Q_EMIT instance->answerCreated(instance->m_localSdp, instance->m_localCandidates);
instance->setState(CallSession::ANSWERSENT);
}
}
}
gboolean newBusMessage(GstBus *bus, GstMessage *msg, gpointer user_data)
{
Q_UNUSED(bus);
INSTANCE
switch (GST_MESSAGE_TYPE(msg)) {
case GST_MESSAGE_EOS:
qCWarning(voip) << "End of stream";
// TODO: Error handling
instance->end();
break;
case GST_MESSAGE_ERROR:
GError *error;
gchar *debug;
gst_message_parse_error(msg, &error, &debug);
qCWarning(voip) << "Error from element:" << GST_OBJECT_NAME(msg->src) << error->message;
// TODO: Error handling
g_clear_error(&error);
g_free(debug);
instance->end();
break;
default:
break;
}
return TRUE;
}
CallSession::CallSession(QObject *parent)
: QObject(parent)
{
}
void CallSession::acceptAnswer(const QString &sdp, const QVector<Candidate> &candidates, const QString &userId)
{
qCDebug(voip) << "Accepting Answer";
if (m_state != CallSession::OFFERSENT) {
return;
}
GstWebRTCSessionDescription *answer = parseSDP(sdp, GST_WEBRTC_SDP_TYPE_ANSWER);
if (!answer) {
end();
return;
}
acceptCandidates(candidates);
setRemoteDescription(answer, userId);
}
void CallSession::setRemoteDescription(GstWebRTCSessionDescription *remote, const QString &userId, GstPromise *promise)
{
GstElement *webrtcbin = binGetByName(m_pipe, "webrtcbin");
auto sdp = remote->sdp;
for (guint i = 0; i < gst_sdp_message_medias_len(sdp); i++) {
auto media = gst_sdp_message_get_media(sdp, i);
QList<uint32_t> ssrcs;
QString msid;
for (guint j = 0; j < gst_sdp_media_attributes_len(media); j++) {
auto attribute = gst_sdp_media_get_attribute(media, j);
if (!strcmp(attribute->key, "ssrc")) {
ssrcs += QString(attribute->value).split(" ")[0].toUInt();
}
if (!strcmp(attribute->key, "msid")) {
msid = QString(attribute->value).split(" ")[0];
}
}
for (const auto &ssrc : ssrcs) {
ssrcToMsid[ssrc] = msid;
}
msidToUserId[msid] = userId;
}
g_signal_emit_by_name(webrtcbin, "set-remote-description", remote, promise);
}
void CallSession::renegotiateOffer(const QString &_offer, const QString &userId, bool answer)
{
GstWebRTCSessionDescription *sdp = parseSDP(_offer, answer ? GST_WEBRTC_SDP_TYPE_ANSWER : GST_WEBRTC_SDP_TYPE_OFFER);
if (!sdp) {
Q_ASSERT(false);
}
GstElement *webrtcbin = binGetByName(m_pipe, "webrtcbin");
setRemoteDescription(sdp, userId);
qWarning() << "answer:" << answer;
if (!answer) {
GstPromise *promise = gst_promise_new_with_change_func(setLocalDescription, this, nullptr);
g_signal_emit_by_name(webrtcbin, "create-answer", nullptr, promise);
}
}
void CallSession::acceptOffer(const QString &sdp, const QVector<Candidate> remoteCandidates, const QString &userId)
{
Q_ASSERT(!sdp.isEmpty());
Q_ASSERT(!remoteCandidates.isEmpty());
qCDebug(voip) << "Accepting offer";
if (m_state != CallSession::DISCONNECTED) {
return;
}
m_isOffering = false;
GstWebRTCSessionDescription *offer = parseSDP(sdp, GST_WEBRTC_SDP_TYPE_OFFER);
if (!offer) {
qCCritical(voip) << "Not an offer";
return;
}
int opusPayloadType;
bool receiveOnly;
bool sendOnly;
if (getMediaAttributes(offer->sdp, "audio", "opus", opusPayloadType, receiveOnly, sendOnly)) {
if (opusPayloadType == -1) {
qCCritical(voip) << "No OPUS in offer";
gst_webrtc_session_description_free(offer);
return;
}
} else {
qCCritical(voip) << "No audio in offer";
gst_webrtc_session_description_free(offer);
return;
}
startPipeline();
QThread::msleep(1000); // ?
acceptCandidates(remoteCandidates);
auto promise = gst_promise_new_with_change_func(createAnswer, this, nullptr);
setRemoteDescription(offer, userId, promise);
gst_webrtc_session_description_free(offer);
}
void CallSession::createCall()
{
qCDebug(voip) << "Creating call";
m_isOffering = true;
startPipeline();
}
void CallSession::startPipeline()
{
qCDebug(voip) << "Starting Pipeline";
if (m_state != CallSession::DISCONNECTED) {
return;
}
m_state = CallSession::INITIATING;
Q_EMIT stateChanged();
createPipeline();
auto webrtcbin = binGetByName(m_pipe, "webrtcbin");
Q_ASSERT(webrtcbin);
if (false /*TODO: CHECK USE STUN*/) {
qCDebug(voip) << "Setting STUN server:" << STUN_SERVER;
g_object_set(webrtcbin, "stun-server", STUN_SERVER, nullptr);
}
for (const auto &uri : m_turnServers) {
qCDebug(voip) << "Setting turn server:" << uri;
gboolean udata;
g_signal_emit_by_name(webrtcbin, "add-turn-server", uri.toLatin1().data(), (gpointer)(&udata));
}
if (m_turnServers.empty()) {
qCWarning(voip) << "No TURN servers provided";
}
if (m_isOffering) {
g_signal_connect(webrtcbin, "on-negotiation-needed", G_CALLBACK(::createOffer), this);
}
g_signal_connect(webrtcbin, "on-ice-candidate", G_CALLBACK(addLocalICECandidate), this);
g_signal_connect(webrtcbin, "notify::ice-connection-state", G_CALLBACK(iceConnectionStateChanged), this);
gst_element_set_state(m_pipe, GST_STATE_READY);
g_signal_connect(webrtcbin, "pad-added", G_CALLBACK(addDecodeBin), this);
g_signal_connect(webrtcbin, "notify::ice-gathering-state", G_CALLBACK(iceGatheringStateChanged), this);
gst_object_unref(webrtcbin);
GstStateChangeReturn ret = gst_element_set_state(m_pipe, GST_STATE_PLAYING);
if (ret == GST_STATE_CHANGE_FAILURE) {
// TODO: Error handling
qCCritical(voip) << "Unable to start pipeline";
end();
return;
}
GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE(m_pipe));
m_busWatchId = gst_bus_add_watch(bus, newBusMessage, this);
gst_object_unref(bus);
m_state = CallSession::INITIATED;
Q_EMIT stateChanged();
}
void CallSession::end()
{
qCDebug(voip) << "Ending Call";
if (m_pipe) {
gst_element_set_state(m_pipe, GST_STATE_NULL);
gst_object_unref(m_pipe);
m_pipe = nullptr;
keyFrameRequestData.pipe = nullptr;
if (m_busWatchId) {
g_source_remove(m_busWatchId);
m_busWatchId = 0;
}
}
if (m_state != CallSession::DISCONNECTED) {
m_state = CallSession::DISCONNECTED;
Q_EMIT stateChanged();
}
}
void CallSession::createPipeline()
{
qCWarning(voip) << "Creating Pipeline";
auto device = AudioSources::instance().currentDevice();
if (!device) {
return;
}
m_pipe = gst_pipeline_new(nullptr);
auto source = gst_device_create_element(device, nullptr);
auto volume = createElement("volume", m_pipe, "srclevel");
auto convert = createElement("audioconvert", m_pipe);
auto resample = createElement("audioresample", m_pipe);
auto queue1 = createElement("queue", m_pipe);
auto opusenc = createElement("opusenc", m_pipe);
auto rtp = createElement("rtpopuspay", m_pipe);
auto queue2 = createElement("queue", m_pipe);
auto capsfilter = createElement("capsfilter", m_pipe);
auto rtpcaps = gst_caps_new_simple("application/x-rtp",
"media",
G_TYPE_STRING,
"audio",
"encoding-name",
G_TYPE_STRING,
"OPUS",
"payload",
G_TYPE_INT,
OPUS_PAYLOAD_TYPE,
nullptr);
Q_ASSERT(rtpcaps);
g_object_set(capsfilter, "caps", rtpcaps, nullptr);
gst_caps_unref(rtpcaps);
auto webrtcbin = createElement("webrtcbin", m_pipe, "webrtcbin");
g_object_set(webrtcbin, "bundle-policy", GST_WEBRTC_BUNDLE_POLICY_MAX_BUNDLE, nullptr);
gst_bin_add_many(GST_BIN(m_pipe), source, nullptr);
if (!gst_element_link_many(source, volume, convert, resample, queue1, opusenc, rtp, queue2, capsfilter, webrtcbin, nullptr)) {
qCCritical(voip) << "Failed to link pipeline";
// TODO propagate errors up and end call
return;
}
}
void CallSession::toggleCamera()
{
// TODO do this only once
static bool inited = false;
if (!inited) {
addVideoPipeline();
inited = true;
}
}
bool CallSession::addVideoPipeline()
{
qCDebug(voip) << "Adding Video Pipeline";
auto videoconvert = createElement("videoconvertscale", m_pipe);
auto tee = createElement("tee", m_pipe);
auto device = VideoSources::instance().currentDevice();
auto deviceCaps = device->caps[VideoSources::instance().capsIndex()];
int width = deviceCaps.width;
int height = deviceCaps.height;
int framerate = deviceCaps.framerates.back();
if (!device) {
return false;
}
auto camera = gst_device_create_element(device->device, nullptr);
gst_bin_add_many(GST_BIN(m_pipe), camera, nullptr);
auto caps =
gst_caps_new_simple("video/x-raw", "width", G_TYPE_INT, width, "height", G_TYPE_INT, height, "framerate", GST_TYPE_FRACTION, framerate, 1, nullptr);
auto camerafilter = createElement("capsfilter", m_pipe);
g_object_set(camerafilter, "caps", caps, nullptr);
gst_caps_unref(caps);
gst_element_link(camera, videoconvert);
if (!gst_element_link_many(videoconvert, camerafilter, nullptr)) {
qCWarning(voip) << "Failed to link camera elements";
// TODO: Error handling
return false;
}
if (!gst_element_link(camerafilter, tee)) {
qCWarning(voip) << "Failed to link camerafilter -> tee";
// TODO: Error handling
return false;
}
auto queue = createElement("queue", m_pipe);
g_object_set(queue, "leaky", true, nullptr);
auto vp8enc = createElement("vp8enc", m_pipe);
g_object_set(vp8enc, "deadline", 1, nullptr);
g_object_set(vp8enc, "error-resilient", 1, nullptr);
auto rtpvp8pay = createElement("rtpvp8pay", m_pipe);
auto rtpqueue = createElement("queue", m_pipe);
auto rtpcapsfilter = createElement("capsfilter", m_pipe);
auto rtpcaps = gst_caps_new_simple("application/x-rtp",
"media",
G_TYPE_STRING,
"video",
"encoding-name",
G_TYPE_STRING,
"VP8",
"payload",
G_TYPE_INT,
VP8_PAYLOAD_TYPE,
nullptr);
g_object_set(rtpcapsfilter, "caps", rtpcaps, nullptr);
gst_caps_unref(rtpcaps);
auto webrtcbin = binGetByName(m_pipe, "webrtcbin");
if (!gst_element_link_many(tee, queue, vp8enc, rtpvp8pay, rtpqueue, rtpcapsfilter, webrtcbin, nullptr)) {
qCCritical(voip) << "Failed to link rtp video elements";
gst_object_unref(webrtcbin);
return false;
}
auto promise = gst_promise_new_with_change_func(setLocalDescription, this, nullptr);
g_signal_emit_by_name(webrtcbin, "create-offer", nullptr, promise);
gst_object_unref(webrtcbin);
auto newpad = gst_element_request_pad_simple(tee, "src_%u");
Q_ASSERT(newpad);
auto fake = createElement("fakesink", m_pipe);
auto selector = createElement("output-selector", m_pipe);
auto selectorSink = gst_element_get_static_pad(selector, "sink");
auto selectorSrc1 = gst_element_request_pad_simple(selector, "src_%u");
gst_pad_link(newpad, selectorSink);
auto fakepad = gst_element_get_static_pad(fake, "sink");
gst_pad_link(selectorSrc1, fakepad);
g_object_set(selector, "active-pad", selectorSrc1, nullptr);
// gst_pad_add_probe(newpad, GST_PAD_PROBE_TYPE_EVENT_BOTH, pad_cb, stream, nullptr);
auto manager = dynamic_cast<CallManager *>(parent());
auto participants = manager->callParticipants();
auto user = dynamic_cast<NeoChatUser *>(manager->room()->localUser());
participants->setHasCamera(user, true);
connectSingleShot(participants->callParticipantForUser(user), &CallParticipant::initialized, this, [=](QQuickItem *item) {
gst_pad_unlink(newpad, fakepad);
Q_ASSERT(item);
auto queue = newVideoSinkChain(m_pipe, item);
Q_ASSERT(queue);
auto queuepad = gst_element_get_static_pad(queue, "sink");
Q_ASSERT(queuepad);
auto selectorSrc = gst_element_request_pad_simple(selector, "src_%u");
Q_ASSERT(selectorSrc);
auto ok = GST_PAD_LINK_SUCCESSFUL(gst_pad_link(selectorSrc, queuepad));
Q_ASSERT(ok);
g_object_set(selector, "active-pad", selectorSrc, nullptr);
gst_object_unref(queuepad);
gst_element_set_state(m_pipe, GST_STATE_READY); // TODO experimental
gst_element_set_state(m_pipe, GST_STATE_PLAYING); // TODO experimental
GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(m_pipe), GST_DEBUG_GRAPH_SHOW_ALL, "foo");
});
return true;
}
void CallSession::setTurnServers(QStringList servers)
{
qCDebug(voip) << "Setting Turn Servers";
qWarning() << "TURN SERVERS" << servers;
m_turnServers = servers;
}
void CallSession::acceptCandidates(const QVector<Candidate> &candidates)
{
qCDebug(voip) << "Accepting ICE Candidates";
auto webrtcbin = binGetByName(m_pipe, "webrtcbin");
for (const auto &c : candidates) {
qCDebug(voip) << "Remote candidate:" << c.candidate << c.sdpMLineIndex;
g_signal_emit_by_name(webrtcbin, "add-ice-candidate", c.sdpMLineIndex, c.candidate.toLatin1().data());
}
}
QStringList CallSession::missingPlugins()
{
GstRegistry *registry = gst_registry_get();
static const QVector<QString> videoPlugins = {
QLatin1String("compositor"),
QLatin1String("opengl"),
QLatin1String("qmlgl"),
QLatin1String("rtp"),
QLatin1String("videoconvertscale"),
QLatin1String("vpx"),
};
static const QVector<QString> audioPlugins = {
QStringLiteral("audioconvert"),
QStringLiteral("audioresample"),
QStringLiteral("autodetect"),
QStringLiteral("dtls"),
QStringLiteral("nice"),
QStringLiteral("opus"),
QStringLiteral("playback"),
QStringLiteral("rtpmanager"),
QStringLiteral("srtp"),
QStringLiteral("volume"),
QStringLiteral("webrtc"),
};
QStringList missingPlugins;
for (const auto &pluginName : videoPlugins + audioPlugins) {
auto plugin = gst_registry_find_plugin(registry, pluginName.toLatin1().data());
if (!plugin) {
missingPlugins << pluginName;
}
gst_object_unref(plugin);
}
return missingPlugins;
}
void CallSession::setMuted(bool muted)
{
const auto srclevel = binGetByName(m_pipe, "srclevel");
g_object_set(srclevel, "mute", muted, nullptr);
gst_object_unref(srclevel);
Q_EMIT mutedChanged();
}
bool CallSession::muted() const
{
if (m_state < CallSession::CONNECTING) {
return false;
}
if (!m_pipe) {
return false;
}
const auto srclevel = binGetByName(m_pipe, "srclevel");
bool muted;
if (!srclevel) {
return false;
}
g_object_get(srclevel, "mute", &muted, nullptr);
// gst_object_unref(srclevel); //TODO why does this crash?
return muted;
}
CallSession *
CallSession::acceptCall(const QString &sdp, const QVector<Candidate> &candidates, const QStringList &turnUris, const QString &userId, QObject *parent)
{
auto instance = new CallSession(parent);
instance->setTurnServers(turnUris);
instance->acceptOffer(sdp, candidates, userId);
return instance;
}
CallSession *CallSession::startCall(const QStringList &turnUris, QObject *parent)
{
auto instance = new CallSession(parent);
instance->setTurnServers(turnUris);
instance->createCall();
return instance;
}
CallSession::State CallSession::state() const
{
return m_state;
}
void CallSession::setState(CallSession::State state)
{
qCWarning(voip) << "Setting state" << state;
m_state = state;
Q_EMIT stateChanged();
}
void CallSession::setMetadata(QJsonObject metadata)
{
m_metadata = metadata;
}

113
src/call/callsession.h Normal file
View File

@@ -0,0 +1,113 @@
// SPDX-FileCopyrightText: 2021 Nheko Contributors
// SPDX-FileCopyrightText: 2021 Carl Schwan <carl@carlschwan.eu>
// SPDX-FileCopyrightText: 2021-2022 Tobias Fella <fella@posteo.de>
//
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QJsonObject>
#include <QMetaType>
#include <QObject>
#include <QQuickItem>
#include <QString>
#include <variant>
#define GST_USE_UNSTABLE_API
#include <gst/webrtc/webrtc.h>
#include <gst/gst.h>
#define OPUS_PAYLOAD_TYPE 111
#define VP8_PAYLOAD_TYPE 96
class CallDevices;
class VideoStream;
struct Candidate {
QString candidate;
int sdpMLineIndex;
QString sdpMid;
};
Q_DECLARE_METATYPE(Candidate)
Q_DECLARE_METATYPE(QVector<Candidate>)
class CallSession : public QObject
{
Q_OBJECT
public:
enum State {
DISCONNECTED,
ICEFAILED,
INITIATING,
INITIATED,
OFFERSENT,
ANSWERSENT,
CONNECTING,
CONNECTED,
};
Q_ENUM(State);
Q_PROPERTY(CallSession::State state READ state NOTIFY stateChanged)
Q_PROPERTY(bool muted READ muted WRITE setMuted NOTIFY mutedChanged)
// For outgoing calls
static CallSession *startCall(const QStringList &turnUris, QObject *parent = nullptr);
void acceptAnswer(const QString &sdp, const QVector<Candidate> &candidates, const QString &parent);
// For incoming calls
static CallSession *
acceptCall(const QString &sdp, const QVector<Candidate> &candidates, const QStringList &turnUris, const QString &userId, QObject *parent = nullptr);
void end();
void renegotiateOffer(const QString &offer, const QString &userId, bool answer);
void setTurnServers(QStringList servers);
static QStringList missingPlugins();
CallSession::State state() const;
void toggleCamera();
bool muted() const;
void setMuted(bool muted);
void setMetadata(QJsonObject metadata);
void acceptCandidates(const QVector<Candidate> &candidates);
QMap<QString, QString> msidToUserId;
Q_SIGNALS:
void stateChanged();
void offerCreated(const QString &sdp, const QVector<Candidate> &candidates);
void answerCreated(const QString &sdp, const QVector<Candidate> &candidates);
void mutedChanged();
void newVideoStream(VideoStream *stream);
void renegotiate(QString sdp, const QString &type);
private:
CallSession(QObject *parent = nullptr);
void acceptOffer(const QString &sdp, const QVector<Candidate> remoteCandidates, const QString &userId);
void createCall();
void setRemoteDescription(GstWebRTCSessionDescription *remote, const QString &userId, GstPromise *promise = nullptr);
void startPipeline();
void createPipeline();
bool addVideoPipeline();
void setState(CallSession::State state);
GstPad *m_activePad;
GstElement *m_inputSelector;
CallSession::State m_state = CallSession::DISCONNECTED;
unsigned int m_busWatchId = 0;
QStringList m_turnServers;
QVector<Candidate> m_localCandidates;
QString m_localSdp;
GstElement *m_pipe = nullptr;
bool m_isOffering = false;
QMap<int, QString> ssrcToMsid;
QJsonObject m_metadata;
GstPad *m_inactivePad;
};

165
src/call/devicemonitor.cpp Normal file
View File

@@ -0,0 +1,165 @@
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "devicemonitor.h"
#include "voiplogging.h"
#include <QTimer>
QDebug operator<<(QDebug dbg, const GstStructure *props)
{
QDebugStateSaver saver(dbg);
auto asStr = gst_structure_to_string(props);
dbg << asStr;
g_free(asStr);
return dbg;
}
static gboolean deviceCallback(GstBus *bus, GstMessage *message, gpointer user_data)
{
Q_UNUSED(bus);
auto monitor = static_cast<DeviceMonitor *>(user_data);
return monitor->callback(message);
}
DeviceMonitor::DeviceMonitor()
: QObject()
{
QTimer::singleShot(0, this, &DeviceMonitor::init);
}
void DeviceMonitor::init()
{
if (m_monitor) {
return;
}
m_monitor = gst_device_monitor_new();
GstCaps *caps = gst_caps_new_empty_simple("audio/x-raw");
gst_device_monitor_add_filter(m_monitor, "Audio/Source", caps);
gst_caps_unref(caps);
caps = gst_caps_new_empty_simple("video/x-raw");
gst_device_monitor_add_filter(m_monitor, "Video/Source", caps);
gst_caps_unref(caps);
GstBus *bus = gst_device_monitor_get_bus(m_monitor);
gst_bus_add_watch(bus, deviceCallback, this);
gst_object_unref(bus);
if (!gst_device_monitor_start(m_monitor)) {
qWarning() << "Failed to start device monitor";
}
}
QVector<AudioSource *> DeviceMonitor::audioSources() const
{
return m_audioSources;
}
QVector<VideoSource *> DeviceMonitor::videoSources() const
{
return m_videoSources;
}
void DeviceMonitor::handleVideoSource(GstDevice *device)
{
auto source = new VideoSource();
auto title = gst_device_get_display_name(device);
source->title = QString(title);
g_free(title);
source->device = device;
auto caps = gst_device_get_caps(device);
auto size = gst_caps_get_size(caps);
for (size_t i = 0; i < size; i++) {
VideoCap videoCap;
GstStructure *cap = gst_caps_get_structure(caps, i);
const gchar *name = gst_structure_get_name(cap);
if (strcmp(name, "video/x-raw")) {
// TODO g_free(name);
continue;
}
// TODO g_free(name);
gst_structure_get(cap, "width", G_TYPE_INT, &videoCap.width, "height", G_TYPE_INT, &videoCap.height, nullptr);
const auto framerate = gst_structure_get_value(cap, "framerate");
if (GST_VALUE_HOLDS_FRACTION(framerate)) {
auto numerator = gst_value_get_fraction_numerator(framerate);
auto denominator = gst_value_get_fraction_denominator(framerate);
videoCap.framerates += (float)numerator / denominator;
}
// unref cap?
source->caps += videoCap;
}
m_videoSources += source;
Q_EMIT videoSourceAdded();
}
void DeviceMonitor::handleAudioSource(GstDevice *device)
{
auto source = new AudioSource();
auto title = gst_device_get_display_name(device);
source->title = QString(title);
g_free(title);
GstStructure *props = gst_device_get_properties(device);
gboolean isDefault = false;
if (gst_structure_has_field(props, "is-default")) {
gst_structure_get_boolean(props, "is-default", &isDefault);
}
gst_structure_free(props);
source->isDefault = isDefault;
source->device = device;
m_audioSources += source;
Q_EMIT audioSourceAdded();
}
bool DeviceMonitor::callback(GstMessage *message)
{
GstDevice *device;
switch (GST_MESSAGE_TYPE(message)) {
case GST_MESSAGE_DEVICE_ADDED: {
gst_message_parse_device_added(message, &device);
auto name = gst_device_get_display_name(device);
auto props = gst_device_get_properties(device);
qCDebug(voip) << name << props;
gst_structure_free(props);
if (gst_device_has_classes(device, "Video/Source")) {
handleVideoSource(device);
} else if (gst_device_has_classes(device, "Audio/Source")) {
handleAudioSource(device);
}
g_free(name);
gst_object_unref(device);
break;
}
case GST_MESSAGE_DEVICE_REMOVED: {
gst_message_parse_device_removed(message, &device);
auto name = gst_device_get_display_name(device);
auto props = gst_device_get_properties(device);
qCDebug(voip) << name << props;
if (gst_device_has_classes(device, "Video/Source")) {
m_videoSources.erase(std::remove_if(m_videoSources.begin(),
m_videoSources.end(),
[name](auto d) {
return d->title == QString(name);
}),
m_videoSources.end());
Q_EMIT videoSourceRemoved();
} else if (gst_device_has_classes(device, "Audio/Source")) {
m_audioSources.erase(std::remove_if(m_audioSources.begin(),
m_audioSources.end(),
[name](auto d) {
return d->title == QString(name);
}),
m_audioSources.end());
Q_EMIT audioSourceRemoved();
}
g_free(name);
gst_object_unref(device);
break;
}
default:
break;
}
return G_SOURCE_CONTINUE;
}

59
src/call/devicemonitor.h Normal file
View File

@@ -0,0 +1,59 @@
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <QtCore/QDebug>
#include <QtCore/QObject>
#include <QtCore/QVector>
#include <gst/gst.h>
struct AudioSource {
QString title;
GstDevice *device;
bool isDefault;
};
struct VideoCap {
int width;
int height;
QVector<float> framerates;
};
struct VideoSource {
QString title;
GstDevice *device;
QVector<VideoCap> caps;
};
class DeviceMonitor : public QObject
{
Q_OBJECT
public:
static DeviceMonitor &instance()
{
static DeviceMonitor _instance;
return _instance;
}
QVector<AudioSource *> audioSources() const;
QVector<VideoSource *> videoSources() const;
bool callback(GstMessage *message);
void init();
Q_SIGNALS:
void videoSourceAdded();
void audioSourceAdded();
void videoSourceRemoved();
void audioSourceRemoved();
private:
DeviceMonitor();
GstDeviceMonitor *m_monitor = nullptr;
QVector<AudioSource *> m_audioSources;
QVector<VideoSource *> m_videoSources;
void handleVideoSource(GstDevice *device);
void handleAudioSource(GstDevice *device);
};

142
src/call/videosources.cpp Normal file
View File

@@ -0,0 +1,142 @@
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "videosources.h"
#include <gst/gst.h>
// #include "pipelinemanager.h"
#include <QDebug>
#include <QString>
#include "devicemonitor.h"
#include "neochatconfig.h"
int VideoSources::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return DeviceMonitor::instance().videoSources().size();
}
QVariant VideoSources::data(const QModelIndex &index, int role) const
{
if (index.row() >= DeviceMonitor::instance().videoSources().size()) {
return QVariant(QStringLiteral("DEADBEEF"));
}
if (role == TitleRole) {
return DeviceMonitor::instance().videoSources()[index.row()]->title;
}
return QVariant();
}
QHash<int, QByteArray> VideoSources::roleNames() const
{
return {
{TitleRole, "title"},
};
}
VideoSources::VideoSources()
: QAbstractListModel()
{
connect(&DeviceMonitor::instance(), &DeviceMonitor::videoSourceAdded, this, [this]() {
beginResetModel();
endResetModel();
Q_EMIT currentIndexChanged();
});
connect(&DeviceMonitor::instance(), &DeviceMonitor::videoSourceRemoved, this, [this]() {
beginResetModel();
endResetModel();
Q_EMIT currentIndexChanged();
});
}
void VideoSources::foo(int index)
{
auto device = DeviceMonitor::instance().videoSources()[index]->device;
auto bin = gst_bin_new(nullptr);
GstElement *videoconvert = gst_element_factory_make("videoconvert", nullptr);
// GstElement *videorate = gst_element_factory_make("videorate", nullptr);
GstElement *filter = gst_element_factory_make("capsfilter", nullptr);
GstCaps *caps = gst_caps_new_simple("video/x-raw", "width", G_TYPE_INT, 1920, "height", G_TYPE_INT, 1080, "framerate", GST_TYPE_FRACTION, 5, 1, nullptr);
g_object_set(filter, "caps", caps, nullptr);
gst_caps_unref(caps);
GstElement *deviceElement = gst_device_create_element(device, nullptr);
gst_bin_add_many(GST_BIN(bin), deviceElement, videoconvert, filter, nullptr);
gst_element_link_many(deviceElement, videoconvert, filter, nullptr);
// GstPad *pad = gst_element_get_static_pad(filter, "src");
GstPad *pad = gst_element_get_static_pad(filter, "src");
auto ghostpad = gst_ghost_pad_new("src", pad);
gst_element_add_pad(bin, ghostpad);
gst_object_unref(pad);
// PipelineManager::instance().add(bin);
}
const VideoSource *VideoSources::currentDevice() const
{
const auto config = NeoChatConfig::self();
const QString name = config->camera();
for (const auto &videoSource : DeviceMonitor::instance().videoSources()) {
if (videoSource->title == name) {
qDebug() << "WebRTC: camera:" << name;
return videoSource;
}
}
if (DeviceMonitor::instance().videoSources().length() == 0) {
return nullptr;
}
return DeviceMonitor::instance().videoSources()[0];
}
void VideoSources::setCurrentIndex(int index)
{
if (DeviceMonitor::instance().videoSources().size() == 0) {
return;
}
NeoChatConfig::setCamera(DeviceMonitor::instance().videoSources()[index]->title);
NeoChatConfig::self()->save();
setCapsIndex(0);
}
int VideoSources::currentIndex() const
{
const auto config = NeoChatConfig::self();
const QString name = config->camera();
for (auto i = 0; i < DeviceMonitor::instance().videoSources().size(); i++) {
if (DeviceMonitor::instance().videoSources()[i]->title == name) {
return i;
}
}
return 0;
}
QStringList VideoSources::caps(int index) const
{
if (index >= DeviceMonitor::instance().videoSources().size()) {
return QStringList();
}
const auto &caps = DeviceMonitor::instance().videoSources()[index]->caps;
QStringList strings;
for (const auto &cap : caps) {
strings += QStringLiteral("%1x%2, %3 FPS").arg(cap.width).arg(cap.height).arg(cap.framerates.back());
}
return strings;
}
void VideoSources::setCapsIndex(int index)
{
NeoChatConfig::self()->setCameraCaps(index);
NeoChatConfig::self()->save();
Q_EMIT capsIndexChanged();
}
int VideoSources::capsIndex() const
{
return NeoChatConfig::self()->cameraCaps();
}

51
src/call/videosources.h Normal file
View File

@@ -0,0 +1,51 @@
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <QtCore/QAbstractListModel>
#include <gst/gst.h>
#include "devicemonitor.h"
class VideoSources : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
Q_PROPERTY(int capsIndex READ capsIndex WRITE setCapsIndex NOTIFY capsIndexChanged)
public:
enum Roles {
TitleRole = Qt::UserRole + 1,
DeviceRole,
};
static VideoSources &instance()
{
static VideoSources _instance;
return _instance;
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QHash<int, QByteArray> roleNames() const override;
Q_INVOKABLE void foo(int index);
const VideoSource *currentDevice() const;
void setCurrentIndex(int index);
int currentIndex() const;
void setCapsIndex(int index);
int capsIndex() const;
Q_INVOKABLE QStringList caps(int index) const;
Q_SIGNALS:
void currentIndexChanged();
void capsIndexChanged();
private:
VideoSources();
};

View File

@@ -14,8 +14,6 @@
#include <Sonnet/BackgroundChecker>
#include <Sonnet/Settings>
#include "models/actionsmodel.h"
#include "models/roomlistmodel.h"
#include "neochatroom.h"
class SyntaxHighlighter : public QSyntaxHighlighter
@@ -138,12 +136,13 @@ int ChatDocumentHandler::completionStartIndex() const
return 0;
}
#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0)
#if !defined(Q_OS_ANDROID) && QT_VERSION > QT_VERSION_CHECK(6, 0, 0)
const long long cursor = cursorPosition();
#else
const auto cursor = cursorPosition();
#endif
const auto &text = getText();
auto start = std::min(cursor, text.size()) - 1;
while (start > -1) {
if (text.at(start) == QLatin1Char(' ')) {
@@ -324,3 +323,35 @@ void ChatDocumentHandler::pushMention(const Mention mention) const
m_room->mentions()->push_back(mention);
}
}
QColor ChatDocumentHandler::mentionColor() const
{
return m_mentionColor;
}
void ChatDocumentHandler::setMentionColor(const QColor &color)
{
if (m_mentionColor == color) {
return;
}
m_mentionColor = color;
m_highlighter->mentionFormat.setForeground(m_mentionColor);
m_highlighter->rehighlight();
Q_EMIT mentionColorChanged();
}
QColor ChatDocumentHandler::errorColor() const
{
return m_errorColor;
}
void ChatDocumentHandler::setErrorColor(const QColor &color)
{
if (m_errorColor == color) {
return;
}
m_errorColor = color;
m_highlighter->errorFormat.setForeground(m_errorColor);
m_highlighter->rehighlight();
Q_EMIT errorColorChanged();
}

View File

@@ -8,13 +8,54 @@
#include <QTextCursor>
#include "models/completionmodel.h"
#include "models/userlistmodel.h"
#include "neochatroom.h"
class QTextDocument;
class NeoChatRoom;
class SyntaxHighlighter;
/**
* @class ChatDocumentHandler
*
* Handle the QQuickTextDocument of a qml text item.
*
* The class provides functionality to highlight text in the text document as well
* as providing completion functionality via a CompletionModel.
*
* The ChatDocumentHandler is also linked to a NeoChatRoom to provide functionality
* to save the chat document text when switching between rooms.
*
* To get the full functionality the cursor position and text selection information
* need to be passed in. For example:
*
* @code{.qml}
* import QtQuick 2.0
* import QtQuick.Controls 2.15 as QQC2
*
* import org.kde.kirigami 2.12 as Kirigami
* import org.kde.neochat 1.0
*
* QQC2.TextArea {
* id: textField
*
* // Set this to a NeoChatRoom object.
* property var room
*
* ChatDocumentHandler {
* id: documentHandler
* document: textField.textDocument
* cursorPosition: textField.cursorPosition
* selectionStart: textField.selectionStart
* selectionEnd: textField.selectionEnd
* mentionColor: Kirigami.Theme.linkColor
* errorColor: Kirigami.Theme.negativeTextColor
* room: textField.room
* }
* }
* @endcode
*
* @sa QQuickTextDocument, CompletionModel, NeoChatRoom
*/
class ChatDocumentHandler : public QObject
{
Q_OBJECT
@@ -26,15 +67,50 @@ class ChatDocumentHandler : public QObject
* from the correct parameters in the assigned room.
*/
Q_PROPERTY(bool isEdit READ isEdit WRITE setIsEdit NOTIFY isEditChanged)
/**
* @brief The QQuickTextDocument that is being handled.
*/
Q_PROPERTY(QQuickTextDocument *document READ document WRITE setDocument NOTIFY documentChanged)
/**
* @brief The current saved cursor position.
*/
Q_PROPERTY(int cursorPosition READ cursorPosition WRITE setCursorPosition NOTIFY cursorPositionChanged)
/**
* @brief The start position of any currently selected text.
*/
Q_PROPERTY(int selectionStart READ selectionStart WRITE setSelectionStart NOTIFY selectionStartChanged)
/**
* @brief The end position of any currently selected text.
*/
Q_PROPERTY(int selectionEnd READ selectionEnd WRITE setSelectionEnd NOTIFY selectionEndChanged)
/**
* @brief The current CompletionModel.
*
* This is typically provided to a qml component to visualise the current
* completion results.
*/
Q_PROPERTY(CompletionModel *completionModel READ completionModel NOTIFY completionModelChanged)
/**
* @brief The current room that the the text document is being handled for.
*/
Q_PROPERTY(NeoChatRoom *room READ room WRITE setRoom NOTIFY roomChanged)
/**
* @brief The color to highlight user mentions.
*/
Q_PROPERTY(QColor mentionColor READ mentionColor WRITE setMentionColor NOTIFY mentionColorChanged);
/**
* @brief The color to highlight spelling errors.
*/
Q_PROPERTY(QColor errorColor READ errorColor WRITE setErrorColor NOTIFY errorColorChanged);
public:
explicit ChatDocumentHandler(QObject *parent = nullptr);
@@ -60,6 +136,13 @@ public:
void updateCompletions();
CompletionModel *completionModel() const;
[[nodiscard]] QColor mentionColor() const;
void setMentionColor(const QColor &color);
[[nodiscard]] QColor errorColor() const;
void setErrorColor(const QColor &color);
Q_SIGNALS:
void isEditChanged();
void documentChanged();
@@ -68,17 +151,22 @@ Q_SIGNALS:
void completionModelChanged();
void selectionStartChanged();
void selectionEndChanged();
void errorColorChanged();
void mentionColorChanged();
private:
int completionStartIndex() const;
bool m_isEdit;
bool m_isEdit = false;
QQuickTextDocument *m_document;
QPointer<QQuickTextDocument> m_document;
QPointer<NeoChatRoom> m_room;
bool completionVisible = false;
QColor m_mentionColor;
QColor m_errorColor;
int m_cursorPosition;
int m_selectionStart;
int m_selectionEnd;

View File

@@ -62,10 +62,10 @@ QString Clipboard::saveImage(QString localPath) const
void Clipboard::saveText(QString message)
{
static QRegularExpression re(QStringLiteral("<[^>]*>"));
auto *mineData = new QMimeData; // ownership is transferred to clipboard
mineData->setHtml(message);
mineData->setText(message.replace(re, QString()));
m_clipboard->setMimeData(mineData);
auto *mimeData = new QMimeData; // ownership is transferred to clipboard
mimeData->setHtml(message);
mimeData->setText(message.replace(re, QString()));
m_clipboard->setMimeData(mimeData);
}
void Clipboard::setImage(const QUrl &url)

View File

@@ -9,23 +9,60 @@ class QClipboard;
class QImage;
/**
* @class Clipboard
*
* Clipboard proxy
*
* Used to set and retrieve content from the clipboard.
*/
class Clipboard : public QObject
{
Q_OBJECT
/**
* @brief Whether the current clipboard content is an image.
*/
Q_PROPERTY(bool hasImage READ hasImage NOTIFY imageChanged)
/**
* @brief Return the current clipboard content image.
*
* Returns a null image if the clipboard does not contain an image or if it
* contains an image in an unsupported image format.
*/
Q_PROPERTY(QImage image READ image NOTIFY imageChanged)
public:
explicit Clipboard(QObject *parent = nullptr);
[[nodiscard]] bool hasImage() const;
[[nodiscard]] QImage image() const;
/**
* @brief Save the current clipboard image to file.
*
* If the clipboard does not contain an image or if it contains an image in an
* unsupported image format nothing happens.
*
* The given file path must be both valid and local or nothing happens.
*
* @param localPath the path to save the image. A default path for the app cache
* will be used if available and this is empty.
*
* @return A QString with the path that the image was saved to. The string will
* be empty if nothing was saved.
*/
Q_INVOKABLE QString saveImage(QString localPath = {}) const;
/**
* @brief Set the clipboard content to the input message.
*/
Q_INVOKABLE void saveText(QString message);
/**
* @brief Set the clipboard content to the input image.
*/
Q_INVOKABLE void setImage(const QUrl &image);
private:

View File

@@ -8,18 +8,53 @@
class QAbstractItemModel;
class KColorSchemeManager;
/**
* @class ColorSchemer
*
* A class to provide a wrapper around KColorSchemeManager to make it available in
* QML.
*
* @sa KColorSchemeManager
*/
class ColorSchemer : public QObject
{
Q_OBJECT
/**
* @brief A QAbstractItemModel of all available color schemes.
*
* @sa QAbstractItemModel
*/
Q_PROPERTY(QAbstractItemModel *model READ model CONSTANT)
public:
ColorSchemer(QObject *parent = nullptr);
~ColorSchemer();
QAbstractItemModel *model() const;
/**
* @brief Activates the KColorScheme identified by the provided index.
*
* @sa KColorScheme
*/
Q_INVOKABLE void apply(int idx);
/**
* @brief Activates the KColorScheme with the given name.
*
* @sa KColorScheme
*/
Q_INVOKABLE void apply(const QString &name);
/**
* @brief Returns the index for the scheme with the given name.
*/
Q_INVOKABLE int indexForScheme(const QString &name) const;
/**
* @brief Returns the name for the scheme with the given index.
*/
Q_INVOKABLE QString nameForIndex(int index) const;
private:

View File

@@ -45,7 +45,6 @@
#include <qt_connection_util.h>
#ifdef QUOTIENT_07
#include <csapi/notifications.h>
#include <eventstats.h>
#endif
@@ -73,24 +72,8 @@ Controller::Controller(QObject *parent)
setApplicationProxy();
#ifndef Q_OS_ANDROID
if (NeoChatConfig::self()->systemTray()) {
m_trayIcon = new TrayIcon(this);
m_trayIcon->show();
connect(m_trayIcon, &TrayIcon::showWindow, this, &Controller::showWindow);
QGuiApplication::setQuitOnLastWindowClosed(false);
}
connect(NeoChatConfig::self(), &NeoChatConfig::SystemTrayChanged, this, [this]() {
if (NeoChatConfig::self()->systemTray()) {
m_trayIcon = new TrayIcon(this);
m_trayIcon->show();
connect(m_trayIcon, &TrayIcon::showWindow, this, &Controller::showWindow);
} else {
disconnect(m_trayIcon, &TrayIcon::showWindow, this, &Controller::showWindow);
delete m_trayIcon;
m_trayIcon = nullptr;
}
QGuiApplication::setQuitOnLastWindowClosed(!NeoChatConfig::self()->systemTray());
});
setQuitOnLastWindowClosed();
connect(NeoChatConfig::self(), &NeoChatConfig::SystemTrayChanged, this, &Controller::setQuitOnLastWindowClosed);
#endif
QTimer::singleShot(0, this, [this] {
@@ -125,98 +108,26 @@ Controller::Controller(QObject *parent)
}
#endif
#ifdef QUOTIENT_07
connect(&Accounts, &AccountRegistry::accountCountChanged, this, &Controller::activeConnectionIndexChanged);
#else
connect(&AccountRegistry::instance(), &AccountRegistry::accountCountChanged, this, &Controller::activeConnectionIndexChanged);
#endif
#ifdef QUOTIENT_07
static int oldAccountCount = 0;
connect(&AccountRegistry::instance(), &AccountRegistry::accountCountChanged, this, [=]() {
if (AccountRegistry::instance().size() > oldAccountCount) {
auto connection = AccountRegistry::instance().accounts()[AccountRegistry::instance().size() - 1];
connect(connection, &Connection::syncDone, this, [=]() {
handleNotifications(connection);
connect(&Accounts, &AccountRegistry::accountCountChanged, this, [this]() {
if (Accounts.size() > oldAccountCount) {
auto connection = Accounts.accounts()[Accounts.size() - 1];
connect(connection, &Connection::syncDone, this, [connection]() {
NotificationsManager::instance().handleNotifications(connection);
});
}
oldAccountCount = AccountRegistry::instance().size();
oldAccountCount = Accounts.size();
});
#endif
}
#ifdef QUOTIENT_07
void Controller::handleNotifications(QPointer<Quotient::Connection> connection)
{
static QStringList initial;
static QStringList oldNotifications;
auto job = connection->callApi<GetNotificationsJob>();
connect(job, &BaseJob::success, this, [job, connection]() {
const auto notifications = job->jsonData()["notifications"].toArray();
if (!initial.contains(connection->user()->id())) {
initial.append(connection->user()->id());
for (const auto &n : notifications) {
oldNotifications += n.toObject()["event"].toObject()["event_id"].toString();
}
return;
}
for (const auto &n : notifications) {
const auto notification = n.toObject();
if (notification["read"].toBool()) {
oldNotifications.removeOne(notification["event"].toObject()["event_id"].toString());
continue;
}
if (oldNotifications.contains(notification["event"].toObject()["event_id"].toString())) {
continue;
}
oldNotifications += notification["event"].toObject()["event_id"].toString();
auto room = connection->room(notification["room_id"].toString());
// If room exists, room is NOT active OR the application is NOT active, show notification
if (room
&& !(RoomManager::instance().currentRoom() && room->id() == RoomManager::instance().currentRoom()->id()
&& QGuiApplication::applicationState() == Qt::ApplicationActive)) {
// The room might have been deleted (for example rejected invitation).
auto sender = room->user(notification["event"].toObject()["sender"].toString());
QString body;
if (notification["event"].toObject()["type"].toString() == "org.matrix.msc3381.poll.start") {
body = notification["event"]
.toObject()["content"]
.toObject()["org.matrix.msc3381.poll.start"]
.toObject()["question"]
.toObject()["body"]
.toString();
} else {
body = notification["event"].toObject()["content"].toObject()["body"].toString();
}
if (notification["event"]["type"] == "m.room.encrypted") {
#ifdef Quotient_E2EE_ENABLED
auto decrypted = connection->decryptNotification(notification);
body = decrypted["content"].toObject()["body"].toString();
#endif
if (body.isEmpty()) {
body = i18n("Encrypted Message");
}
}
QImage avatar_image;
if (!sender->avatarUrl(room).isEmpty()) {
avatar_image = sender->avatar(128, room);
} else {
avatar_image = room->avatar(128);
}
NotificationsManager::instance().postNotification(dynamic_cast<NeoChatRoom *>(room),
sender->displayname(room),
body,
avatar_image,
notification["event"].toObject()["event_id"].toString(),
true);
}
}
});
}
#endif
Controller &Controller::instance()
{
static Controller _instance;
@@ -228,38 +139,6 @@ void Controller::showWindow()
WindowController::instance().showAndRaiseWindow(QString());
}
void Controller::loginWithAccessToken(const QString &serverAddr, const QString &user, const QString &token, const QString &deviceName)
{
if (user.isEmpty() || token.isEmpty()) {
return;
}
QUrl serverUrl(serverAddr);
auto conn = new Connection();
if (serverUrl.isValid()) {
conn->setHomeserver(serverUrl);
}
connect(conn, &Connection::connected, this, [this, conn, deviceName] {
AccountSettings account(conn->userId());
account.setKeepLoggedIn(true);
account.setHomeserver(conn->homeserver());
account.setDeviceId(conn->deviceId());
account.setDeviceName(deviceName);
if (!saveAccessTokenToKeyChain(account, conn->accessToken())) {
qWarning() << "Couldn't save access token";
}
account.sync();
addConnection(conn);
setActiveConnection(conn);
});
connect(conn, &Connection::networkError, this, [this](QString error, const QString &, int, int) {
Q_EMIT errorOccured(i18n("Network Error: %1", error));
});
conn->assumeIdentity(user, token, deviceName);
}
void Controller::logout(Connection *conn, bool serverSideLogout)
{
if (!conn) {
@@ -277,10 +156,18 @@ void Controller::logout(Connection *conn, bool serverSideLogout)
job.start();
loop.exec();
#ifdef QUOTIENT_07
if (Accounts.count() > 1) {
#else
if (AccountRegistry::instance().count() > 1) {
#endif
// Only set the connection if the the account being logged out is currently active
if (conn == activeConnection()) {
#ifdef QUOTIENT_07
setActiveConnection(Accounts.accounts()[0]);
#else
setActiveConnection(AccountRegistry::instance().accounts()[0]);
#endif
}
} else {
setActiveConnection(nullptr);
@@ -295,15 +182,15 @@ void Controller::addConnection(Connection *c)
{
Q_ASSERT_X(c, __FUNCTION__, "Attempt to add a null connection");
#ifndef QUOTIENT_07
#ifdef QUOTIENT_07
Accounts.add(c);
#else
AccountRegistry::instance().add(c);
#endif
c->setLazyLoading(true);
connect(c, &Connection::syncDone, this, [this, c] {
setBusy(false);
Q_EMIT syncDone();
c->sync(30000);
@@ -319,8 +206,6 @@ void Controller::addConnection(Connection *c)
}
});
setBusy(true);
c->sync();
Q_EMIT connectionAdded(c);
@@ -456,15 +341,9 @@ bool Controller::saveAccessTokenToKeyChain(const AccountSettings &account, const
void Controller::changeAvatar(Connection *conn, const QUrl &localFile)
{
auto job = conn->uploadFile(localFile.toLocalFile());
#ifdef QUOTIENT_07
if (isJobPending(job)) {
#else
if (isJobRunning(job)) {
#endif
connect(job, &BaseJob::success, this, [conn, job] {
conn->callApi<SetAvatarUrlJob>(conn->userId(), job->contentUri());
});
}
connect(job, &BaseJob::success, this, [conn, job] {
conn->callApi<SetAvatarUrlJob>(conn->userId(), job->contentUri());
});
}
void Controller::markAllMessagesAsRead(Connection *conn)
@@ -548,34 +427,31 @@ NeochatChangePasswordJob::NeochatChangePasswordJob(const QString &newPassword, b
int Controller::accountCount() const
{
#ifdef QUOTIENT_07
return Accounts.count();
#else
return AccountRegistry::instance().count();
#endif
}
bool Controller::quitOnLastWindowClosed()
void Controller::setQuitOnLastWindowClosed()
{
return QGuiApplication::quitOnLastWindowClosed();
}
void Controller::setQuitOnLastWindowClosed(bool value)
{
if (quitOnLastWindowClosed() != value) {
QGuiApplication::setQuitOnLastWindowClosed(value);
Q_EMIT quitOnLastWindowClosedChanged();
#ifndef Q_OS_ANDROID
if (NeoChatConfig::self()->systemTray()) {
m_trayIcon = new TrayIcon(this);
m_trayIcon->show();
connect(m_trayIcon, &TrayIcon::showWindow, this, &Controller::showWindow);
} else {
if (m_trayIcon) {
disconnect(m_trayIcon, &TrayIcon::showWindow, this, &Controller::showWindow);
delete m_trayIcon;
m_trayIcon = nullptr;
}
}
}
bool Controller::busy() const
{
return m_busy;
}
void Controller::setBusy(bool busy)
{
if (m_busy == busy) {
return;
}
m_busy = busy;
Q_EMIT busyChanged();
QGuiApplication::setQuitOnLastWindowClosed(!NeoChatConfig::self()->systemTray());
#else
return;
#endif
}
Connection *Controller::activeConnection() const
@@ -593,6 +469,7 @@ void Controller::setActiveConnection(Connection *connection)
}
if (m_connection != nullptr) {
disconnect(m_connection, &Connection::syncError, this, nullptr);
disconnect(m_connection, &Connection::accountDataChanged, this, nullptr);
}
m_connection = connection;
if (connection != nullptr) {
@@ -611,17 +488,23 @@ void Controller::setActiveConnection(Connection *connection)
m_isOnline = true;
Q_EMIT isOnlineChanged(true);
});
connect(connection, &Connection::requestFailed, this, [=](BaseJob *job) {
connect(connection, &Connection::requestFailed, this, [](BaseJob *job) {
if (dynamic_cast<DownloadFileJob *>(job) && job->jsonData()["errcode"].toString() == "M_TOO_LARGE"_ls) {
RoomManager::instance().warning(i18n("File too large to download."), i18n("Contact your matrix server administrator for support."));
}
});
connect(connection, &Connection::accountDataChanged, this, [this](const QString &type) {
if (type == QLatin1String("org.kde.neochat.account_label")) {
Q_EMIT activeAccountLabelChanged();
}
});
} else {
NeoChatConfig::self()->setActiveConnection(QString());
}
NeoChatConfig::self()->save();
Q_EMIT activeConnectionChanged();
Q_EMIT activeConnectionIndexChanged();
Q_EMIT activeAccountLabelChanged();
}
void Controller::saveWindowGeometry()
@@ -645,16 +528,30 @@ void Controller::createRoom(const QString &name, const QString &topic)
{
auto createRoomJob = m_connection->createRoom(Connection::PublishRoom, "", name, topic, QStringList());
connect(createRoomJob, &CreateRoomJob::failure, this, [this, createRoomJob] {
Q_EMIT errorOccured(i18n("Room creation failed: \"%1\"", createRoomJob->errorString()));
Q_EMIT errorOccured(i18n("Room creation failed: %1", createRoomJob->errorString()));
});
connectSingleShot(
this,
&Controller::roomAdded,
this,
[this](NeoChatRoom *room) {
RoomManager::instance().enterRoom(room);
},
Qt::QueuedConnection);
connectSingleShot(this, &Controller::roomAdded, &RoomManager::instance(), &RoomManager::enterRoom, Qt::QueuedConnection);
}
void Controller::createSpace(const QString &name, const QString &topic)
{
auto createRoomJob = m_connection->createRoom(Connection::UnpublishRoom,
{},
name,
topic,
QStringList(),
{},
{},
false,
{},
{},
QJsonObject{
{"type"_ls, "m.space"_ls},
});
connect(createRoomJob, &CreateRoomJob::failure, this, [this, createRoomJob] {
Q_EMIT errorOccured(i18n("Space creation failed: %1", createRoomJob->errorString()));
});
connectSingleShot(this, &Controller::roomAdded, &RoomManager::instance(), &RoomManager::enterRoom, Qt::QueuedConnection);
}
bool Controller::isOnline() const
@@ -724,11 +621,6 @@ bool Controller::hasWindowSystem() const
#endif
}
QString Controller::plainText(QQuickTextDocument *document) const
{
return document->textDocument()->toPlainText();
}
bool Controller::encryptionSupported() const
{
#ifdef QUOTIENT_07
@@ -809,3 +701,47 @@ bool Controller::isFlatpak() const
return false;
#endif
}
void Controller::setActiveAccountLabel(const QString &label)
{
if (!m_connection) {
return;
}
QJsonObject json{
{"account_label", label},
};
m_connection->setAccountData("org.kde.neochat.account_label", json);
}
QString Controller::activeAccountLabel() const
{
if (!m_connection) {
return {};
}
return m_connection->accountDataJson("org.kde.neochat.account_label")["account_label"].toString();
}
QVariantList Controller::getSupportedRoomVersions(Quotient::Connection *connection)
{
auto roomVersions = connection->availableRoomVersions();
QVariantList supportedRoomVersions;
for (const Quotient::Connection::SupportedRoomVersion &v : roomVersions) {
QVariantMap roomVersionMap;
roomVersionMap.insert("id", v.id);
roomVersionMap.insert("status", v.status);
roomVersionMap.insert("isStable", v.isStable());
supportedRoomVersions.append(roomVersionMap);
}
return supportedRoomVersions;
}
bool Controller::callsSupported() const
{
#ifdef GSTREAMER_AVAILABLE
return true;
#else
return false;
#endif
}

View File

@@ -28,86 +28,205 @@ namespace QKeychain
class ReadPasswordJob;
}
/**
* @class Controller
*
* A singleton class designed to help manage the application.
*
* There are also a bunch of helper functions that currently don't fit anywhere
* else.
*/
class Controller : public QObject
{
Q_OBJECT
/**
* @brief The number of logged in accounts.
*/
Q_PROPERTY(int accountCount READ accountCount NOTIFY accountCountChanged)
Q_PROPERTY(bool quitOnLastWindowClosed READ quitOnLastWindowClosed WRITE setQuitOnLastWindowClosed NOTIFY quitOnLastWindowClosedChanged)
/**
* @brief The current connection for the rest of NeoChat to use.
*/
Q_PROPERTY(Quotient::Connection *activeConnection READ activeConnection WRITE setActiveConnection NOTIFY activeConnectionChanged)
Q_PROPERTY(bool busy READ busy WRITE setBusy NOTIFY busyChanged)
Q_PROPERTY(bool supportSystemTray READ supportSystemTray CONSTANT)
Q_PROPERTY(bool hasWindowSystem READ hasWindowSystem CONSTANT)
Q_PROPERTY(bool isOnline READ isOnline NOTIFY isOnlineChanged)
Q_PROPERTY(bool encryptionSupported READ encryptionSupported CONSTANT)
/**
* @brief The row number in the accounts directory of the active connection.
*/
Q_PROPERTY(int activeConnectionIndex READ activeConnectionIndex NOTIFY activeConnectionIndexChanged)
/**
* @brief The account label for the active account.
*
* Account labels are a concept specific to NeoChat, allowing accounts to be
* labelled, e.g. for "Work", "Private", etc.
*
* Set to an empty string to remove the label.
*/
Q_PROPERTY(QString activeAccountLabel READ activeAccountLabel WRITE setActiveAccountLabel NOTIFY activeAccountLabelChanged)
/**
* @brief Whether the OS NeoChat is running on supports sytem tray icons.
*/
Q_PROPERTY(bool supportSystemTray READ supportSystemTray CONSTANT)
/**
* @brief Whether KWindowSystem specific features are available.
*/
Q_PROPERTY(bool hasWindowSystem READ hasWindowSystem CONSTANT)
/**
* @brief Whether NeoChat is currently able to connect to the server.
*/
Q_PROPERTY(bool isOnline READ isOnline NOTIFY isOnlineChanged)
/**
* @brief Whether the ecryption support has been enabled.
*/
Q_PROPERTY(bool encryptionSupported READ encryptionSupported CONSTANT)
/**
* @brief The current minor version number of libQuotient being used.
*
* This is the only way to gate NeoChat features by libQuotient version in QML.
*
* @note No major version because libQuotient doesn't have any; All are 0.x.
*/
Q_PROPERTY(int quotientMinorVersion READ quotientMinorVersion CONSTANT)
/**
* @brief Whether NeoChat is running as a flatpak.
*
* This is the only way to gate NeoChat features in flatpaks in QML.
*/
Q_PROPERTY(bool isFlatpak READ isFlatpak CONSTANT)
Q_PROPERTY(bool callsSupported READ callsSupported CONSTANT)
public:
/**
* @brief Defines the status after an attempt to change the password on an account.
*/
enum PasswordStatus {
Success, /**< The password was successfully changed. */
Wrong, /**< The current password entered was wrong. */
Other, /**< An unknown problem occurred. */
};
Q_ENUM(PasswordStatus);
static Controller &instance();
[[nodiscard]] int accountCount() const;
void setActiveConnection(Quotient::Connection *connection);
[[nodiscard]] Quotient::Connection *activeConnection() const;
/**
* @brief Add a new connection to the account registry.
*/
void addConnection(Quotient::Connection *c);
/**
* @brief Drop a connection from the account registry.
*/
void dropConnection(Quotient::Connection *c);
Q_INVOKABLE void loginWithAccessToken(const QString &, const QString &, const QString &, const QString &);
Q_INVOKABLE void changePassword(Quotient::Connection *connection, const QString &currentPassword, const QString &newPassword);
Q_INVOKABLE bool setAvatar(Quotient::Connection *connection, const QUrl &avatarSource);
[[nodiscard]] int accountCount() const;
[[nodiscard]] static bool quitOnLastWindowClosed();
void setQuitOnLastWindowClosed(bool value);
[[nodiscard]] bool busy() const;
void setBusy(bool busy);
[[nodiscard]] bool supportSystemTray() const;
bool saveAccessTokenToKeyChain(const Quotient::AccountSettings &account, const QByteArray &accessToken);
int activeConnectionIndex() const;
enum PasswordStatus {
Success,
Wrong,
Other,
};
Q_ENUM(PasswordStatus);
[[nodiscard]] QString activeAccountLabel() const;
void setActiveAccountLabel(const QString &label);
/// \brief Create new room for a group chat.
/**
* @brief Save an access token to the keychain for the given account.
*/
bool saveAccessTokenToKeyChain(const Quotient::AccountSettings &account, const QByteArray &accessToken);
/**
* @brief Change the password for an account.
*
* The function emits a passwordStatus signal with a PasswordStatus value when
* complete.
*
* @sa PasswordStatus, passwordStatus
*/
Q_INVOKABLE void changePassword(Quotient::Connection *connection, const QString &currentPassword, const QString &newPassword);
/**
* @brief Change the avatar for an account.
*/
Q_INVOKABLE bool setAvatar(Quotient::Connection *connection, const QUrl &avatarSource);
/**
* @brief Create new room for a group chat.
*/
Q_INVOKABLE void createRoom(const QString &name, const QString &topic);
/// \brief Join a room.
/**
* @brief Create new space.
*/
Q_INVOKABLE void createSpace(const QString &name, const QString &topic);
/**
* @brief Join a room.
*/
Q_INVOKABLE void joinRoom(const QString &alias);
/**
* @brief Join a direct chat with the given user.
*
* If a direct chat with the user doesn't exist one is created and then joined.
*/
Q_INVOKABLE void openOrCreateDirectChat(NeoChatUser *user);
[[nodiscard]] bool supportSystemTray() const;
/**
* @brief Set the background blur status of the given item.
*/
Q_INVOKABLE void setBlur(QQuickItem *item, bool blur);
bool isOnline() const;
Q_INVOKABLE QString formatDuration(quint64 msecs, KFormat::DurationFormatOptions options = KFormat::DefaultDuration) const;
Q_INVOKABLE QString formatByteSize(double size, int precision = 1) const;
Q_INVOKABLE void openOrCreateDirectChat(NeoChatUser *user);
Q_INVOKABLE void setBlur(QQuickItem *item, bool blur);
Q_INVOKABLE QString plainText(QQuickTextDocument *document) const;
bool encryptionSupported() const;
Q_INVOKABLE void forceRefreshTextDocument(QQuickTextDocument *textDocument, QQuickItem *item);
/**
* @brief Sets the QNetworkProxy for the application.
*
* @sa QNetworkProxy::setApplicationProxy
*/
Q_INVOKABLE void setApplicationProxy();
int quotientMinorVersion() const;
bool isFlatpak() const;
bool callsSupported() const;
/**
* @brief Return a string for the input timestamp.
*
* The output format depends on the KFormat::DurationFormatOptions chosen.
*
* @sa KFormat::DurationFormatOptions
*/
Q_INVOKABLE QString formatDuration(quint64 msecs, KFormat::DurationFormatOptions options = KFormat::DefaultDuration) const;
/**
* @brief Return a human readable string for a given input number of bytes.
*/
Q_INVOKABLE QString formatByteSize(double size, int precision = 1) const;
/**
* @brief Force a QQuickTextDocument to refresh when images are loaded.
*
* HACK: This is a workaround for QTBUG 93281.
*/
Q_INVOKABLE void forceRefreshTextDocument(QQuickTextDocument *textDocument, QQuickItem *item);
Q_INVOKABLE QVariantList getSupportedRoomVersions(Quotient::Connection *connection);
private:
explicit Controller(QObject *parent = nullptr);
QPointer<Quotient::Connection> m_connection;
bool m_busy = false;
TrayIcon *m_trayIcon = nullptr;
QKeychain::ReadPasswordJob *loadAccessTokenFromKeyChain(const Quotient::AccountSettings &account);
@@ -118,16 +237,13 @@ private:
QMap<Quotient::Room *, int> m_notificationCounts;
bool hasWindowSystem() const;
#ifdef QUOTIENT_07
void handleNotifications(QPointer<Quotient::Connection> connection);
#endif
private Q_SLOTS:
void invokeLogin();
void showWindow();
void setQuitOnLastWindowClosed();
Q_SIGNALS:
void busyChanged();
/// Error occurred because of user inputs
void errorOccured(const QString &error);
@@ -152,6 +268,7 @@ Q_SIGNALS:
void keyVerificationKey(const QString &sas);
void activeConnectionIndexChanged();
void roomAdded(NeoChatRoom *room);
void activeAccountLabelChanged();
public Q_SLOTS:
void logout(Quotient::Connection *conn, bool serverSideLogout);

153
src/delegatesizehelper.cpp Normal file
View File

@@ -0,0 +1,153 @@
// SPDX-FileCopyrightText: 2023 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#include "delegatesizehelper.h"
#include <cmath>
#include <QDebug>
DelegateSizeHelper::DelegateSizeHelper(QObject *parent)
: QObject(parent)
{
}
qreal DelegateSizeHelper::parentWidth() const
{
return m_parentWidth;
}
void DelegateSizeHelper::setParentWidth(qreal parentWidth)
{
if (parentWidth == m_parentWidth) {
return;
}
m_parentWidth = parentWidth;
Q_EMIT parentWidthChanged();
Q_EMIT currentPercentageWidthChanged();
Q_EMIT currentWidthChanged();
}
qreal DelegateSizeHelper::startBreakpoint() const
{
return m_startBreakpoint;
}
void DelegateSizeHelper::setStartBreakpoint(qreal startBreakpoint)
{
if (startBreakpoint == m_startBreakpoint) {
return;
}
m_startBreakpoint = startBreakpoint;
Q_EMIT startBreakpointChanged();
}
qreal DelegateSizeHelper::endBreakpoint() const
{
return m_endBreakpoint;
}
void DelegateSizeHelper::setEndBreakpoint(qreal endBreakpoint)
{
if (endBreakpoint == m_endBreakpoint) {
return;
}
m_endBreakpoint = endBreakpoint;
Q_EMIT endBreakpointChanged();
}
int DelegateSizeHelper::startPercentWidth() const
{
return m_startPercentWidth;
}
void DelegateSizeHelper::setStartPercentWidth(int startPercentWidth)
{
if (startPercentWidth == m_startPercentWidth) {
return;
}
m_startPercentWidth = startPercentWidth;
Q_EMIT startPercentWidthChanged();
}
int DelegateSizeHelper::endPercentWidth() const
{
return m_endPercentWidth;
}
void DelegateSizeHelper::setEndPercentWidth(int endPercentWidth)
{
if (endPercentWidth == m_endPercentWidth) {
return;
}
m_endPercentWidth = endPercentWidth;
Q_EMIT endPercentWidthChanged();
}
qreal DelegateSizeHelper::maxWidth() const
{
return m_maxWidth;
}
void DelegateSizeHelper::setMaxWidth(qreal maxWidth)
{
if (maxWidth == m_maxWidth) {
return;
}
m_maxWidth = maxWidth;
Q_EMIT maxWidthChanged();
}
int DelegateSizeHelper::calculateCurrentPercentageWidth() const
{
// Don't do anything if m_parentWidth hasn't been set yet.
if (m_parentWidth < 0) {
return -1;
}
// Don't bother with calculations for a horizontal line.
if (m_startPercentWidth == m_endPercentWidth) {
return m_startPercentWidth;
}
// Dividing by zero is a bad idea.
if (m_startBreakpoint == m_endBreakpoint) {
qWarning() << "DelegateSizeHelper::calculateCurrentPercentageWidth() - m_startBreakpoint is equal to m_endBreakpoint this would lead to divide by "
"zero, aborting";
return -1;
}
// Fit to y = mx + c
qreal m = (m_endPercentWidth - m_startPercentWidth) / (m_endBreakpoint - m_startBreakpoint);
qreal c = m_startPercentWidth - m * m_startBreakpoint;
// This allows us to clamp correctly if the start or end width is bigger.
bool endPercentBigger = m_endPercentWidth > m_startPercentWidth;
int maxPercentWidth = endPercentBigger ? m_endPercentWidth : m_startPercentWidth;
int minPercentWidth = endPercentBigger ? m_startPercentWidth : m_endPercentWidth;
int calcPercentWidth = std::ceil(m * m_parentWidth + c);
return std::clamp(calcPercentWidth, minPercentWidth, maxPercentWidth);
}
int DelegateSizeHelper::currentPercentageWidth() const
{
return calculateCurrentPercentageWidth();
}
qreal DelegateSizeHelper::currentWidth() const
{
if (m_parentWidth < 0) {
return 0.0;
}
int percentWidth = calculateCurrentPercentageWidth();
// - 1 means bad input values so don't try to calculate.
if (percentWidth == -1) {
return 0.0;
}
qreal absoluteWidth = m_parentWidth * percentWidth * 0.01;
if (m_maxWidth < 0.0) {
return std::ceil(absoluteWidth);
} else {
return std::ceil(std::min(absoluteWidth, m_maxWidth));
}
}

123
src/delegatesizehelper.h Normal file
View File

@@ -0,0 +1,123 @@
// SPDX-FileCopyrightText: 2023 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#pragma once
#include <QObject>
/**
* @class DelegateSizeHelper
*
* A class to help calculate the current width of a chat delegate/bar.
*
* The aim is to support a dynamic sizing based upon the width of the page. There is
* a built in curve that allows the width to transition between two percentages based
* upon a start and finish break point. This is to provide better convergence where
* generally the delegate will need to fill all or most the screen when thin but
* should max out in size and only fill a lower percentage of the screen when wide.
*
* @note While the main intended usage is to start with a high percentage when the parentWidth
* is small and transition to a lower one when large, the math is setup for the
* general case so any combination of parameters works.
*/
class DelegateSizeHelper : public QObject
{
Q_OBJECT
/**
* @brief The width of the component's parent.
*/
Q_PROPERTY(qreal parentWidth READ parentWidth WRITE setParentWidth NOTIFY parentWidthChanged)
/**
* @brief The width (in px) when the width percentage should start to transition.
*/
Q_PROPERTY(qreal startBreakpoint READ startBreakpoint WRITE setStartBreakpoint NOTIFY startBreakpointChanged)
/**
* @brief The width (in px) when the width percentage should finish transitioning.
*/
Q_PROPERTY(qreal endBreakpoint READ endBreakpoint WRITE setEndBreakpoint NOTIFY endBreakpointChanged)
/**
* @brief The width (in %) of the component at or before the startBreakpoint.
*
* @sa startBreakpoint
*/
Q_PROPERTY(int startPercentWidth READ startPercentWidth WRITE setStartPercentWidth NOTIFY startPercentWidthChanged)
/**
* @brief The width (in %) of the component at or after the endBreakpoint.
*
* @sa endBreakpoint
*/
Q_PROPERTY(int endPercentWidth READ endPercentWidth WRITE setEndPercentWidth NOTIFY endPercentWidthChanged)
/**
* @brief The absolute maximum width (in px) the component can be.
*/
Q_PROPERTY(qreal maxWidth READ maxWidth WRITE setMaxWidth NOTIFY maxWidthChanged)
/**
* @brief The width (in %) of the component at the current parentWidth.
*
* Will return -1 if no parentWidth is set or startBreakpoint == endBreakpoint.
*
* @sa parentWidth, startBreakpoint, endBreakpoint
*/
Q_PROPERTY(int currentPercentageWidth READ currentPercentageWidth NOTIFY currentPercentageWidthChanged)
/**
* @brief The width (in px) of the component at the current parentWidth.
*
* Will return 0.0 if no parentWidth is set.
*
* @sa parentWidth
*/
Q_PROPERTY(qreal currentWidth READ currentWidth NOTIFY currentWidthChanged)
public:
DelegateSizeHelper(QObject *parent = nullptr);
qreal parentWidth() const;
void setParentWidth(qreal parentWidth);
qreal startBreakpoint() const;
void setStartBreakpoint(qreal startBreakpoint);
qreal endBreakpoint() const;
void setEndBreakpoint(qreal endBreakpoint);
int startPercentWidth() const;
void setStartPercentWidth(int startPercentWidth);
int endPercentWidth() const;
void setEndPercentWidth(int endPercentWidth);
qreal maxWidth() const;
void setMaxWidth(qreal maxWidth);
int currentPercentageWidth() const;
qreal currentWidth() const;
Q_SIGNALS:
void parentWidthChanged();
void startBreakpointChanged();
void endBreakpointChanged();
void startPercentWidthChanged();
void endPercentWidthChanged();
void maxWidthChanged();
void currentPercentageWidthChanged();
void currentWidthChanged();
private:
qreal m_parentWidth = -1.0;
qreal m_startBreakpoint;
qreal m_endBreakpoint;
int m_startPercentWidth;
int m_endPercentWidth;
qreal m_maxWidth = -1.0;
int calculateCurrentPercentageWidth() const;
};

View File

@@ -5,6 +5,13 @@
#include <QVariant>
/**
* @class EmojiTones
*
* This class provides a _tones variable with the available emoji tones to EmojiModel.
*
* @sa EmojiModel
*/
class EmojiTones
{
private:

View File

@@ -0,0 +1,92 @@
// SPDX-FileCopyrightText: 2021-2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "imagepackevent.h"
#include <QJsonObject>
using namespace Quotient;
ImagePackEventContent::ImagePackEventContent(const QJsonObject &json)
{
if (json.contains(QStringLiteral("pack"))) {
pack = ImagePackEventContent::Pack{
fromJson<Omittable<QString>>(json["pack"].toObject()["display_name"]),
#ifdef QUOTIENT_07
fromJson<Omittable<QUrl>>(json["pack"].toObject()["avatar_url"]),
#else
QUrl(),
#endif
fromJson<Omittable<QStringList>>(json["pack"].toObject()["usage"]),
fromJson<Omittable<QString>>(json["pack"].toObject()["attribution"]),
};
} else {
pack = none;
}
const auto &keys = json["images"].toObject().keys();
for (const auto &k : keys) {
Omittable<EventContent::ImageInfo> info;
if (json["images"][k].toObject().contains(QStringLiteral("info"))) {
#ifdef QUOTIENT_07
info = EventContent::ImageInfo(QUrl(json["images"][k]["url"].toString()), json["images"][k]["info"].toObject(), k);
#else
info = EventContent::ImageInfo(QUrl(json["images"][k]["url"].toString()), json["images"][k].toObject(), k);
#endif
} else {
info = none;
}
images += ImagePackImage{
k,
#ifdef QUOTIENT_07
fromJson<QUrl>(json["images"][k]["url"].toString()),
#else
QUrl(),
#endif
fromJson<Omittable<QString>>(json["images"][k]["body"]),
info,
fromJson<Omittable<QStringList>>(json["images"][k]["usage"]),
};
}
}
void ImagePackEventContent::fillJson(QJsonObject *o) const
{
if (pack) {
QJsonObject packJson;
if (pack->displayName) {
packJson["display_name"] = *pack->displayName;
}
if (pack->usage) {
QJsonArray usageJson;
for (const auto &usage : *pack->usage) {
usageJson += usage;
}
packJson["usage"] = usageJson;
}
if (pack->avatarUrl) {
packJson["avatar_url"] = pack->avatarUrl->toString();
}
if (pack->attribution) {
packJson["attribution"] = *pack->attribution;
}
(*o)["pack"_ls] = packJson;
}
QJsonObject imagesJson;
for (const auto &image : images) {
QJsonObject imageJson;
imageJson["url"] = image.url.toString();
if (image.body) {
imageJson["body"] = *image.body;
}
if (image.usage) {
QJsonArray usageJson;
for (const auto &usage : *image.usage) {
usageJson += usage;
}
imageJson["usage"] = usageJson;
}
imagesJson[image.shortcode] = imageJson;
}
(*o)["images"_ls] = imagesJson;
}

106
src/events/imagepackevent.h Normal file
View File

@@ -0,0 +1,106 @@
// SPDX-FileCopyrightText: 2021-2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <QVector>
#include <events/eventcontent.h>
#include <events/stateevent.h>
namespace Quotient
{
/**
* @class ImagePackEventContent
*
* A class to define the content of an image pack event.
*
* See Matrix MSC2545 for more details.
* https://github.com/Sorunome/matrix-doc/blob/soru/emotes/proposals/2545-emotes.md
*
* @sa ImagePackEvent
*/
class ImagePackEventContent
{
public:
/**
* @brief Defines the properties of an image pack.
*/
struct Pack {
Quotient::Omittable<QString> displayName; /**< The display name of the pack. */
Quotient::Omittable<QUrl> avatarUrl; /**< The source mxc URL for the pack avatar. */
Quotient::Omittable<QStringList> usage; /**< An array of the usages for this pack. Possible usages are "emoticon" and "sticker". */
Quotient::Omittable<QString> attribution; /**< The attribution for the pack author(s). */
};
/**
* @brief Defines the properties of an image pack image.
*/
struct ImagePackImage {
QString shortcode; /**< The shortcode for the image. */
QUrl url; /**< The mxc URL for this image. */
Quotient::Omittable<QString> body; /**< An optional text body for this image. */
Quotient::Omittable<Quotient::EventContent::ImageInfo> info; /**< The ImageInfo object used for the info block of m.sticker events. */
/**
* @brief An array of the usages for this image.
*
* The possible values match those of the usage key of a pack object.
*/
Quotient::Omittable<QStringList> usage;
};
/**
* @brief Return the pack properties.
*
* @sa Pack
*/
Quotient::Omittable<Pack> pack;
/**
* @brief Return a vector of images in the pack.
*
* @sa ImagePackImage
*/
QVector<ImagePackEventContent::ImagePackImage> images;
explicit ImagePackEventContent(const QJsonObject &o);
/**
* @brief The definition of how to convert the content to Json.
*
* This is a specialization of the standard fillJson function from libQuotient.
*
* @sa Quotient::converters
*/
void fillJson(QJsonObject *o) const;
};
/**
* @class ImagePackEvent
*
* Class to define an image pack state event.
*
* The event content is ImagePackEventContent.
*
* @sa Quotient::StateEvent, ImagePackEventContent
*/
#ifdef QUOTIENT_07
class ImagePackEvent : public KeyedStateEventBase<ImagePackEvent, ImagePackEventContent>
#else
class ImagePackEvent : public StateEvent<ImagePackEventContent>
#endif
{
public:
#ifdef QUOTIENT_07
QUO_EVENT(ImagePackEvent, "im.ponies.room_emotes")
using KeyedStateEventBase::KeyedStateEventBase;
#else
DEFINE_EVENT_TYPEID("im.ponies.room_emotes", ImagePackEvent)
explicit ImagePackEvent(const QJsonObject &obj)
: StateEvent(typeId(), obj)
{
}
#endif
};
REGISTER_EVENT_TYPE(ImagePackEvent)
}

View File

@@ -7,6 +7,13 @@
namespace Quotient
{
/**
* @class JoinRulesEvent
*
* Class to define a join rule state event.
*
* @sa Quotient::StateEvent
*/
#ifdef QUOTIENT_07
class JoinRulesEvent : public StateEvent
#else
@@ -29,7 +36,20 @@ public:
{
}
/**
* @brief The join rule for the room.
*
* see https://spec.matrix.org/latest/client-server-api/#mroomjoin_rules for
* the available join rules for a room.
*/
QString joinRule() const;
/**
* @brief The allow rule for restricted rooms.
*
* see https://spec.matrix.org/latest/client-server-api/#mroomjoin_rules for
* full details on allow rules.
*/
QJsonArray allow() const;
};
REGISTER_EVENT_TYPE(JoinRulesEvent)

72
src/events/pollevent.h Normal file
View File

@@ -0,0 +1,72 @@
// SPDX-FileCopyrightText: 2022 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <events/eventcontent.h>
#include <events/roomevent.h>
namespace Quotient
{
/**
* @class PollStartEvent
*
* Class to define a poll start event.
*
* See MSC3381 for full details on polls in the matrix spec
* https://github.com/matrix-org/matrix-spec-proposals/blob/travis/msc/polls/proposals/3381-polls.md.
*
* @sa Quotient::RoomEvent
*/
class PollStartEvent : public RoomEvent
{
public:
QUO_EVENT(PollStartEvent, "org.matrix.msc3381.poll.start");
explicit PollStartEvent(const QJsonObject &obj);
/**
* @brief The maximum number of options a user can select in a poll.
*/
int maxSelections() const;
/**
* @brief The question being asked in the poll.
*/
QString question() const;
};
/**
* @class PollResponseEvent
*
* Class to define a poll response event.
*
* See MSC3381 for full details on polls in the matrix spec
* https://github.com/matrix-org/matrix-spec-proposals/blob/travis/msc/polls/proposals/3381-polls.md.
*
* @sa Quotient::RoomEvent
*/
class PollResponseEvent : public RoomEvent
{
public:
QUO_EVENT(PollResponseEvent, "org.matrix.msc3381.poll.response");
explicit PollResponseEvent(const QJsonObject &obj);
explicit PollResponseEvent(const QString &pollStartEventId, QStringList responses);
};
/**
* @class PollEndEvent
*
* Class to define a poll end event.
*
* See MSC3381 for full details on polls in the matrix spec
* https://github.com/matrix-org/matrix-spec-proposals/blob/travis/msc/polls/proposals/3381-polls.md.
*
* @sa Quotient::RoomEvent
*/
class PollEndEvent : public RoomEvent
{
public:
QUO_EVENT(PollEndEvent, "org.matrix.msc3381.poll.end");
explicit PollEndEvent(const QJsonObject &obj);
};
}

55
src/events/stickerevent.h Normal file
View File

@@ -0,0 +1,55 @@
// SPDX-FileCopyrightText: 2020 Carl Schwan <carlschwan@kde.org>
// SPDX-License-Identifier: LGPL-2.1-or-later
#pragma once
#include <events/eventcontent.h>
#include <events/roomevent.h>
namespace Quotient
{
/**
* @class StickerEvent
*
* Class to define a sticker event.
*
* Sticker messages are specialised image messages that are displayed without
* controls (e.g. no "download" link, or light-box view on click, as would be
* displayed for for m.image events).
*
* @sa Quotient::RoomEvent
*/
class StickerEvent : public RoomEvent
{
public:
#ifdef QUOTIENT_07
QUO_EVENT(StickerEvent, "m.sticker")
#else
DEFINE_EVENT_TYPEID("m.sticker", StickerEvent)
#endif
explicit StickerEvent(const QJsonObject &obj);
/**
* @brief A textual representation or associated description of the sticker image.
*
* This could be the alt text of the original image, or a message to accompany
* and further describe the sticker.
*/
QString body() const;
/**
* @brief Metadata about the image referred to in url including a thumbnail representation.
*/
const EventContent::ImageContent &image() const;
/**
* @brief The URL to the sticker image. This must be a valid mxc:// URI.
*/
QUrl url() const;
private:
EventContent::ImageContent m_imageContent;
};
REGISTER_EVENT_TYPE(StickerEvent)
}

View File

@@ -25,6 +25,7 @@ void FileTransferPseudoJob::fileTransferProgress(QString id, qint64 progress, qi
void FileTransferPseudoJob::fileTransferCompleted(QString id, QUrl localFile)
{
Q_UNUSED(localFile);
if (id != m_eventId) {
return;
}

View File

@@ -6,6 +6,13 @@
#include <KJob>
#include <QString>
/**
* @class FileTransferPseudoJob
*
* A class inherited from KJob to track a file download.
*
* @sa KJob
*/
class FileTransferPseudoJob : public KJob
{
public:
@@ -15,10 +22,25 @@ public:
};
Q_ENUM(Operation);
FileTransferPseudoJob(Operation operation, const QString &srcDest, const QString &path);
/**
* @brief Set the current number of bytes transferred.
*/
void fileTransferProgress(QString id, qint64 progress, qint64 total);
/**
* @brief Set the file transfer as complete.
*/
void fileTransferCompleted(QString id, QUrl localFile);
/**
* @brief Set the file transfer as failed.
*/
void fileTransferFailed(QString id, QString errorMessage = {});
/**
* @brief Start the file transfer.
*/
void start() override;
private:

View File

@@ -11,11 +11,31 @@
class FileTypeSingletonPrivate;
/**
* @class FileTypeSingleton
*
* Provide a singleton to expose the functionality of QMimeDatabase.
*
* @sa QMimeDatabase
*/
class FileTypeSingleton : public QObject
{
Q_OBJECT
/**
* @brief List of supported image formats.
*
* Returns a list of file extensions, not MIME types.
*/
Q_PROPERTY(QStringList supportedImageFormats READ supportedImageFormats CONSTANT FINAL)
/**
* @brief List of supported animated image formats.
*
* Returns a list of file extensions, not MIME types.
*/
Q_PROPERTY(QStringList supportedAnimatedImageFormats READ supportedAnimatedImageFormats CONSTANT FINAL)
QML_NAMED_ELEMENT(FileType)
QML_SINGLETON
@@ -23,26 +43,79 @@ public:
explicit FileTypeSingleton(QObject *parent = nullptr);
~FileTypeSingleton();
// Most of the code in this public section was copy/pasted from qmimedatabase.h
/**
* @brief Returns a MIME type for nameOrAlias or an invalid one if none found.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QMimeType mimeTypeForName(const QString &nameOrAlias) const;
enum MatchMode { MatchDefault, MatchExtension, MatchContent };
Q_ENUM(MatchMode)
/**
* @brief Returns a MIME type for the file named fileName using mode.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QMimeType mimeTypeForFile(const QString &fileName, FileTypeSingleton::MatchMode mode = MatchDefault) const;
/**
* @brief Returns a MIME type for fileInfo.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QMimeType mimeTypeForFile(const QFileInfo &fileInfo, FileTypeSingleton::MatchMode mode = MatchDefault) const;
/**
* @brief Returns the MIME types for the file name fileName.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QList<QMimeType> mimeTypesForFileName(const QString &fileName) const;
/**
* @brief Returns a MIME type for data.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QMimeType mimeTypeForData(const QByteArray &data) const;
/**
* @brief Returns a MIME type for the data in device.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QMimeType mimeTypeForData(QIODevice *device) const;
/**
* @brief Returns a MIME type for url.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QMimeType mimeTypeForUrl(const QUrl &url) const;
/**
* @brief Returns a MIME type for the given fileName and device data.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QMimeType mimeTypeForFileNameAndData(const QString &fileName, QIODevice *device) const;
/**
* @brief Returns a MIME type for the given fileName and device data.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QMimeType mimeTypeForFileNameAndData(const QString &fileName, const QByteArray &data) const;
/**
* @brief Returns the suffix for the file fileName, as known by the MIME database.
*
* @sa QMimeDatabase
*/
Q_INVOKABLE QString suffixForFileName(const QString &fileName) const;
// These return a list of file extensions, not mimetypes
QStringList supportedImageFormats() const;
QStringList supportedAnimatedImageFormats() const;

View File

@@ -3,17 +3,20 @@
#include "linkpreviewer.h"
#include "controller.h"
#include <connection.h>
#include <csapi/content-repo.h>
#include "neochatroom.h"
using namespace Quotient;
LinkPreviewer::LinkPreviewer(QObject *parent)
LinkPreviewer::LinkPreviewer(QObject *parent, NeoChatRoom *room, QUrl url)
: QObject(parent)
, m_currentRoom(room)
, m_loaded(false)
, m_url(url)
{
loadUrlPreview();
}
bool LinkPreviewer::loaded() const
@@ -31,7 +34,7 @@ QString LinkPreviewer::description() const
return m_description;
}
QString LinkPreviewer::imageSource() const
QUrl LinkPreviewer::imageSource() const
{
return m_imageSource;
}
@@ -43,22 +46,41 @@ QUrl LinkPreviewer::url() const
void LinkPreviewer::setUrl(QUrl url)
{
if (url.scheme() == QStringLiteral("https")) {
if (url != m_url) {
m_url = url;
urlChanged();
loadUrlPreview();
}
}
void LinkPreviewer::loadUrlPreview()
{
if (m_url.scheme() == QStringLiteral("https")) {
m_loaded = false;
Q_EMIT loadedChanged();
m_url = url;
Q_EMIT urlChanged();
auto conn = Controller::instance().activeConnection();
auto conn = m_currentRoom->connection();
GetUrlPreviewJob *job = conn->callApi<GetUrlPreviewJob>(m_url.toString());
connect(job, &BaseJob::success, this, [this, job]() {
connect(job, &BaseJob::success, this, [this, job, conn]() {
const auto json = job->jsonData();
m_title = json["og:title"].toString().trimmed();
m_description = json["og:description"].toString().trimmed().replace("\n", " ");
m_imageSource = json["og:image"].toString();
auto imageUrl = QUrl(json["og:image"].toString());
if (imageUrl.isValid() && imageUrl.scheme() == QStringLiteral("mxc")) {
#ifdef QUOTIENT_07
m_imageSource = conn->makeMediaUrl(imageUrl);
#else
QUrlQuery q(imageUrl.query());
q.addQueryItem(QStringLiteral("user_id"), conn->userId());
imageUrl.setQuery(q);
m_imageSource = imageUrl;
#endif
} else {
m_imageSource = QUrl();
}
m_loaded = true;
Q_EMIT titleChanged();
Q_EMIT descriptionChanged();

View File

@@ -6,33 +6,65 @@
#include <QObject>
#include <QUrl>
class NeoChatRoom;
/**
* @class LinkPreviewer
*
* A class to download the link preview info for a URL and provide a QML interface for it.
*
* To use set the URL property and then access the other parameters which will be
* populated once loaded is true.
*/
class LinkPreviewer : public QObject
{
Q_OBJECT
Q_PROPERTY(bool loaded READ loaded NOTIFY loadedChanged)
Q_PROPERTY(QString title READ title NOTIFY titleChanged)
Q_PROPERTY(QString description READ description NOTIFY descriptionChanged)
Q_PROPERTY(QString imageSource READ imageSource NOTIFY imageSourceChanged)
/**
* @brief The URL to get the preview for.
*/
Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged)
public:
explicit LinkPreviewer(QObject *parent = nullptr);
/**
* @brief Whether the preview information has been loaded.
*/
Q_PROPERTY(bool loaded READ loaded NOTIFY loadedChanged)
/**
* @brief The title of the preview.
*/
Q_PROPERTY(QString title READ title NOTIFY titleChanged)
/**
* @brief The description of the preview.
*/
Q_PROPERTY(QString description READ description NOTIFY descriptionChanged)
/**
* @brief The image source for the preview.
*/
Q_PROPERTY(QUrl imageSource READ imageSource NOTIFY imageSourceChanged)
public:
explicit LinkPreviewer(QObject *parent = nullptr, NeoChatRoom *room = nullptr, QUrl url = {});
[[nodiscard]] QUrl url() const;
void setUrl(QUrl);
[[nodiscard]] bool loaded() const;
[[nodiscard]] QString title() const;
[[nodiscard]] QString description() const;
[[nodiscard]] QString imageSource() const;
[[nodiscard]] QUrl url() const;
void setUrl(QUrl);
[[nodiscard]] QUrl imageSource() const;
private:
NeoChatRoom *m_currentRoom = nullptr;
bool m_loaded;
QString m_title;
QString m_description;
QString m_imageSource;
QString m_title = QString();
QString m_description = QString();
QUrl m_imageSource = QUrl();
QUrl m_url;
void loadUrlPreview();
Q_SIGNALS:
void loadedChanged();
void titleChanged();
@@ -40,3 +72,4 @@ Q_SIGNALS:
void imageSourceChanged();
void urlChanged();
};
Q_DECLARE_METATYPE(LinkPreviewer *)

222
src/logger.cpp Normal file
View File

@@ -0,0 +1,222 @@
// SPDX-FileCopyrightText: 1997 Matthias Kalle Dalheimer <kalle@kde.org>
// SPDX-FileCopyrightText: 2002 Holger Freyther <freyther@kde.org>
// SPDX-FileCopyrightText: 2008 Volker Krause <vkrause@kde.org>
// SPDX-FileCopyrightText: 2023 Tobias Fella <fella@posteo.de>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "logger.h"
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
#include <QLoggingCategory>
#include <QMutex>
#include <QStandardPaths>
static QLoggingCategory::CategoryFilter oldCategoryFilter = nullptr;
static QtMessageHandler oldHandler = nullptr;
static bool e2eeDebugEnabled = false;
class FileDebugStream : public QIODevice
{
Q_OBJECT
public:
FileDebugStream()
: mType(QtCriticalMsg)
{
open(WriteOnly);
}
bool isSequential() const override
{
return true;
}
qint64 readData(char *, qint64) override
{
return 0;
}
qint64 readLineData(char *, qint64) override
{
return 0;
}
qint64 writeData(const char *data, qint64 len) override
{
if (!mFileName.isEmpty()) {
QFile outputFile(mFileName);
outputFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Unbuffered);
outputFile.write(data, len);
outputFile.putChar('\n');
outputFile.close();
}
return len;
}
void setFileName(const QString &fileName)
{
mFileName = fileName;
}
void setType(QtMsgType type)
{
mType = type;
}
private:
QString mFileName;
QtMsgType mType;
};
class DebugPrivate
{
public:
DebugPrivate()
: origHandler(nullptr)
{
}
~DebugPrivate()
{
qInstallMessageHandler(origHandler);
file.close();
}
void log(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
QMutexLocker locker(&mutex);
QByteArray buf;
QTextStream str(&buf);
str << QDateTime::currentDateTime().toString(Qt::ISODate) << " [";
switch (type) {
case QtDebugMsg:
str << "DEBUG";
break;
case QtInfoMsg:
str << "INFO ";
break;
case QtWarningMsg:
str << "WARN ";
break;
case QtFatalMsg:
str << "FATAL";
break;
case QtCriticalMsg:
str << "CRITICAL";
break;
}
str << "] " << context.category << ": ";
if (context.file && *context.file && context.line) {
str << context.file << ":" << context.line << ": ";
}
if (context.function && *context.function) {
str << context.function << ": ";
}
str << message << "\n";
str.flush();
file.write(buf.constData(), buf.size());
file.flush();
if (oldHandler && (strcmp(context.category, "quotient.e2ee") != 0 || e2eeDebugEnabled)) {
oldHandler(type, context, message);
}
}
void setName(const QString &appName)
{
name = appName;
if (file.isOpen()) {
file.close();
}
auto filePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator() + appName;
QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator());
auto entryList = dir.entryList({appName + QStringLiteral(".*")});
std::sort(entryList.begin(), entryList.end(), [](const auto &left, const auto &right) {
auto leftIndex = left.split(".").last().toInt();
auto rightIndex = right.split(".").last().toInt();
return leftIndex > rightIndex;
});
for (const auto &entry : entryList) {
bool ok = false;
const auto index = entry.split(".").last().toInt(&ok);
if (!ok) {
continue;
}
QFileInfo info(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator() + entry);
if (info.exists()) {
QFile file(info.absoluteFilePath());
if (index > 50) {
file.remove();
continue;
}
const QString newName = filePath + QStringLiteral(".%1").arg(index + 1);
const bool success = file.copy(newName);
if (success) {
file.remove();
} else {
qFatal("Cannot rename log file '%s' to '%s': %s",
qUtf8Printable(file.fileName()),
qUtf8Printable(newName),
qUtf8Printable(file.errorString()));
}
}
}
QFileInfo finfo(filePath);
if (!finfo.absoluteDir().exists()) {
QDir().mkpath(finfo.absolutePath());
}
file.setFileName(filePath + QStringLiteral(".0"));
file.open(QIODevice::WriteOnly | QIODevice::Unbuffered);
}
void setOrigHandler(QtMessageHandler origHandler_)
{
origHandler = origHandler_;
}
QMutex mutex;
QFile file;
QString name;
QtMessageHandler origHandler;
QByteArray loggingCategory;
};
Q_GLOBAL_STATIC(DebugPrivate, sInstance)
void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message)
{
switch (type) {
case QtDebugMsg:
case QtInfoMsg:
case QtWarningMsg:
case QtCriticalMsg:
sInstance()->log(type, context, message);
break;
case QtFatalMsg:
sInstance()->log(QtInfoMsg, context, message);
abort();
}
}
void filter(QLoggingCategory *category)
{
if (qstrcmp(category->categoryName(), "quotient.e2ee") == 0) {
category->setEnabled(QtDebugMsg, true);
} else if (oldCategoryFilter) {
oldCategoryFilter(category);
}
}
void initLogging()
{
e2eeDebugEnabled = QLoggingCategory("quotient.e2ee", QtDebugMsg).isEnabled(QtDebugMsg);
oldCategoryFilter = QLoggingCategory::installFilter(filter);
oldHandler = qInstallMessageHandler(messageHandler);
sInstance->setOrigHandler(oldHandler);
sInstance->setName("neochat.log");
}
#include "logger.moc"

9
src/logger.h Normal file
View File

@@ -0,0 +1,9 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
/**
* Initlalize logging to file and enables some additional categories, which will only be logged to the file
*/
void initLogging();

View File

@@ -38,12 +38,20 @@ void Login::init()
connect(this, &Login::matrixIdChanged, this, [this]() {
setHomeserverReachable(false);
QRegularExpression validator("^\\@?[a-zA-Z0-9\\._=\\-/]+\\:[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]+)*(\\:[0-9]+)?$");
if (!validator.match(m_matrixId).hasMatch()) {
return;
}
if (m_matrixId == "@") {
return;
}
#ifdef QUOTIENT_07
m_isLoggedIn = Accounts.isLoggedIn(m_matrixId);
#else
m_isLoggedIn = AccountRegistry::instance().isLoggedIn(m_matrixId);
#endif
Q_EMIT isLoggedInChanged();
if (m_isLoggedIn) {
return;

View File

@@ -10,19 +10,67 @@ namespace Quotient
{
class Connection;
}
/**
* @class Login
*
* A helper class for logging into a Matrix account.
*/
class Login : public QObject
{
Q_OBJECT
/**
* @brief Whether the home server for the account is reachable.
*/
Q_PROPERTY(bool homeserverReachable READ homeserverReachable NOTIFY homeserverReachableChanged)
/**
* @brief Whether the connection to the home server is being tested.
*
* True if NeoChat is trying to resolve the home server, false if not started
* or complete.
*/
Q_PROPERTY(bool testing READ testing NOTIFY testingChanged)
/**
* @brief The Matrix ID of the account that is being logged into.
*/
Q_PROPERTY(QString matrixId READ matrixId WRITE setMatrixId NOTIFY matrixIdChanged)
/**
* @brief The password entered by the user to login to the account.
*/
Q_PROPERTY(QString password READ password WRITE setPassword NOTIFY passwordChanged)
/**
* @brief The device name to assign to this session.
*/
Q_PROPERTY(QString deviceName READ deviceName WRITE setDeviceName NOTIFY deviceNameChanged)
/**
* @brief Whether the home server of the account supports single sign on login.
*/
Q_PROPERTY(bool supportsSso READ supportsSso NOTIFY loginFlowsChanged STORED false)
/**
* @brief Whether the home server of the account supports password login.
*/
Q_PROPERTY(bool supportsPassword READ supportsPassword NOTIFY loginFlowsChanged STORED false)
/**
* @brief The URL for the single sign on session.
*/
Q_PROPERTY(QUrl ssoUrl READ ssoUrl NOTIFY ssoUrlChanged)
/**
* @brief Whether login process is ongoing.
*/
Q_PROPERTY(bool isLoggingIn READ isLoggingIn NOTIFY isLoggingInChanged)
/**
* @brief Whether login has successfully completed.
*/
Q_PROPERTY(bool isLoggedIn READ isLoggedIn NOTIFY isLoggedInChanged)
public:

View File

@@ -43,19 +43,24 @@
#include "chatdocumenthandler.h"
#include "clipboard.h"
#include "controller.h"
#include "delegatesizehelper.h"
#include "filetypesingleton.h"
#include "joinrulesevent.h"
#include "linkpreviewer.h"
#include "logger.h"
#include "login.h"
#include "matriximageprovider.h"
#include "models/accountemoticonmodel.h"
#include "models/collapsestateproxymodel.h"
#include "models/customemojimodel.h"
#include "models/devicesmodel.h"
#include "models/emojimodel.h"
#include "models/emoticonfiltermodel.h"
#include "models/imagepacksmodel.h"
#include "models/keywordnotificationrulemodel.h"
#include "models/messageeventmodel.h"
#include "models/messagefiltermodel.h"
#include "models/publicroomlistmodel.h"
#include "models/reactionmodel.h"
#include "models/roomlistmodel.h"
#include "models/searchmodel.h"
#include "models/serverlistmodel.h"
@@ -72,6 +77,8 @@
#ifdef QUOTIENT_07
#include "pollhandler.h"
#endif
#include "models/statefiltermodel.h"
#include "models/stickermodel.h"
#include "roommanager.h"
#include "spacehierarchycache.h"
#include "urlhelper.h"
@@ -79,6 +86,8 @@
#ifdef QUOTIENT_07
#include <keyverificationsession.h>
#endif
#include <room.h>
#ifdef HAVE_COLORSCHEME
#include "colorschemer.h"
#endif
@@ -86,6 +95,14 @@
#include "models/statemodel.h"
#include "neochatuser.h"
#ifdef GSTREAMER_AVAILABLE
#include "call/audiosources.h"
#include "call/callmanager.h"
#include "call/callparticipant.h"
#include "call/videosources.h"
#include "models/callparticipantsmodel.h"
#endif
#ifdef HAVE_RUNNER
#include "runner.h"
#include <QDBusConnection>
@@ -155,7 +172,7 @@ int main(int argc, char *argv[])
QStringLiteral(NEOCHAT_VERSION_STRING),
i18n("Matrix client"),
KAboutLicense::GPL_V3,
i18n("© 2018-2020 Black Hat, 2020-2022 KDE Community"));
i18n("© 2018-2020 Black Hat, 2020-2023 KDE Community"));
about.addAuthor(i18n("Carl Schwan"), i18n("Maintainer"), QStringLiteral("carl@carlschwan.eu"), QStringLiteral("https://carlschwan.eu"));
about.addAuthor(i18n("Tobias Fella"), i18n("Maintainer"), QStringLiteral("tobias.fella@kde.org"), QStringLiteral("https://tobiasfella.de"));
about.addAuthor(i18n("James Graham"), i18n("Maintainer"), QStringLiteral("james.h.graham@protonmail.com"));
@@ -176,10 +193,28 @@ int main(int argc, char *argv[])
#endif
QStringLiteral("https://github.com/quotient-im/libquotient"),
KAboutLicense::LGPL_V2_1);
#ifdef GSTREAMER_AVAILABLE
guint major, minor, micro, nano;
gst_version(&major, &minor, &micro, &nano);
about.addComponent(QStringLiteral("GStreamer"),
i18nc("Description of GStreamer", "Open Source Multimedia Framework"),
i18nc("<version number> (built against <possibly different version number>)",
"%1.%2.%3.%4 (built against %5.%6.%7.%8)",
major,
minor,
micro,
nano,
GST_VERSION_MAJOR,
GST_VERSION_MINOR,
GST_VERSION_MICRO,
GST_VERSION_NANO));
#endif
KAboutData::setApplicationData(about);
QGuiApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("org.kde.neochat")));
initLogging();
#ifdef NEOCHAT_FLATPAK
// Copy over the included FontConfig configuration to the
// app's config dir:
@@ -223,6 +258,7 @@ int main(int argc, char *argv[])
qmlRegisterType<KWebShortcutModel>("org.kde.neochat", 1, 0, "WebShortcutModel");
qmlRegisterType<UserListModel>("org.kde.neochat", 1, 0, "UserListModel");
qmlRegisterType<MessageEventModel>("org.kde.neochat", 1, 0, "MessageEventModel");
qmlRegisterType<ReactionModel>("org.kde.neochat", 1, 0, "ReactionModel");
qmlRegisterType<CollapseStateProxyModel>("org.kde.neochat", 1, 0, "CollapseStateProxyModel");
qmlRegisterType<MessageFilterModel>("org.kde.neochat", 1, 0, "MessageFilterModel");
qmlRegisterType<UserFilterModel>("org.kde.neochat", 1, 0, "UserFilterModel");
@@ -235,18 +271,28 @@ int main(int argc, char *argv[])
qmlRegisterType<LinkPreviewer>("org.kde.neochat", 1, 0, "LinkPreviewer");
qmlRegisterType<CompletionModel>("org.kde.neochat", 1, 0, "CompletionModel");
qmlRegisterType<StateModel>("org.kde.neochat", 1, 0, "StateModel");
qmlRegisterType<StateFilterModel>("org.kde.neochat", 1, 0, "StateFilterModel");
qmlRegisterType<SearchModel>("org.kde.neochat", 1, 0, "SearchModel");
#ifdef QUOTIENT_07
qmlRegisterType<PollHandler>("org.kde.neochat", 1, 0, "PollHandler");
#endif
qmlRegisterType<KeywordNotificationRuleModel>("org.kde.neochat", 1, 0, "KeywordNotificationRuleModel");
qmlRegisterType<StickerModel>("org.kde.neochat", 1, 0, "StickerModel");
qmlRegisterType<ImagePacksModel>("org.kde.neochat", 1, 0, "ImagePacksModel");
qmlRegisterType<AccountEmoticonModel>("org.kde.neochat", 1, 0, "AccountEmoticonModel");
qmlRegisterType<EmoticonFilterModel>("org.kde.neochat", 1, 0, "EmoticonFilterModel");
qmlRegisterType<DelegateSizeHelper>("org.kde.neochat", 1, 0, "DelegateSizeHelper");
qmlRegisterUncreatableType<RoomMessageEvent>("org.kde.neochat", 1, 0, "RoomMessageEvent", "ENUM");
qmlRegisterUncreatableType<PushNotificationState>("org.kde.neochat", 1, 0, "PushNotificationState", "ENUM");
qmlRegisterUncreatableType<PushNotificationAction>("org.kde.neochat", 1, 0, "PushNotificationAction", "ENUM");
qmlRegisterUncreatableType<NeoChatRoomType>("org.kde.neochat", 1, 0, "NeoChatRoomType", "ENUM");
qmlRegisterUncreatableType<UserType>("org.kde.neochat", 1, 0, "UserType", "ENUM");
qmlRegisterUncreatableType<NeoChatUser>("org.kde.neochat", 1, 0, "NeoChatUser", {});
qmlRegisterUncreatableType<NeoChatRoom>("org.kde.neochat", 1, 0, "NeoChatRoom", {});
#ifdef GSTREAMER_AVAILABLE
qmlRegisterUncreatableType<CallParticipantsModel>("org.kde.neochat", 1, 0, "CallParticipantsModel", "Get through CallManager");
qmlRegisterUncreatableType<CallParticipant>("org.kde.neochat", 1, 0, "CallParticipant", "Get through model");
#endif
qRegisterMetaType<User *>("User*");
qRegisterMetaType<User *>("const User*");
qRegisterMetaType<User *>("const Quotient::User*");
@@ -263,10 +309,18 @@ int main(int argc, char *argv[])
qmlRegisterUncreatableType<KeyVerificationSession>("org.kde.neochat", 1, 0, "KeyVerificationSession", {});
qRegisterMetaType<QVector<EmojiEntry>>("QVector<EmojiEntry>");
#endif
#endif
#ifdef GSTREAMER_AVAILABLE
qmlRegisterSingletonInstance("org.kde.neochat", 1, 0, "AudioSources", &AudioSources::instance());
qmlRegisterSingletonInstance("org.kde.neochat", 1, 0, "VideoSources", &VideoSources::instance());
qmlRegisterSingletonInstance("org.kde.neochat", 1, 0, "CallManager", &CallManager::instance());
qmlRegisterUncreatableType<CallSession>("org.kde.neochat", 1, 0, "CallSession", "ENUM");
#endif
qmlRegisterSingletonType("org.kde.neochat", 1, 0, "About", [](QQmlEngine *engine, QJSEngine *) -> QJSValue {
return engine->toScriptValue(KAboutData::applicationData());
});
qmlRegisterSingletonType(QUrl("qrc:/OsmLocationPlugin.qml"), "org.kde.neochat", 1, 0, "OsmLocationPlugin");
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
qRegisterMetaTypeStreamOperators<Emoji>();

View File

@@ -98,18 +98,6 @@ void ThumbnailResponse::prepareResult()
Q_EMIT finished();
}
void ThumbnailResponse::doCancel()
{
if (!Controller::instance().activeConnection()) {
return;
}
// Runs in the main thread, not QML thread
if (job) {
Q_ASSERT(QThread::currentThread() == job->thread());
job->abandon();
}
}
QQuickTextureFactory *ThumbnailResponse::textureFactory() const
{
QReadLocker _(&lock);
@@ -122,11 +110,6 @@ QString ThumbnailResponse::errorString() const
return errorStr;
}
void ThumbnailResponse::cancel()
{
QMetaObject::invokeMethod(this, &ThumbnailResponse::doCancel, Qt::QueuedConnection);
}
QQuickImageResponse *MatrixImageProvider::requestImageResponse(const QString &id, const QSize &requestedSize)
{
return new ThumbnailResponse(id, requestedSize);

Some files were not shown because too many files have changed in this diff Show More