Compare commits

...

144 Commits

Author SHA1 Message Date
Ingo Klöcker
238e31fe23 Add "16:9 Super hero art" for Microsoft Store
For details, where this image is used, see
https://learn.microsoft.com/en-us/windows/apps/publish/publish-your-app/screenshots-and-images?pivots=store-installer-msix#windows-10-and-xbox-image-169-super-hero-art
2023-06-26 15:38:12 +02:00
Ingo Klöcker
99aeba2882 Add some logos in different sizes for the Microsoft Store
For details, where those images are used see
https://learn.microsoft.com/en-us/windows/apps/publish/publish-your-app/screenshots-and-images?pivots=store-installer-msix#store-logos
2023-06-26 15:36:35 +02:00
Ingo Klöcker
a65724ebc7 Add features as custom values
Microsoft Store allows adding a list of up-to 20 features to an app
submission. It's not clear whether this adds value over the common
practice for KDE apps to add a list of features to the description.
If the search in Microsoft Store would rank matching features higher
than a full-text match in the description, then it might make sense.

The problem is that this would duplicate the list of features in
Microsoft Store because removing the list of features from the description
would remove the features from the app listing in Linux app stores.
Therefore, we should probably stick to the established practice and leave
the list of features in Microsoft Store empty.

See also https://github.com/ximion/appstream/issues/388
2023-06-26 15:31:06 +02:00
Ingo Klöcker
d5ab724edb Add Windows-specific screenshots as custom values
This is clearly a hack. It would be preferable to add those directly
to the existing list of screenshots with some property marking them as
screenshots of the Windows version for the Microsoft Store
(https://github.com/ximion/appstream/issues/390). The IDs are derived
from the IDs used by the CSV export of an app submission in Microsoft
Partner Center.
2023-06-26 15:19:16 +02:00
Ingo Klöcker
67ff7e0842 Add a few keywords for easier finding in stores
This is supported by AppStream
https://www.freedesktop.org/software/appstream/docs/chap-Metadata.html#tag-keywords
and can be used in the Microsoft Store.
2023-06-26 15:12:24 +02:00
l10n daemon script
9be04c1272 GIT_SILENT Sync po/docbooks with svn 2023-06-26 01:59:28 +00:00
l10n daemon script
6f5d88cf63 GIT_SILENT Sync po/docbooks with svn 2023-06-25 02:12:18 +00:00
l10n daemon script
1103e80191 GIT_SILENT made messages (after extraction) 2023-06-25 00:52:33 +00:00
l10n daemon script
a5320397c2 GIT_SILENT Sync po/docbooks with svn 2023-06-24 02:10:00 +00:00
Volker Krause
53719b971d Show a placeholder message if there are no shared locations 2023-06-22 15:17:40 +00:00
Volker Krause
64a1316f9b Zoom/center the page map so that all locations are in view 2023-06-22 15:17:40 +00:00
Volker Krause
a3b8168744 Add bounding box property for LocationsModel as well
Needed to property position the room map.
2023-06-22 15:17:40 +00:00
Volker Krause
c06e69931a Add fullscreen map to live location delegates as well 2023-06-22 15:17:40 +00:00
Volker Krause
30f8573dfc Show live location shares on the room map as well 2023-06-22 15:17:40 +00:00
Volker Krause
7f067b698e Unify map markers on the full screen and room maps as well 2023-06-22 15:17:40 +00:00
Volker Krause
b56ebdf149 Don't assert on invalid/empty geo: URIs 2023-06-22 15:17:40 +00:00
Volker Krause
a02dd4ab87 Extend LocationsModel to include asset and auther roles
Needed for compatibility with the standard map marker.
2023-06-22 15:17:40 +00:00
Volker Krause
898f0c962a Factor out map marker into its own QML element for reuse 2023-06-22 15:17:40 +00:00
Tobias Fella
5b4ae764cf Show a map for location events 2023-06-22 15:17:40 +00:00
l10n daemon script
d14db326bb GIT_SILENT Sync po/docbooks with svn 2023-06-22 01:53:18 +00:00
l10n daemon script
5c51e0d0fc GIT_SILENT Sync po/docbooks with svn 2023-06-21 01:49:24 +00:00
l10n daemon script
f78b4af692 GIT_SILENT Sync po/docbooks with svn 2023-06-19 02:05:24 +00:00
Carl Schwan
bd5ed0f46c Fix toolbar of RoomList when using font size 11px
We don't need to use a ToolBar for the titleDelegate since the
titleDelegate is already included inside a toolbar. This work magically
when using the default font size of 10px Noto Sans but breaks with 11px

BUG: 467242
2023-06-18 07:00:47 +00:00
l10n daemon script
529cfa8f7d GIT_SILENT Sync po/docbooks with svn 2023-06-18 02:44:28 +00:00
Carl Schwan
5552cd60f6 Group pageStack properties of the ApplicationWindow together 2023-06-17 21:29:15 +02:00
Tobias Fella
c51a1f4851 Fix another missing import 2023-06-17 14:32:03 +02:00
James Graham
a27f4765e4 Fix permission model
Make sure `Permissions.qml` uses the right role.
2023-06-17 09:34:42 +00:00
James Graham
402f99923c Fix NeoChatRoom type QML
Make sure import `org.kde.neochat 1.0` is included where `NeoChatRoom` is used as a type
2023-06-17 09:26:22 +00:00
l10n daemon script
2afda78912 GIT_SILENT Sync po/docbooks with svn 2023-06-17 01:53:16 +00:00
Volker Krause
25f9c7e125 Compute live location bounding box and center the map accordingly 2023-06-16 14:12:15 +00:00
Volker Krause
05082cb2bb Consider live location beacon timeouts for their 2023-06-16 14:12:15 +00:00
Volker Krause
59495a1452 Show starting live location beacons as location delegates in the timeline
Also, hide ending live location beacon state changes.
2023-06-16 14:12:15 +00:00
Volker Krause
d10460c45b Add live location tracking model
This can either watch a single live location beacon or all of those in
a given room.
2023-06-16 14:12:15 +00:00
l10n daemon script
b968c85de2 GIT_SILENT Sync po/docbooks with svn 2023-06-16 01:49:40 +00:00
l10n daemon script
13efc08b07 GIT_SILENT Sync po/docbooks with svn 2023-06-14 01:51:18 +00: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
167 changed files with 22083 additions and 13906 deletions

View File

@@ -103,7 +103,6 @@
{
"name": "libQuotient",
"buildsystem": "cmake-ninja",
"config-opts": [ "-DBUILD_TESTING=OFF" ],
"sources": [
{
"type": "git",
@@ -113,7 +112,8 @@
}
],
"config-opts": [
"-DQuotient_ENABLE_E2EE=ON"
"-DQuotient_ENABLE_E2EE=ON",
"-DBUILD_TESTING=OFF"
]
},
{

View File

@@ -4,11 +4,11 @@
include:
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/reuse-lint.yml
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/android.yml
- https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/android-qt6.yml
# - https://invent.kde.org/sysadmin/ci-utilities/raw/master/gitlab-templates/android-qt6.yml
- 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

@@ -59,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

@@ -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"

BIN
icons/300-apps-neochat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

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>
@@ -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,6 +76,7 @@
<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>
@@ -84,7 +87,13 @@ 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="fi">NeoChat on asiakassovellus Matrixille, hajautetulle pikaviestinyhteyskäytännölle. Sillä voi lähettää teksti-, video- ja ääniviestejä perheelle, tutuille ja ystäville. Se käyttää KDE-kehystä ja erityisesti Kirigamia tuottaakseen mukautuvan monialustaisen käyttökokemuksen.</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="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>
@@ -97,26 +106,38 @@ to provide a convergent experience across multiple platforms.</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="fi">NeoChat pyrkii olemaan Matrix-määritelmän täysominaisuuksinen sovellus, joten se tukee kaikkea nykyisessä vakaassa määritelmässä muutamaa huomattavaa poikkeusta lukuun ottamatta (VoIP, säikeet ja jotkin piirteet päästä päähän -salauksessa). Joitakin pienempiäkin puutteita on Matrix-määritelmän jatkuvan kehityksen vuoksi, mutta lopputavoitteena on tarjota määritelmän täysi tuki.</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 spesifikasyonu için tam özellikli bir uygulama olmayı hedefler. Bu nedenle; VoIP, ileti zincirleri ve Uçtan Uca Şifrelemenin 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="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="fi">Matrix-määritelmän kehittyessä NeoChat tukee myös monia epävakaita ominaisuuksia. Tällä hetkellä näitä ovat:</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 belirtim geliştirmesinin doğası gereği çok sayıda kararsız özelliği de destekler. Şu anda bunlar:</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>
@@ -124,12 +145,18 @@ to provide a convergent experience across multiple platforms.</p>
<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="fi">Kyselyt 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>
@@ -137,11 +164,18 @@ to provide a convergent experience across multiple platforms.</p>
<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="fi">Tarrapakkaukset 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>
@@ -149,16 +183,28 @@ to provide a convergent experience across multiple platforms.</p>
<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="fi">Sijaintitapahtumat 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>
<keywords>
<keyword>instant messaging</keyword>
<keyword>chat</keyword>
<keyword>matrix</keyword>
</keywords>
<url type="homepage">https://apps.kde.org/neochat/</url>
<url type="bugtracker">https://bugs.kde.org/buglist.cgi?component=General&amp;product=NeoChat</url>
<categories>
@@ -177,6 +223,7 @@ to provide a convergent experience across multiple platforms.</p>
<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>
@@ -194,6 +241,7 @@ to provide a convergent experience across multiple platforms.</p>
<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>
@@ -203,6 +251,20 @@ to provide a convergent experience across multiple platforms.</p>
<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>
<value key="KDE::windows_store::StoreLogo9x16">https://invent.kde.org/network/neochat/-/raw/master/icons/windows/storelogo-720x1080.png</value>
<value key="KDE::windows_store::StoreLogoSquare">https://invent.kde.org/network/neochat/-/raw/master/icons/windows/storelogo-1080x1080.png</value>
<value key="KDE::windows_store::Icon">https://invent.kde.org/network/neochat/-/raw/master/icons/300-apps-neochat.png</value>
<value key="KDE::windows_store::PromotionalArt16x9">https://invent.kde.org/network/neochat/-/raw/master/icons/windows/promoimage-1920x1080.png</value>
<value key="KDE::feature1">Supports the Matrix protocol for instant messaging.</value>
<value key="KDE::feature2">End-to-End Encryption</value>
<value key="KDE::feature3">Polls (experimental)</value>
<value key="KDE::feature4">Sticker Packs (experimental)</value>
<value key="KDE::feature5">Location Events (experimental)</value>
<value key="KDE::windows_store::DesktopScreenshot1">https://cdn.kde.org/screenshots/neochat/NeoChat-Windows-Timeline.png</value>
<value key="KDE::windows_store::DesktopScreenshotCaption1">Main view of NeoChat with room list, chat, and room information pane</value>
<value key="KDE::windows_store::DesktopScreenshot2">https://cdn.kde.org/screenshots/neochat/NeoChat-Windows-Login.png</value>
<value key="KDE::windows_store::DesktopScreenshotCaption2">Login screen of NeoChat</value>
</custom>
<launchable type="desktop-id">org.kde.neochat.desktop</launchable>
<screenshots>
@@ -217,6 +279,7 @@ to provide a convergent experience across multiple platforms.</p>
<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">
<artifacts>

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,6 +25,7 @@ add_library(neochat STATIC
models/publicroomlistmodel.cpp
models/userdirectorylistmodel.cpp
models/keywordnotificationrulemodel.cpp
models/emoticonfiltermodel.cpp
notificationsmanager.cpp
models/sortfilterroomlistmodel.cpp
chatdocumenthandler.cpp
@@ -52,6 +54,11 @@ add_library(neochat STATIC
events/imagepackevent.cpp
events/joinrulesevent.cpp
events/stickerevent.cpp
models/reactionmodel.cpp
delegatesizehelper.cpp
models/livelocationsmodel.cpp
models/locationsmodel.cpp
locationhelper.cpp
)
ecm_qt_declare_logging_category(neochat

View File

@@ -159,7 +159,7 @@ private:
bool m_isEdit = false;
QQuickTextDocument *m_document;
QPointer<QQuickTextDocument> m_document;
QPointer<NeoChatRoom> m_room;
bool completionVisible = false;

View File

@@ -45,7 +45,6 @@
#include <qt_connection_util.h>
#ifdef QUOTIENT_07
#include <csapi/notifications.h>
#include <eventstats.h>
#endif
@@ -109,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;
@@ -229,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);
@@ -247,7 +182,9 @@ 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
@@ -404,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)
@@ -496,7 +427,11 @@ NeochatChangePasswordJob::NeochatChangePasswordJob(const QString &newPassword, b
int Controller::accountCount() const
{
#ifdef QUOTIENT_07
return Accounts.count();
#else
return AccountRegistry::instance().count();
#endif
}
void Controller::setQuitOnLastWindowClosed()
@@ -553,7 +488,7 @@ 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."));
}
@@ -593,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

View File

@@ -159,6 +159,11 @@ public:
*/
Q_INVOKABLE void createRoom(const QString &name, const QString &topic);
/**
* @brief Create new space.
*/
Q_INVOKABLE void createSpace(const QString &name, const QString &topic);
/**
* @brief Join a room.
*/
@@ -230,9 +235,6 @@ 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();

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

@@ -51,5 +51,42 @@ ImagePackEventContent::ImagePackEventContent(const QJsonObject &json)
void ImagePackEventContent::fillJson(QJsonObject *o) const
{
// TODO
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;
}

44
src/locationhelper.cpp Normal file
View File

@@ -0,0 +1,44 @@
// SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "locationhelper.h"
#include <cmath>
QRectF LocationHelper::unite(const QRectF &r1, const QRectF &r2)
{
// this looks weird but is actually intentional as we need to handle point-like "rects" as well
if ((!r1.isEmpty() || r1.isNull()) && (!r2.isEmpty() || r2.isNull())) {
return r1 | r2;
}
return (!r1.isEmpty() || r1.isNull()) ? r1 : r2;
}
QPointF LocationHelper::center(const QRectF &r)
{
return r.center();
}
constexpr inline double degToRad(double deg)
{
return deg / 180.0 * M_PI;
}
static QPointF mercatorProject(double lat, double lon, double zoom)
{
const auto x = (256.0 / (2.0 * M_PI)) * std::pow(2.0, zoom) * (degToRad(lon) + M_PI);
const auto y = (256.0 / (2.0 * M_PI)) * std::pow(2.0, zoom) * (M_PI - std::log(std::tan(M_PI / 4.0 + degToRad(lat) / 2.0)));
return QPointF(x, y);
}
float LocationHelper::zoomToFit(const QRectF &r, float mapWidth, float mapHeight)
{
const auto p1 = mercatorProject(r.bottomLeft().y(), r.bottomLeft().x(), 1.0);
const auto p2 = mercatorProject(r.topRight().y(), r.topRight().x(), 1.0);
const auto zx = std::log2((mapWidth / (p2.x() - p1.x())));
const auto zy = std::log2((mapHeight / (p2.y() - p1.y())));
const auto z = std::min(zx, zy);
return std::clamp(z, 5.0, 18.0);
}

22
src/locationhelper.h Normal file
View File

@@ -0,0 +1,22 @@
// SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "linkpreviewer.h"
#include <QMetaType>
#include <QRectF>
/** Location related helper functions for QML. */
class LocationHelper
{
Q_GADGET
public:
/** Unite two rectanlges. */
Q_INVOKABLE static QRectF unite(const QRectF &r1, const QRectF &r2);
/** Returns the center of @p r. */
Q_INVOKABLE static QPointF center(const QRectF &r);
/** Returns the highest zoom level to fit @r into a map of size @p mapWidth x @p mapHeight. */
Q_INVOKABLE static float zoomToFit(const QRectF &r, float mapWidth, float mapHeight);
};
Q_DECLARE_METATYPE(LocationHelper)

View File

@@ -131,22 +131,36 @@ public:
}
auto filePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator() + appName;
QFileInfo infoOld(filePath + QLatin1String(".old"));
if (infoOld.exists()) {
QFile fileOld(infoOld.absoluteFilePath());
const bool success = fileOld.remove();
if (!success) {
qFatal("Cannot remove old log file '%s': %s", qUtf8Printable(fileOld.fileName()), qUtf8Printable(fileOld.errorString()));
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(filePath);
if (info.exists()) {
QFile file(info.absoluteFilePath());
const QString oldName = filePath + QLatin1String(".old");
const bool success = file.copy(oldName);
if (!success) {
qFatal("Cannot rename log file '%s' to '%s': %s", qUtf8Printable(file.fileName()), qUtf8Printable(oldName), qUtf8Printable(file.errorString()));
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()));
}
}
}
@@ -154,7 +168,7 @@ public:
if (!finfo.absoluteDir().exists()) {
QDir().mkpath(finfo.absolutePath());
}
file.setFileName(filePath);
file.setFileName(filePath + QStringLiteral(".0"));
file.open(QIODevice::WriteOnly | QIODevice::Unbuffered);
}

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

@@ -43,20 +43,27 @@
#include "chatdocumenthandler.h"
#include "clipboard.h"
#include "controller.h"
#include "delegatesizehelper.h"
#include "filetypesingleton.h"
#include "linkpreviewer.h"
#include "locationhelper.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/livelocationsmodel.h"
#include "models/locationsmodel.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"
@@ -158,7 +165,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"));
@@ -228,6 +235,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");
@@ -242,17 +250,23 @@ int main(int argc, char *argv[])
qmlRegisterType<StateModel>("org.kde.neochat", 1, 0, "StateModel");
qmlRegisterType<StateFilterModel>("org.kde.neochat", 1, 0, "StateFilterModel");
qmlRegisterType<SearchModel>("org.kde.neochat", 1, 0, "SearchModel");
qmlRegisterType<LiveLocationsModel>("org.kde.neochat", 1, 0, "LiveLocationsModel");
qmlRegisterType<LocationsModel>("org.kde.neochat", 1, 0, "LocationsModel");
#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<NeoChatUser>("org.kde.neochat", 1, 0, "NeoChatUser", {});
qmlRegisterUncreatableType<NeoChatRoom>("org.kde.neochat", 1, 0, "NeoChatRoom", {});
qRegisterMetaType<User *>("User*");
qRegisterMetaType<User *>("const User*");
@@ -274,6 +288,10 @@ int main(int argc, char *argv[])
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");
qmlRegisterSingletonType("org.kde.neochat", 1, 0, "LocationHelper", [](QQmlEngine *engine, QJSEngine *) -> QJSValue {
return engine->toScriptValue(LocationHelper());
});
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
qRegisterMetaTypeStreamOperators<Emoji>();

View File

@@ -0,0 +1,178 @@
// SPDX-FileCopyrightText: 2021-2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "accountemoticonmodel.h"
#include <csapi/content-repo.h>
#include <qcoro/qcorosignal.h>
using namespace Quotient;
AccountEmoticonModel::AccountEmoticonModel(QObject *parent)
: QAbstractListModel(parent)
{
}
int AccountEmoticonModel::rowCount(const QModelIndex &index) const
{
Q_UNUSED(index);
if (!m_images) {
return 0;
}
return m_images->images.size();
}
QVariant AccountEmoticonModel::data(const QModelIndex &index, int role) const
{
const auto &row = index.row();
const auto &image = m_images->images[row];
if (role == UrlRole) {
#ifdef QUOTIENT_07
return m_connection->makeMediaUrl(image.url);
#else
return QUrl();
#endif
}
if (role == BodyRole) {
if (image.body) {
return *image.body;
}
}
if (role == ShortCodeRole) {
return image.shortcode;
}
if (role == IsStickerRole) {
if (image.usage) {
return image.usage->isEmpty() || image.usage->contains("sticker"_ls);
}
if (m_images->pack && m_images->pack->usage) {
return m_images->pack->usage->isEmpty() || m_images->pack->usage->contains("sticker"_ls);
}
return true;
}
if (role == IsEmojiRole) {
if (image.usage) {
return image.usage->isEmpty() || image.usage->contains("emoticon"_ls);
}
if (m_images->pack && m_images->pack->usage) {
return m_images->pack->usage->isEmpty() || m_images->pack->usage->contains("emoticon"_ls);
}
return true;
}
return {};
}
QHash<int, QByteArray> AccountEmoticonModel::roleNames() const
{
return {
{AccountEmoticonModel::UrlRole, "url"},
{AccountEmoticonModel::BodyRole, "body"},
{AccountEmoticonModel::ShortCodeRole, "shortcode"},
{AccountEmoticonModel::IsStickerRole, "isSticker"},
{AccountEmoticonModel::IsEmojiRole, "isEmoji"},
};
}
Connection *AccountEmoticonModel::connection() const
{
return m_connection;
}
void AccountEmoticonModel::setConnection(Connection *connection)
{
if (m_connection) {
disconnect(m_connection, nullptr, this, nullptr);
}
m_connection = connection;
Q_EMIT connectionChanged();
connect(m_connection, &Connection::accountDataChanged, this, [this](QString type) {
if (type == QStringLiteral("im.ponies.user_emotes")) {
reloadEmoticons();
}
});
reloadEmoticons();
}
void AccountEmoticonModel::reloadEmoticons()
{
QJsonObject json;
if (m_connection->hasAccountData("im.ponies.user_emotes"_ls)) {
json = m_connection->accountData("im.ponies.user_emotes"_ls)->contentJson();
}
const auto &content = ImagePackEventContent(json);
beginResetModel();
m_images = content;
endResetModel();
}
void AccountEmoticonModel::deleteEmoticon(int index)
{
QJsonObject data;
m_images->images.removeAt(index);
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
}
void AccountEmoticonModel::setEmoticonBody(int index, const QString &text)
{
m_images->images[index].body = text;
QJsonObject data;
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
}
void AccountEmoticonModel::setEmoticonShortcode(int index, const QString &shortcode)
{
m_images->images[index].shortcode = shortcode;
QJsonObject data;
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
}
void AccountEmoticonModel::setEmoticonImage(int index, const QUrl &source)
{
doSetEmoticonImage(index, source);
}
QCoro::Task<void> AccountEmoticonModel::doSetEmoticonImage(int index, QUrl source)
{
auto job = m_connection->uploadFile(source.isLocalFile() ? source.toLocalFile() : source.toString());
co_await qCoro(job, &BaseJob::finished);
if (job->error() != BaseJob::NoError) {
co_return;
}
#ifdef QUOTIENT_07
m_images->images[index].url = job->contentUri().toString();
#else
m_images->images[index].url = job->contentUri();
#endif
m_images->images[index].info = none;
QJsonObject data;
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
}
QCoro::Task<void> AccountEmoticonModel::doAddEmoticon(QUrl source, QString shortcode, QString description, QString type)
{
auto job = m_connection->uploadFile(source.isLocalFile() ? source.toLocalFile() : source.toString());
co_await qCoro(job, &BaseJob::finished);
if (job->error() != BaseJob::NoError) {
co_return;
}
m_images->images.append(ImagePackEventContent::ImagePackImage{
shortcode,
job->contentUri(),
description,
none,
QStringList{type},
});
QJsonObject data;
m_images->fillJson(&data);
m_connection->setAccountData("im.ponies.user_emotes"_ls, data);
}
void AccountEmoticonModel::addEmoticon(const QUrl &source, const QString &shortcode, const QString &description, const QString &type)
{
doAddEmoticon(source, shortcode, description, type);
}

View File

@@ -0,0 +1,101 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include "events/imagepackevent.h"
#include <QAbstractListModel>
#include <QCoroTask>
#include <QObject>
#include <QPointer>
#include <QVector>
#include <connection.h>
class ImagePacksModel;
/**
* @class AccountEmoticonModel
*
* This class defines the model for visualising the account stickers and emojis.
*
* This is based upon the im.ponies.user_emotes spec (MSC2545).
*/
class AccountEmoticonModel : public QAbstractListModel
{
Q_OBJECT
/**
* @brief The connection to get emoticons from.
*/
Q_PROPERTY(Quotient::Connection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
public:
enum Roles {
UrlRole = Qt::UserRole + 1, /**< The URL for the emoticon. */
ShortCodeRole, /**< The shortcode for the emoticon. */
BodyRole, //**< A textual description of the emoticon */
IsStickerRole, //**< Whether this emoticon is a sticker */
IsEmojiRole, //**< Whether this emoticon is an emoji */
};
explicit AccountEmoticonModel(QObject *parent = nullptr);
/**
* @brief Number of rows in the model.
*
* @sa QAbstractItemModel::rowCount
*/
[[nodiscard]] int rowCount(const QModelIndex &index) const override;
/**
* @brief Get the given role value at the given index.
*
* @sa QAbstractItemModel::data
*/
[[nodiscard]] QVariant data(const QModelIndex &index, int role) const override;
/**
* @brief Returns a mapping from Role enum values to role names.
*
* @sa Roles, QAbstractItemModel::roleNames()
*/
[[nodiscard]] QHash<int, QByteArray> roleNames() const override;
[[nodiscard]] Quotient::Connection *connection() const;
void setConnection(Quotient::Connection *connection);
/**
* @brief Deletes the emoticon at the given index.
*/
Q_INVOKABLE void deleteEmoticon(int index);
/**
* @brief Changes the description for the emoticon at the given index.
*/
Q_INVOKABLE void setEmoticonBody(int index, const QString &text);
/**
* @brief Changes the shortcode for the emoticon at the given index.
*/
Q_INVOKABLE void setEmoticonShortcode(int index, const QString &shortCode);
/**
* @brief Changes the image for the emoticon at the given index.
*/
Q_INVOKABLE void setEmoticonImage(int index, const QUrl &source);
/**
* @brief Add an emoticon with the given parameters.
*/
Q_INVOKABLE void addEmoticon(const QUrl &source, const QString &shortcode, const QString &description, const QString &type);
Q_SIGNALS:
void connectionChanged();
private:
std::optional<Quotient::ImagePackEventContent> m_images;
QPointer<Quotient::Connection> m_connection;
QCoro::Task<void> doSetEmoticonImage(int index, QUrl source);
QCoro::Task<void> doAddEmoticon(QUrl source, QString shortcode, QString description, QString type);
void reloadEmoticons();
};

View File

@@ -11,8 +11,9 @@ bool CollapseStateProxyModel::filterAcceptsRow(int source_row, const QModelIndex
Q_UNUSED(source_parent);
return sourceModel()->data(sourceModel()->index(source_row, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If this is not a state, show it
|| sourceModel()->data(sourceModel()->index(source_row + 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If this is the first state in a block, show it. TODO hidden events?
|| (source_row < sourceModel()->rowCount() - 1
&& sourceModel()->data(sourceModel()->index(source_row + 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State) // If this is the first state in a block, show it. TODO hidden events?
|| sourceModel()->data(sourceModel()->index(source_row, 0), MessageEventModel::ShowSectionRole).toBool(); // If it's a new day, show it
}
@@ -50,10 +51,11 @@ QString CollapseStateProxyModel::aggregateEventToString(int sourceRow) const
if (!uniqueAuthors.contains(nextAuthor)) {
uniqueAuthors.append(nextAuthor);
}
if (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If it's not a state event
|| sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::ShowSectionRole).toBool() // or the section needs to be visible
) {
if (i > 0
&& (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If it's not a state event
|| sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::ShowSectionRole).toBool() // or the section needs to be visible
)) {
break;
}
}
@@ -108,10 +110,11 @@ QVariantList CollapseStateProxyModel::stateEventsList(int sourceRow) const
{"text", sourceModel()->data(sourceModel()->index(i, 0), Qt::DisplayRole).toString()},
};
stateEvents.append(nextState);
if (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If it's not a state event
|| sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::ShowSectionRole).toBool() // or the section needs to be visible
) {
if (i > 0
&& (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If it's not a state event
|| sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::ShowSectionRole).toBool() // or the section needs to be visible
)) {
break;
}
}
@@ -126,10 +129,11 @@ QVariantList CollapseStateProxyModel::authorList(int sourceRow) const
if (!uniqueAuthors.contains(nextAvatar)) {
uniqueAuthors.append(nextAvatar);
}
if (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If it's not a state event
|| sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::ShowSectionRole).toBool() // or the section needs to be visible
) {
if (i > 0
&& (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If it's not a state event
|| sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::ShowSectionRole).toBool() // or the section needs to be visible
)) {
break;
}
}
@@ -148,10 +152,11 @@ QString CollapseStateProxyModel::excessAuthors(int row) const
if (!uniqueAuthors.contains(nextAvatar)) {
uniqueAuthors.append(nextAvatar);
}
if (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If it's not a state event
|| sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::ShowSectionRole).toBool() // or the section needs to be visible
) {
if (i > 0
&& (sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::DelegateTypeRole)
!= MessageEventModel::DelegateType::State // If it's not a state event
|| sourceModel()->data(sourceModel()->index(i - 1, 0), MessageEventModel::ShowSectionRole).toBool() // or the section needs to be visible
)) {
break;
}
}

View File

@@ -54,7 +54,7 @@ QVariant CompletionModel::data(const QModelIndex &index, int role) const
auto filterIndex = m_filterModel->index(index.row(), 0);
if (m_autoCompletionType == User) {
if (role == Text) {
return m_filterModel->data(filterIndex, UserListModel::NameRole);
return m_filterModel->data(filterIndex, UserListModel::DisplayNameRole);
}
if (role == Subtitle) {
return m_filterModel->data(filterIndex, UserListModel::UserIdRole);
@@ -123,7 +123,7 @@ void CompletionModel::updateCompletion()
if (text().startsWith(QLatin1Char('@'))) {
m_filterModel->setSourceModel(m_userListModel);
m_filterModel->setFilterRole(UserListModel::UserIdRole);
m_filterModel->setSecondaryFilterRole(UserListModel::NameRole);
m_filterModel->setSecondaryFilterRole(UserListModel::DisplayNameRole);
m_filterModel->setFullText(m_fullText);
m_filterModel->setFilterText(m_text);
m_autoCompletionType = User;

View File

@@ -16,12 +16,6 @@
using namespace Quotient;
#ifdef QUOTIENT_07
#define running isJobPending
#else
#define running isJobRunning
#endif
void CustomEmojiModel::fetchEmojis()
{
if (!Controller::instance().activeConnection()) {
@@ -62,36 +56,35 @@ void CustomEmojiModel::addEmoji(const QString &name, const QUrl &location)
auto job = Controller::instance().activeConnection()->uploadFile(location.toLocalFile());
if (running(job)) {
connect(job, &BaseJob::success, this, [name, location, job] {
const auto &data = Controller::instance().activeConnection()->accountData("im.ponies.user_emotes");
auto json = data != nullptr ? data->contentJson() : QJsonObject();
auto emojiData = json["images"].toObject();
connect(job, &BaseJob::success, this, [name, location, job] {
const auto &data = Controller::instance().activeConnection()->accountData("im.ponies.user_emotes");
auto json = data != nullptr ? data->contentJson() : QJsonObject();
auto emojiData = json["images"].toObject();
QString url;
QString url;
#ifdef QUOTIENT_07
url = job->contentUri().toString();
url = job->contentUri().toString();
#else
url = job->contentUri();
url = job->contentUri();
#endif
QImage image(location.toLocalFile());
QJsonObject imageInfo;
imageInfo["w"] = image.width();
imageInfo["h"] = image.height();
imageInfo["mimetype"] = QMimeDatabase().mimeTypeForFile(location.toLocalFile()).name();
imageInfo["size"] = image.sizeInBytes();
QImage image(location.toLocalFile());
QJsonObject imageInfo;
imageInfo["w"] = image.width();
imageInfo["h"] = image.height();
imageInfo["mimetype"] = QMimeDatabase().mimeTypeForFile(location.toLocalFile()).name();
imageInfo["size"] = image.sizeInBytes();
emojiData[QStringLiteral("%1").arg(name)] = QJsonObject({
{QStringLiteral("url"), url},
{QStringLiteral("info"), imageInfo},
{QStringLiteral("body"), location.fileName()},
});
json["images"] = emojiData;
Controller::instance().activeConnection()->setAccountData("im.ponies.user_emotes", json);
emojiData[QStringLiteral("%1").arg(name)] = QJsonObject({
{QStringLiteral("url"), url},
{QStringLiteral("info"), imageInfo},
{QStringLiteral("body"), location.fileName()},
{"usage"_ls, "emoticon"_ls},
});
}
json["images"] = emojiData;
Controller::instance().activeConnection()->setAccountData("im.ponies.user_emotes", json);
});
}
void CustomEmojiModel::removeEmoji(const QString &name)

View File

@@ -0,0 +1,55 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#include "emoticonfiltermodel.h"
#include "accountemoticonmodel.h"
#include "stickermodel.h"
EmoticonFilterModel::EmoticonFilterModel(QObject *parent)
: QSortFilterProxyModel(parent)
{
connect(this, &EmoticonFilterModel::sourceModelChanged, this, [this]() {
if (dynamic_cast<StickerModel *>(sourceModel())) {
m_stickerRole = StickerModel::IsStickerRole;
m_emojiRole = StickerModel::IsEmojiRole;
} else {
m_stickerRole = AccountEmoticonModel::IsStickerRole;
m_emojiRole = AccountEmoticonModel::IsEmojiRole;
}
});
}
bool EmoticonFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
Q_UNUSED(sourceParent);
auto stickerUsage = sourceModel()->data(sourceModel()->index(sourceRow, 0), m_stickerRole).toBool();
auto emojiUsage = sourceModel()->data(sourceModel()->index(sourceRow, 0), m_emojiRole).toBool();
return (stickerUsage && m_showStickers) || (emojiUsage && m_showEmojis);
}
bool EmoticonFilterModel::showStickers() const
{
return m_showStickers;
}
void EmoticonFilterModel::setShowStickers(bool showStickers)
{
beginResetModel();
m_showStickers = showStickers;
endResetModel();
Q_EMIT showStickersChanged();
}
bool EmoticonFilterModel::showEmojis() const
{
return m_showEmojis;
}
void EmoticonFilterModel::setShowEmojis(bool showEmojis)
{
beginResetModel();
m_showEmojis = showEmojis;
endResetModel();
Q_EMIT showEmojisChanged();
}

View File

@@ -0,0 +1,51 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#include <QSortFilterProxyModel>
/**
* @class EmoticonFilterModel
*
* This class creates a custom QSortFilterProxyModel for filtering a emoticon by type
* (Sticker or Emoji).
*/
class EmoticonFilterModel : public QSortFilterProxyModel
{
Q_OBJECT
/**
* @brief Whether stickers should be shown
*/
Q_PROPERTY(bool showStickers READ showStickers WRITE setShowStickers NOTIFY showStickersChanged)
/**
* @brief Whether emojis show be shown
*/
Q_PROPERTY(bool showEmojis READ showEmojis WRITE setShowEmojis NOTIFY showEmojisChanged)
public:
explicit EmoticonFilterModel(QObject *parent = nullptr);
/**
* @brief Custom filter function checking the type of emoticon
*
* @note The filter cannot be modified and will always use the same filter properties.
*/
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;
[[nodiscard]] bool showStickers() const;
void setShowStickers(bool showStickers);
[[nodiscard]] bool showEmojis() const;
void setShowEmojis(bool showEmojis);
Q_SIGNALS:
void showStickersChanged();
void showEmojisChanged();
private:
bool m_showStickers = false;
bool m_showEmojis = false;
int m_stickerRole = 0;
int m_emojiRole = 0;
};

View File

@@ -15,12 +15,17 @@ ImagePacksModel::ImagePacksModel(QObject *parent)
int ImagePacksModel::rowCount(const QModelIndex &index) const
{
Q_UNUSED(index);
return m_events.count();
}
QVariant ImagePacksModel::data(const QModelIndex &index, int role) const
{
const auto &event = m_events[index.row()];
const auto row = index.row();
if (row < 0 || row >= m_events.size()) {
return {};
}
const auto &event = m_events[row];
if (role == DisplayNameRole) {
if (event.pack->displayName) {
return *event.pack->displayName;
@@ -59,24 +64,38 @@ void ImagePacksModel::setRoom(NeoChatRoom *room)
{
if (m_room) {
disconnect(m_room, nullptr, this, nullptr);
disconnect(m_room->connection(), nullptr, this, nullptr);
}
m_room = room;
connect(m_room->connection(), &Connection::accountDataChanged, this, [this](const QString &type) {
if (type == "im.ponies.user_emotes"_ls) {
reloadImages();
}
});
// TODO listen to packs changing
reloadImages();
Q_EMIT roomChanged();
}
void ImagePacksModel::reloadImages()
{
beginResetModel();
m_events.clear();
// TODO listen to account data changing
// TODO listen to packs changing
// Load emoticons from the account data
if (m_room->connection()->hasAccountData("im.ponies.user_emotes"_ls)) {
auto json = m_room->connection()->accountData("im.ponies.user_emotes"_ls)->contentJson();
json["pack"] = QJsonObject{
{"display_name", i18n("Own Stickers")},
{"display_name", m_showStickers ? i18nc("As in 'The user's own Stickers'", "Own Stickers") : i18nc("As in 'The user's own emojis", "Own Emojis")},
};
const auto &content = ImagePackEventContent(json);
if (!content.images.isEmpty()) {
m_events += ImagePackEventContent(json);
}
}
// Load emoticons from the saved rooms
const auto &accountData = m_room->connection()->accountData("im.ponies.emote_rooms"_ls);
if (accountData) {
const auto &rooms = accountData->contentJson()["rooms"_ls].toObject();
@@ -88,11 +107,11 @@ void ImagePacksModel::setRoom(NeoChatRoom *room)
const auto &stickerRoom = m_room->connection()->room(roomId);
for (const auto &packKey : packs.keys()) {
#ifdef QUOTIENT_07
const auto &pack = stickerRoom->currentState().get<ImagePackEvent>(packKey);
if (pack) {
if (const auto &pack = stickerRoom->currentState().get<ImagePackEvent>(packKey)) {
const auto packContent = pack->content();
if (!packContent.pack->usage || (packContent.pack->usage->contains("emoticon") && showEmoticons())
|| (packContent.pack->usage->contains("sticker") && showStickers())) {
if ((!packContent.pack || !packContent.pack->usage || (packContent.pack->usage->contains("emoticon") && showEmoticons())
|| (packContent.pack->usage->contains("sticker") && showStickers()))
&& !packContent.images.isEmpty()) {
m_events += packContent;
}
}
@@ -101,17 +120,21 @@ void ImagePacksModel::setRoom(NeoChatRoom *room)
}
}
#ifdef QUOTIENT_07
// Load emoticons from the current room
auto events = m_room->currentState().eventsOfType("im.ponies.room_emotes");
for (const auto &event : events) {
auto packContent = eventCast<const ImagePackEvent>(event)->content();
if (!packContent.pack->usage || (packContent.pack->usage->contains("emoticon") && showEmoticons())
|| (packContent.pack->usage->contains("sticker") && showStickers())) {
m_events += packContent;
if (packContent.pack.has_value()) {
if (!packContent.pack->usage || (packContent.pack->usage->contains("emoticon") && showEmoticons())
|| (packContent.pack->usage->contains("sticker") && showStickers())) {
m_events += packContent;
}
}
}
#endif
Q_EMIT imagesLoaded();
endResetModel();
Q_EMIT roomChanged();
}
bool ImagePacksModel::showStickers() const

View File

@@ -90,10 +90,12 @@ Q_SIGNALS:
void roomChanged();
void showStickersChanged();
void showEmoticonsChanged();
void imagesLoaded();
private:
QPointer<NeoChatRoom> m_room;
QVector<Quotient::ImagePackEventContent> m_events;
bool m_showStickers = true;
bool m_showEmoticons = true;
void reloadImages();
};

View File

@@ -0,0 +1,171 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#include "livelocationsmodel.h"
#include <Quotient/events/roommessageevent.h>
#include <QDebug>
using namespace Quotient;
bool operator<(const LiveLocationData &lhs, const LiveLocationData &rhs)
{
return lhs.eventId < rhs.eventId;
}
LiveLocationsModel::LiveLocationsModel(QObject *parent)
: QAbstractListModel(parent)
{
connect(
this,
&LiveLocationsModel::roomChanged,
this,
[this]() {
for (const auto &event : m_room->messageEvents()) {
addEvent(event.get());
}
connect(m_room, &NeoChatRoom::aboutToAddHistoricalMessages, this, [this](const auto &events) {
for (const auto &event : events) {
addEvent(event.get());
}
});
connect(m_room, &NeoChatRoom::aboutToAddNewMessages, this, [this](const auto &events) {
for (const auto &event : events) {
addEvent(event.get());
}
});
},
Qt::QueuedConnection); // deferred so we are sure the eventId filter is set
connect(this, &LiveLocationsModel::dataChanged, this, &LiveLocationsModel::boundingBoxChanged);
connect(this, &LiveLocationsModel::rowsInserted, this, &LiveLocationsModel::boundingBoxChanged);
}
int LiveLocationsModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return m_locations.size();
}
QVariant LiveLocationsModel::data(const QModelIndex &index, int roleName) const
{
if (!checkIndex(index)) {
return {};
}
const auto &data = m_locations.at(index.row());
switch (roleName) {
case LatitudeRole: {
const auto geoUri = data.beacon["org.matrix.msc3488.location"_ls].toObject()["uri"_ls].toString();
if (geoUri.isEmpty()) {
return {};
}
const auto latitude = geoUri.split(u';')[0].split(u':')[1].split(u',')[0];
return latitude.toFloat();
}
case LongitudeRole: {
const auto geoUri = data.beacon["org.matrix.msc3488.location"_ls].toObject()["uri"_ls].toString();
if (geoUri.isEmpty()) {
return {};
}
const auto longitude = geoUri.split(u';')[0].split(u':')[1].split(u',')[1];
return longitude.toFloat();
}
case AssetRole:
return data.beaconInfo["org.matrix.msc3488.asset"_ls].toObject()["type"].toString();
case AuthorRole:
return m_room->getUser(data.senderId);
case IsLiveRole: {
if (!data.beaconInfo["live"_ls].toBool()) {
return false;
}
// TODO Qt6: port to toInteger(), timestamps are in ms since epoch, ie. 64 bit values
const auto lastTs = std::max(data.beaconInfo.value("org.matrix.msc3488.ts"_ls).toDouble(), data.beacon.value("org.matrix.msc3488.ts"_ls).toDouble());
const auto timeout = data.beaconInfo.value("timeout"_ls).toDouble(600000);
return lastTs + timeout >= QDateTime::currentDateTime().toMSecsSinceEpoch();
}
}
return {};
}
QHash<int, QByteArray> LiveLocationsModel::roleNames() const
{
auto r = QAbstractListModel::roleNames();
r.insert(LatitudeRole, "latitude");
r.insert(LongitudeRole, "longitude");
r.insert(AssetRole, "asset");
r.insert(AuthorRole, "author");
r.insert(IsLiveRole, "isLive");
return r;
}
QRectF LiveLocationsModel::boundingBox() const
{
QRectF bbox(QPointF(180.0, 90.0), QPointF(-180.0, -90.0));
for (auto i = 0; i < rowCount(); ++i) {
const auto lat = data(index(i, 0), LatitudeRole).toDouble();
const auto lon = data(index(i, 0), LongitudeRole).toDouble();
bbox.setLeft(std::min(bbox.left(), lon));
bbox.setRight(std::max(bbox.right(), lon));
bbox.setTop(std::min(bbox.top(), lat));
bbox.setBottom(std::max(bbox.bottom(), lat));
}
return bbox;
}
void LiveLocationsModel::addEvent(const Quotient::RoomEvent *event)
{
if (event->isStateEvent() && event->matrixType() == "org.matrix.msc3672.beacon_info") {
LiveLocationData data;
data.senderId = event->senderId();
data.beaconInfo = event->contentJson();
if (event->contentJson()["live"_ls].toBool()) {
data.eventId = event->id();
} else {
data.eventId = event->fullJson()["replaces_state"_ls].toString();
}
updateLocationData(std::move(data));
}
if (event->matrixType() == "org.matrix.msc3672.beacon"_ls) {
LiveLocationData data;
data.eventId = event->contentJson()["m.relates_to"_ls].toObject()["event_id"_ls].toString();
data.senderId = event->senderId();
data.beacon = event->contentJson();
updateLocationData(std::move(data));
}
}
void LiveLocationsModel::updateLocationData(LiveLocationData &&data)
{
if (!m_eventId.isEmpty() && data.eventId != m_eventId) {
return;
}
auto it = std::lower_bound(m_locations.begin(), m_locations.end(), data);
if (it == m_locations.end() || it->eventId != data.eventId) {
const auto row = std::distance(m_locations.begin(), it);
beginInsertRows({}, row, row);
m_locations.insert(it, std::move(data));
endInsertRows();
return;
}
const auto idx = index(std::distance(m_locations.begin(), it), 0);
// TODO Qt6: port to toInteger(), timestamps are in ms since epoch, ie. 64 bit values
if (it->beacon.isEmpty() || it->beacon.value("org.matrix.msc3488.ts"_ls).toDouble() < data.beacon.value("org.matrix.msc3488.ts"_ls).toDouble()) {
it->beacon = std::move(data.beacon);
}
if (it->beaconInfo.isEmpty()
|| it->beaconInfo.value("org.matrix.msc3488.ts"_ls).toDouble() < data.beaconInfo.value("org.matrix.msc3488.ts"_ls).toDouble()) {
it->beaconInfo = std::move(data.beaconInfo);
}
Q_EMIT dataChanged(idx, idx);
}

View File

@@ -0,0 +1,74 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "neochatroom.h"
#include <QAbstractListModel>
#include <QPointer>
#include <QRectF>
namespace Quotient
{
class RoomMessageEvent;
}
struct LiveLocationData {
QString eventId;
QString senderId;
QJsonObject beaconInfo;
QJsonObject beacon;
};
bool operator<(const LiveLocationData &lhs, const LiveLocationData &rhs);
/** Accumulates live location beacon events in a given room
* and provides the last known state for one or more live location beacons.
*/
class LiveLocationsModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(NeoChatRoom *room MEMBER m_room NOTIFY roomChanged)
/** The event id of the beacon start event, ie. the one all suspequent
* events use to relate to the same beacon.
* If this is set only this specific beacon will be coverd by this model,
* if it is empty, all beacons in the room will be covered.
*/
Q_PROPERTY(QString eventId MEMBER m_eventId NOTIFY eventIdChanged)
/** Bounding box of all live location beacons covered by this model. */
Q_PROPERTY(QRectF boundingBox READ boundingBox NOTIFY boundingBoxChanged)
public:
explicit LiveLocationsModel(QObject *parent = nullptr);
enum Roles {
LatitudeRole, /**< Latest latitude of a live locaction beacon. */
LongitudeRole, /**< Latest longitude of a live locaction beacon. */
AssetRole, /**< Type of location event, e.g. self pin of the user location. */
AuthorRole, /**< The author of the event. */
IsLiveRole, /**< Boolean that indicates whether a live location beacon is still live. */
};
Q_ENUM(Roles)
int rowCount(const QModelIndex &parent = {}) const override;
QVariant data(const QModelIndex &index, int roleName) const override;
QHash<int, QByteArray> roleNames() const override;
QRectF boundingBox() const;
Q_SIGNALS:
void roomChanged();
void eventIdChanged();
void boundingBoxChanged();
private:
void addEvent(const Quotient::RoomEvent *event);
void updateLocationData(LiveLocationData &&data);
QPointer<NeoChatRoom> m_room;
QString m_eventId;
QList<LiveLocationData> m_locations;
};

View File

@@ -0,0 +1,129 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#include "locationsmodel.h"
using namespace Quotient;
LocationsModel::LocationsModel(QObject *parent)
: QAbstractListModel(parent)
{
connect(this, &LocationsModel::roomChanged, this, [=]() {
for (const auto &event : m_room->messageEvents()) {
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"] == "m.location") {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
}
connect(m_room, &NeoChatRoom::aboutToAddHistoricalMessages, this, [=](const auto &events) {
for (const auto &event : events) {
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"] == "m.location") {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
}
});
connect(m_room, &NeoChatRoom::aboutToAddNewMessages, this, [=](const auto &events) {
for (const auto &event : events) {
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"] == "m.location") {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
}
});
});
connect(this, &LocationsModel::rowsInserted, this, &LocationsModel::boundingBoxChanged);
}
void LocationsModel::addLocation(const RoomMessageEvent *event)
{
const auto uri = event->contentJson()["org.matrix.msc3488.location"]["uri"].toString();
const auto parts = uri.mid(4).split(QLatin1Char(','));
if (parts.size() < 2) {
qWarning() << "invalid geo: URI" << uri;
return;
}
const auto latitude = parts[0].toFloat();
const auto longitude = parts[1].toFloat();
beginInsertRows(QModelIndex(), m_locations.size(), m_locations.size() + 1);
m_locations += LocationData{
.eventId = event->id(),
.latitude = latitude,
.longitude = longitude,
.content = event->contentJson(),
.author = dynamic_cast<NeoChatUser *>(m_room->user(event->senderId())),
};
endInsertRows();
}
NeoChatRoom *LocationsModel::room() const
{
return m_room;
}
void LocationsModel::setRoom(NeoChatRoom *room)
{
if (m_room) {
disconnect(this, nullptr, m_room, nullptr);
}
m_room = room;
Q_EMIT roomChanged();
}
QHash<int, QByteArray> LocationsModel::roleNames() const
{
return {
{LongitudeRole, "longitude"},
{LatitudeRole, "latitude"},
{TextRole, "text"},
{AssetRole, "asset"},
{AuthorRole, "author"},
};
}
QVariant LocationsModel::data(const QModelIndex &index, int roleName) const
{
auto row = index.row();
if (roleName == LongitudeRole) {
return m_locations[row].longitude;
} else if (roleName == LatitudeRole) {
return m_locations[row].latitude;
} else if (roleName == TextRole) {
return m_locations[row].content["body"_ls].toString();
} else if (roleName == AssetRole) {
return m_locations[row].content["org.matrix.msc3488.asset"_ls].toObject()["type"_ls].toString();
} else if (roleName == AuthorRole) {
return m_room->getUser(m_locations[row].author);
}
return {};
}
int LocationsModel::rowCount(const QModelIndex &parent) const
{
return m_locations.size();
}
QRectF LocationsModel::boundingBox() const
{
QRectF bbox(QPointF(180.0, 90.0), QPointF(-180.0, -90.0));
for (auto i = 0; i < rowCount(); ++i) {
const auto lat = data(index(i, 0), LatitudeRole).toDouble();
const auto lon = data(index(i, 0), LongitudeRole).toDouble();
bbox.setLeft(std::min(bbox.left(), lon));
bbox.setRight(std::max(bbox.right(), lon));
bbox.setTop(std::min(bbox.top(), lat));
bbox.setBottom(std::max(bbox.bottom(), lat));
}
return bbox;
}

View File

@@ -0,0 +1,58 @@
// SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <QAbstractListModel>
#include <QPointer>
#include <QRectF>
#include "neochatroom.h"
#include <events/roommessageevent.h>
class LocationsModel : public QAbstractListModel
{
Q_OBJECT
public:
enum Roles {
TextRole = Qt::DisplayRole,
LongitudeRole,
LatitudeRole,
AssetRole,
AuthorRole,
};
Q_ENUM(Roles)
Q_PROPERTY(NeoChatRoom *room READ room WRITE setRoom NOTIFY roomChanged)
/** Bounding box of all locations covered by this model. */
Q_PROPERTY(QRectF boundingBox READ boundingBox NOTIFY boundingBoxChanged)
explicit LocationsModel(QObject *parent = nullptr);
[[nodiscard]] NeoChatRoom *room() const;
void setRoom(NeoChatRoom *room);
QRectF boundingBox() const;
[[nodiscard]] QHash<int, QByteArray> roleNames() const override;
[[nodiscard]] QVariant data(const QModelIndex &index, int roleName) const override;
[[nodiscard]] int rowCount(const QModelIndex &parent = {}) const override;
Q_SIGNALS:
void roomChanged();
void boundingBoxChanged();
private:
QPointer<NeoChatRoom> m_room;
struct LocationData {
QString eventId;
float latitude;
float longitude;
QJsonObject content;
NeoChatUser *author;
};
QList<LocationData> m_locations;
void addLocation(const Quotient::RoomMessageEvent *event);
};

View File

@@ -6,12 +6,12 @@
#include "neochatconfig.h"
#include <connection.h>
#include <csapi/rooms.h>
#include <events/reactionevent.h>
#include <events/redactionevent.h>
#include <events/roomavatarevent.h>
#include <events/roommemberevent.h>
#include <events/simplestateevents.h>
#include <qt_connection_util.h>
#include <user.h>
#ifdef QUOTIENT_07
@@ -21,12 +21,12 @@
#include <QDebug>
#include <QGuiApplication>
#include <QQmlEngine> // for qmlRegisterType()
#include <QTimeZone>
#include <KFormat>
#include <KLocalizedString>
#include "models/reactionmodel.h"
#include "neochatuser.h"
#include "texthandler.h"
@@ -44,8 +44,7 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
roles[ContentRole] = "content";
roles[HighlightRole] = "isHighlighted";
roles[SpecialMarksRole] = "marks";
roles[LongOperationRole] = "progressInfo";
roles[EventResolvedTypeRole] = "eventResolvedType";
roles[ProgressInfoRole] = "progressInfo";
roles[ShowLinkPreviewRole] = "showLinkPreview";
roles[LinkPreviewRole] = "linkPreview";
roles[MediaInfoRole] = "mediaInfo";
@@ -61,9 +60,9 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
roles[ReadMarkersStringRole] = "readMarkersString";
roles[ShowReadMarkersRole] = "showReadMarkers";
roles[ReactionRole] = "reaction";
roles[ShowReactionsRole] = "showReactions";
roles[SourceRole] = "source";
roles[MimeTypeRole] = "mimeType";
roles[FormattedBodyRole] = "formattedBody";
roles[AuthorIdRole] = "authorId";
roles[VerifiedRole] = "verified";
roles[DisplayNameForInitialsRole] = "displayNameForInitials";
@@ -80,17 +79,11 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
MessageEventModel::MessageEventModel(QObject *parent)
: QAbstractListModel(parent)
{
using namespace Quotient;
qmlRegisterAnonymousType<FileTransferInfo>("org.kde.neochat", 1);
qRegisterMetaType<FileTransferInfo>();
connect(static_cast<QGuiApplication *>(QGuiApplication::instance()), &QGuiApplication::paletteChanged, this, [this] {
Q_EMIT dataChanged(index(0, 0), index(rowCount() - 1, 0), {AuthorRole, ReplyRole});
});
}
MessageEventModel::~MessageEventModel() = default;
NeoChatRoom *MessageEventModel::room() const
{
return m_currentRoom;
@@ -106,6 +99,8 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
if (m_currentRoom) {
m_currentRoom->disconnect(this);
m_linkPreviewers.clear();
qDeleteAll(m_reactionModels);
m_reactionModels.clear();
}
m_currentRoom = room;
@@ -116,6 +111,7 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
for (auto event = m_currentRoom->messageEvents().begin(); event != m_currentRoom->messageEvents().end(); ++event) {
if (auto e = &*event->viewAs<RoomMessageEvent>()) {
createLinkPreviewerForEvent(e);
createReactionModelForEvent(e);
}
}
@@ -127,13 +123,21 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
#else
lastReadEventId = room->readMarkerEventId();
#endif
connect(m_currentRoom, &NeoChatRoom::replyLoaded, this, [this](const auto &eventId, const auto &replyId) {
Q_UNUSED(replyId);
auto row = eventIdToRow(eventId);
if (row == -1) {
return;
}
Q_EMIT dataChanged(index(row, 0), index(row, 0), {ReplyRole, ReplyMediaInfoRole, ReplyAuthor});
});
using namespace Quotient;
connect(m_currentRoom, &Room::aboutToAddNewMessages, this, [this](RoomEventsRange events) {
for (auto &&event : events) {
const RoomMessageEvent *message = dynamic_cast<RoomMessageEvent *>(event.get());
if (message != nullptr) {
createLinkPreviewerForEvent(message);
createReactionModelForEvent(message);
if (NeoChatConfig::self()->showFancyEffects()) {
QString planBody = message->plainBody();
@@ -173,6 +177,7 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
RoomMessageEvent *message = dynamic_cast<RoomMessageEvent *>(event.get());
if (message) {
createLinkPreviewerForEvent(message);
createReactionModelForEvent(message);
}
}
if (rowCount() > 0) {
@@ -244,7 +249,11 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
if (eventId.isEmpty()) { // How did we get here?
return;
}
refreshEventRoles(eventId, {ReactionRole, Qt::DisplayRole});
const auto eventIt = m_currentRoom->findInTimeline(eventId);
if (eventIt != m_currentRoom->historyEdge()) {
createReactionModelForEvent(static_cast<const RoomMessageEvent *>(&**eventIt));
}
refreshEventRoles(eventId, {ReactionRole, ShowReactionsRole, Qt::DisplayRole});
});
connect(m_currentRoom, &Room::changed, this, [this]() {
for (auto it = m_currentRoom->messageEvents().rbegin(); it != m_currentRoom->messageEvents().rend(); ++it) {
@@ -382,25 +391,6 @@ QDateTime MessageEventModel::makeMessageTimestamp(const Quotient::Room::rev_iter
return {};
}
QString MessageEventModel::renderDate(const QDateTime &timestamp)
{
auto date = timestamp.toLocalTime().date();
if (date == QDate::currentDate()) {
return i18n("Today");
}
if (date == QDate::currentDate().addDays(-1)) {
return i18n("Yesterday");
}
if (date == QDate::currentDate().addDays(-2)) {
return i18n("The day before yesterday");
}
if (date > QDate::currentDate().addDays(-7)) {
return date.toString("dddd");
}
return QLocale::system().toString(date, QLocale::ShortFormat);
}
void MessageEventModel::refreshLastUserEvents(int baseTimelineRow)
{
if (!m_currentRoom || m_currentRoom->timelineSize() <= baseTimelineRow) {
@@ -448,37 +438,13 @@ void MessageEventModel::fetchMore(const QModelIndex &parent)
}
}
static const QVariantMap emptyUser = {
{"isLocalUser", false},
{"id", QString()},
{"avatarSource", QUrl()},
{"avatarMediaId", QString()},
{"avatarUrl", QString()},
{"displayName", QString()},
{"display", QString()},
{"color", QColor()},
{"object", QVariant()},
};
inline QVariantMap userInContext(NeoChatUser *user, NeoChatRoom *room)
{
return QVariantMap{
{"isLocalUser", user->id() == room->localUser()->id()},
{"id", user->id()},
{"avatarSource", room->avatarForMember(user)},
{"avatarMediaId", user->avatarMediaId(room)},
{"avatarUrl", user->avatarUrl(room)},
{"displayName", user->displayname(room)},
{"display", user->name()},
{"color", user->color()},
{"object", QVariant::fromValue(user)},
};
}
static LinkPreviewer *emptyLinkPreview = new LinkPreviewer;
QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
{
if (!checkIndex(idx, QAbstractItemModel::CheckIndexOption::IndexIsValid)) {
return {};
}
const auto row = idx.row();
if (!m_currentRoom || row < 0 || row >= int(m_currentRoom->pendingEvents().size()) + m_currentRoom->timelineSize()) {
@@ -523,16 +489,6 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return m_currentRoom->eventToGenericString(evt);
}
if (role == FormattedBodyRole) {
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
if (e->hasTextContent() && e->mimeType().name() != "text/plain") {
return static_cast<const Quotient::EventContent::TextContent *>(e->content())->body;
}
}
return {};
}
if (role == PlainText) {
return m_currentRoom->eventToString(evt);
}
@@ -569,6 +525,9 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return DelegateType::Sticker;
}
if (evt.isStateEvent()) {
if (evt.matrixType() == "org.matrix.msc3672.beacon_info"_ls) {
return DelegateType::LiveLocation;
}
return DelegateType::State;
}
if (is<const EncryptedEvent>(evt)) {
@@ -586,13 +545,9 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return DelegateType::Other;
}
if (role == EventResolvedTypeRole) {
return EventTypeRegistry::getMatrixType(evt.type());
}
if (role == AuthorRole) {
auto author = static_cast<NeoChatUser *>(isPending ? m_currentRoom->localUser() : m_currentRoom->user(evt.senderId()));
return userInContext(author, m_currentRoom);
return m_currentRoom->getUser(author);
}
if (role == ContentRole) {
@@ -683,6 +638,11 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return EventStatus::Hidden;
}
// hide ending live location beacons
if (evt.isStateEvent() && evt.matrixType() == "org.matrix.msc3672.beacon_info"_ls && !evt.contentJson()["live"_ls].toBool()) {
return EventStatus::Hidden;
}
return EventStatus::Normal;
}
@@ -690,7 +650,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return !evt.id().isEmpty() ? evt.id() : evt.transactionId();
}
if (role == LongOperationRole) {
if (role == ProgressInfoRole) {
if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
if (e->hasFileContent()) {
return QVariant::fromValue(m_currentRoom->fileTransferInfo(e->id()));
@@ -703,7 +663,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
if (role == TimeRole || role == SectionRole) {
auto ts = isPending ? pendingIt->lastUpdated() : makeMessageTimestamp(timelineIt);
return role == TimeRole ? QVariant(ts) : renderDate(ts);
return role == TimeRole ? QVariant(ts) : m_format.formatRelativeDate(ts.toLocalTime().date(), QLocale::ShortFormat);
}
if (role == ShowLinkPreviewRole) {
@@ -731,18 +691,18 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
}
if (role == ReplyAuthor) {
auto replyPtr = getReplyForEvent(evt);
auto replyPtr = m_currentRoom->getReplyForEvent(evt);
if (replyPtr) {
auto replyUser = static_cast<NeoChatUser *>(m_currentRoom->user(replyPtr->senderId()));
return userInContext(replyUser, m_currentRoom);
return m_currentRoom->getUser(replyUser);
} else {
return emptyUser;
return m_currentRoom->getUser(nullptr);
}
}
if (role == ReplyMediaInfoRole) {
auto replyPtr = getReplyForEvent(evt);
auto replyPtr = m_currentRoom->getReplyForEvent(evt);
if (!replyPtr) {
return {};
}
@@ -750,7 +710,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
}
if (role == ReplyRole) {
auto replyPtr = getReplyForEvent(evt);
auto replyPtr = m_currentRoom->getReplyForEvent(evt);
if (!replyPtr) {
return {};
}
@@ -873,7 +833,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
#else
auto user = static_cast<NeoChatUser *>(userId);
#endif
users += userInContext(user, m_currentRoom);
users += m_currentRoom->getUser(user);
}
return users;
@@ -932,38 +892,17 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
}
if (role == ReactionRole) {
const auto &annotations = m_currentRoom->relatedEvents(evt, EventRelation::Annotation());
if (annotations.isEmpty()) {
return {};
};
QMap<QString, QList<NeoChatUser *>> reactions = {};
for (const auto &a : annotations) {
if (a->isRedacted()) { // Just in case?
continue;
}
if (auto e = eventCast<const ReactionEvent>(a)) {
reactions[e->relation().key].append(static_cast<NeoChatUser *>(m_currentRoom->user(e->senderId())));
}
if (m_reactionModels.contains(evt.id())) {
return QVariant::fromValue<ReactionModel *>(m_reactionModels[evt.id()]);
} else {
return QVariantList();
}
if (reactions.isEmpty()) {
return {};
}
QVariantList res = {};
auto i = reactions.constBegin();
while (i != reactions.constEnd()) {
QVariantList authors;
for (auto author : i.value()) {
authors.append(userInContext(author, m_currentRoom));
}
bool hasLocalUser = i.value().contains(static_cast<NeoChatUser *>(m_currentRoom->localUser()));
res.append(QVariantMap{{"reaction", i.key()}, {"count", i.value().count()}, {"authors", authors}, {"hasLocalUser", hasLocalUser}});
++i;
}
return res;
}
if (role == ShowReactionsRole) {
return m_reactionModels.contains(evt.id());
}
if (role == AuthorIdRole) {
return evt.senderId();
}
@@ -1020,117 +959,6 @@ int MessageEventModel::eventIdToRow(const QString &eventID) const
return it - m_currentRoom->messageEvents().rbegin() + timelineBaseIndex();
}
QVariant MessageEventModel::getLastLocalUserMessageEventId()
{
QVariantMap targetMessage;
const auto &timelineBottom = m_currentRoom->messageEvents().rbegin();
// set a cap limit of 35 messages, to prevent loading a lot of messages
// in rooms where the user has not sent many messages
const auto limit = timelineBottom + std::min(35, m_currentRoom->timelineSize());
for (auto it = timelineBottom; it != limit; ++it) {
auto evt = it->event();
auto e = eventCast<const RoomMessageEvent>(evt);
if (!e) {
return {};
}
// check if the current message's sender's id is same as the user's id
if ((*it)->senderId() == m_currentRoom->localUser()->id()) {
auto content = (*it)->contentJson();
if (e->msgtype() != MessageEventType::Unknown) {
QString eventId;
if (content.contains("m.new_content")) {
// The message has been edited so we have to return the id of the original message instead of the replacement
eventId = content["m.relates_to"].toObject()["event_id"].toString();
} else {
// For any message that isn't an edit return the id of the current message
eventId = (*it)->id();
}
targetMessage.insert("event_id", eventId);
targetMessage.insert("formattedBody", content["formatted_body"].toString());
// Need to get the message from the original eventId or body will have * on the front
QModelIndex idx = index(eventIdToRow(eventId), 0);
targetMessage.insert("message", idx.data(Qt::UserRole + 2));
return targetMessage;
}
}
}
return targetMessage;
}
QVariant MessageEventModel::getLatestMessageFromRow(const int startRow)
{
QVariantMap replyResponse;
const auto &timelineBottom = m_currentRoom->messageEvents().rbegin() + startRow;
// set a cap limit of startRow + 35 messages, to prevent loading a lot of messages
// in rooms where the user has not sent many messages
const auto limit = timelineBottom + std::min(startRow + 35, m_currentRoom->timelineSize());
for (auto it = timelineBottom; it != limit; ++it) {
auto evt = it->event();
auto e = eventCast<const RoomMessageEvent>(evt);
if (!e) {
continue;
}
auto content = (*it)->contentJson();
if (e->msgtype() != MessageEventType::Unknown) {
QString eventId;
if (content.contains("m.new_content")) {
// The message has been edited so we have to return the id of the original message instead of the replacement
eventId = content["m.relates_to"].toObject()["event_id"].toString();
} else {
// For any message that isn't an edit return the id of the current message
eventId = (*it)->id();
}
replyResponse.insert("event_id", eventId);
// Need to get the message from the original eventId or body will have * on the front
QModelIndex idx = index(eventIdToRow(eventId), 0);
replyResponse.insert("message", idx.data(Qt::UserRole + 2));
replyResponse.insert("sender_id", QVariant::fromValue(m_currentRoom->getUser((*it)->senderId())));
replyResponse.insert("at", -it->index());
return replyResponse;
}
}
return replyResponse;
}
void MessageEventModel::loadReply(const QModelIndex &index)
{
auto job = m_currentRoom->connection()->callApi<GetOneRoomEventJob>(m_currentRoom->id(), data(index, ReplyIdRole).toString());
QPersistentModelIndex persistentIndex(index);
connect(job, &BaseJob::success, this, [this, job, persistentIndex] {
m_extraEvents.push_back(fromJson<event_ptr_tt<RoomEvent>>(job->jsonData()));
Q_EMIT dataChanged(persistentIndex, persistentIndex, {ReplyRole, ReplyMediaInfoRole, ReplyAuthor});
});
}
const RoomEvent *MessageEventModel::getReplyForEvent(const RoomEvent &event) const
{
const QString &replyEventId = event.contentJson()["m.relates_to"].toObject()["m.in_reply_to"].toObject()["event_id"].toString();
if (replyEventId.isEmpty()) {
return {};
};
const auto replyIt = m_currentRoom->findInTimeline(replyEventId);
const RoomEvent *replyPtr = replyIt != m_currentRoom->historyEdge() ? &**replyIt : nullptr;
if (!replyPtr) {
for (const auto &e : m_extraEvents) {
if (e->id() == replyEventId) {
replyPtr = e.get();
break;
}
}
}
return replyPtr;
}
QVariantMap MessageEventModel::getMediaInfoForEvent(const RoomEvent &event) const
{
QVariantMap mediaInfo;
@@ -1278,3 +1106,60 @@ void MessageEventModel::createLinkPreviewerForEvent(const Quotient::RoomMessageE
}
}
}
void MessageEventModel::createReactionModelForEvent(const Quotient::RoomMessageEvent *event)
{
if (event == nullptr) {
return;
}
auto eventId = event->id();
const auto &annotations = m_currentRoom->relatedEvents(eventId, EventRelation::Annotation());
if (annotations.isEmpty()) {
if (m_reactionModels.contains(eventId)) {
delete m_reactionModels[eventId];
m_reactionModels.remove(eventId);
}
return;
};
QMap<QString, QList<NeoChatUser *>> reactions = {};
for (const auto &a : annotations) {
if (a->isRedacted()) { // Just in case?
continue;
}
if (const auto &e = eventCast<const ReactionEvent>(a)) {
reactions[e->relation().key].append(static_cast<NeoChatUser *>(m_currentRoom->user(e->senderId())));
}
}
if (reactions.isEmpty()) {
if (m_reactionModels.contains(eventId)) {
delete m_reactionModels[eventId];
m_reactionModels.remove(eventId);
}
return;
}
QList<ReactionModel::Reaction> res;
auto i = reactions.constBegin();
while (i != reactions.constEnd()) {
QVariantList authors;
for (const auto &author : i.value()) {
authors.append(m_currentRoom->getUser(author));
}
res.append(ReactionModel::Reaction{i.key(), authors});
++i;
}
if (m_reactionModels.contains(eventId)) {
m_reactionModels[eventId]->setReactions(res);
} else if (res.size() > 0) {
m_reactionModels[eventId] = new ReactionModel(this, res, static_cast<NeoChatUser *>(m_currentRoom->localUser()));
} else {
if (m_reactionModels.contains(eventId)) {
delete m_reactionModels[eventId];
m_reactionModels.remove(eventId);
}
}
}

View File

@@ -3,11 +3,14 @@
#pragma once
#include <KFormat>
#include <QAbstractListModel>
#include "linkpreviewer.h"
#include "neochatroom.h"
class ReactionModel;
/**
* @class MessageEventModel
*
@@ -50,6 +53,7 @@ public:
ReadMarker, /**< The local user read marker. */
Poll, /**< The initial event for a poll. */
Location, /**< A location event. */
LiveLocation, /**< The initial event of a shared live location (i.e., the place where this is supposed to be shown in the timeline). */
Other, /**< Anything that cannot be classified as another type. */
};
Q_ENUM(DelegateType);
@@ -67,8 +71,7 @@ public:
ContentRole, /**< The full message content. */
HighlightRole, /**< Whether the event should be highlighted. */
SpecialMarksRole, /**< Whether the event is hidden or not. */
LongOperationRole, /**< Progress info when downloading files. */
FormattedBodyRole, /**< The formatted body of a rich message. */
ProgressInfoRole, /**< Progress info when downloading files. */
GenericDisplayRole, /**< A generic string based upon the message type. */
ShowLinkPreviewRole, /**< Whether a link preview should be shown. */
@@ -90,11 +93,10 @@ public:
ExcessReadMarkersRole, /**< The number of other users at the event after the first 5. */
ReadMarkersStringRole, /**< String with the display name and mxID of the users at the event. */
ShowReadMarkersRole, /**< Whether there are any other user read markers to be shown. */
ReactionRole, /**< List of reactions to this event. */
ReactionRole, /**< List model for this event. */
ShowReactionsRole, /**< Whether there are any reactions to be shown. */
SourceRole, /**< The full message source JSON. */
// For debugging
EventResolvedTypeRole, /**< The event type the message. */
AuthorIdRole, /**< Matrix ID of the message author. */
VerifiedRole, /**< Whether an encrypted message is sent in a verified session. */
@@ -110,7 +112,6 @@ public:
Q_ENUM(EventRoles)
explicit MessageEventModel(QObject *parent = nullptr);
~MessageEventModel() override;
[[nodiscard]] NeoChatRoom *room() const;
void setRoom(NeoChatRoom *room);
@@ -141,39 +142,6 @@ public:
*/
Q_INVOKABLE [[nodiscard]] int eventIdToRow(const QString &eventID) const;
/**
* @brief Get the last message sent by the local user.
*
* @note This checks a maximum of the previous 35 message for performance reasons.
*
* @return a QVariantMap for the event with the following parameters:
* - eventId - The event ID.
* - formattedBody - The message text formatted as Qt::RichText.
* - message - The message text formatted as Qt::PlainText.
*/
Q_INVOKABLE [[nodiscard]] QVariant getLastLocalUserMessageEventId();
/**
* @brief Get the last message sent earlier than the given row.
*
* @note This checks a maximum of the previous 35 message for performance reasons.
*
* @return a QVariantMap for the event with the following parameters:
* - eventId - The event ID.
* - message - The message text formatted as Qt::PlainText.
* - sender_id - The matrix ID of the sender.
* - at - The QModelIndex of the message.
*/
Q_INVOKABLE [[nodiscard]] QVariant getLatestMessageFromRow(const int startRow);
/**
* @brief Load the event that the item at the given index replied to.
*
* This is used to ensure that the reply data is available when the message that
* was replied to is outside the currently loaded timeline.
*/
Q_INVOKABLE void loadReply(const QModelIndex &index);
private Q_SLOTS:
int refreshEvent(const QString &eventId);
void refreshRow(int row);
@@ -184,12 +152,13 @@ private:
QPersistentModelIndex m_lastReadEventIndex;
int rowBelowInserted = -1;
bool movingEvent = false;
KFormat m_format;
QMap<QString, LinkPreviewer *> m_linkPreviewers;
QMap<QString, ReactionModel *> m_reactionModels;
[[nodiscard]] int timelineBaseIndex() const;
[[nodiscard]] QDateTime makeMessageTimestamp(const Quotient::Room::rev_iter_t &baseIt) const;
[[nodiscard]] static QString renderDate(const QDateTime &timestamp);
bool canFetchMore(const QModelIndex &parent) const override;
void fetchMore(const QModelIndex &parent) override;
@@ -199,12 +168,10 @@ private:
int refreshEventRoles(const QString &eventId, const QVector<int> &roles = {});
void moveReadMarker(const QString &toEventId);
const Quotient::RoomEvent *getReplyForEvent(const Quotient::RoomEvent &event) const;
QVariantMap getMediaInfoForEvent(const Quotient::RoomEvent &event) const;
QVariantMap getMediaInfoFromFileInfo(const Quotient::EventContent::FileInfo *fileInfo, const QString &eventId, bool isThumbnail = false) const;
void createLinkPreviewerForEvent(const Quotient::RoomMessageEvent *event);
std::vector<Quotient::event_ptr_tt<Quotient::RoomEvent>> m_extraEvents;
void createReactionModelForEvent(const Quotient::RoomMessageEvent *event);
// Hack to ensure that we don't call endInsertRows when we haven't called beginInsertRows
bool m_initialized = false;

View File

@@ -0,0 +1,110 @@
// 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 "reactionmodel.h"
#include <QDebug>
#include <KLocalizedString>
#include "neochatuser.h"
ReactionModel::ReactionModel(QObject *parent, QList<Reaction> reactions, NeoChatUser *localUser)
: QAbstractListModel(parent)
, m_localUser(localUser)
{
setReactions(reactions);
}
QVariant ReactionModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return {};
}
if (index.row() >= rowCount()) {
qDebug() << "ReactionModel, something's wrong: index.row() >= rowCount()";
return {};
}
const auto &reaction = m_reactions.at(index.row());
if (role == TextRole) {
if (reaction.authors.count() > 1) {
return reaction.reaction + QStringLiteral(" %1").arg(reaction.authors.count());
} else {
return reaction.reaction;
}
}
if (role == ReactionRole) {
return reaction.reaction;
}
if (role == ToolTipRole) {
QString text;
for (int i = 0; i < reaction.authors.count() && i < 3; i++) {
if (i != 0) {
if (i < reaction.authors.count() - 1) {
text += QStringLiteral(", ");
} else {
text += i18nc("Separate the usernames of users", " and ");
}
}
text += reaction.authors.at(i).toMap()["displayName"].toString();
}
if (reaction.authors.count() > 3) {
text += i18ncp("%1 is the number of other users", " and %1 other", " and %1 others", reaction.authors.count() - 3);
}
text = i18ncp("%2 is the users who reacted and %3 the emoji that was given",
"%2 reacted with %3",
"%2 reacted with %3",
reaction.authors.count(),
text,
reaction.reaction);
return text;
}
if (role == AuthorsRole) {
return reaction.authors;
}
if (role == HasLocalUser) {
for (auto author : reaction.authors) {
if (author.toMap()["id"] == m_localUser->id()) {
return true;
}
}
return false;
}
return {};
}
int ReactionModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_reactions.count();
}
void ReactionModel::setReactions(QList<Reaction> reactions)
{
beginResetModel();
m_reactions.clear();
m_reactions = reactions;
endResetModel();
}
QHash<int, QByteArray> ReactionModel::roleNames() const
{
return {
{TextRole, "text"},
{ReactionRole, "reaction"},
{ToolTipRole, "toolTip"},
{AuthorsRole, "authors"},
{HasLocalUser, "hasLocalUser"},
};
}

View File

@@ -0,0 +1,72 @@
// 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 <QAbstractListModel>
class NeoChatUser;
/**
* @class ReactionModel
*
* This class defines the model for visualising a list of reactions to an event.
*/
class ReactionModel : public QAbstractListModel
{
Q_OBJECT
public:
/**
* @brief Definition of an reaction.
*/
struct Reaction {
QString reaction; /**< The reaction emoji. */
QVariantList authors; /**< The list of authors who sent the given reaction. */
};
/**
* @brief Defines the model roles.
*/
enum Roles {
TextRole = Qt::DisplayRole, /**< The text to show in the reaction. */
ReactionRole, /**< The reaction emoji. */
ToolTipRole, /**< The tool tip to show for the reaction. */
AuthorsRole, /**< The list of authors who sent the given reaction. */
HasLocalUser, /**< Whether the local user is in the list of authors. */
};
ReactionModel(QObject *parent = nullptr, QList<Reaction> reactions = {}, NeoChatUser *localUser = nullptr);
/**
* @brief Get the given role value at the given index.
*
* @sa QAbstractItemModel::data
*/
[[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
/**
* @brief Number of rows in the model.
*
* @sa QAbstractItemModel::rowCount
*/
[[nodiscard]] int rowCount(const QModelIndex &parent = QModelIndex()) const override;
/**
* @brief Returns a mapping from Role enum values to role names.
*
* @sa Roles, QAbstractItemModel::roleNames()
*/
[[nodiscard]] QHash<int, QByteArray> roleNames() const override;
/**
* @brief Set the reactions data in the model.
*/
void setReactions(QList<Reaction> reactions);
private:
QList<Reaction> m_reactions;
NeoChatUser *m_localUser;
};
Q_DECLARE_METATYPE(ReactionModel *)

View File

@@ -158,7 +158,7 @@ void RoomListModel::doAddRoom(Room *r)
void RoomListModel::connectRoomSignals(NeoChatRoom *room)
{
connect(room, &Room::displaynameChanged, this, [this, room] {
refresh(room, {DisplayNameRole, NameRole});
refresh(room, {DisplayNameRole});
});
connect(room, &Room::unreadMessagesChanged, this, [this, room] {
refresh(room, {NotificationCountRole, HighlightCountRole});
@@ -281,7 +281,7 @@ void RoomListModel::updateRoom(Room *room, Room *prev)
}
// Ok, we're through with pre-checks, now for the real thing.
auto newRoom = static_cast<NeoChatRoom *>(room);
const auto it = std::find_if(m_rooms.begin(), m_rooms.end(), [=](const NeoChatRoom *r) {
const auto it = std::find_if(m_rooms.begin(), m_rooms.end(), [prev, newRoom](const NeoChatRoom *r) {
return r == prev || r == newRoom;
});
if (it != m_rooms.end()) {
@@ -333,9 +333,6 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
return QVariant();
}
NeoChatRoom *room = m_rooms.at(index.row());
if (role == NameRole) {
return !room->name().isEmpty() ? room->name() : room->displayName();
}
if (role == DisplayNameRole) {
return room->displayName();
}
@@ -434,7 +431,6 @@ void RoomListModel::refresh(NeoChatRoom *room, const QVector<int> &roles)
QHash<int, QByteArray> RoomListModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
roles[DisplayNameRole] = "displayName";
roles[AvatarRole] = "avatar";
roles[CanonicalAliasRole] = "canonicalAlias";

View File

@@ -58,8 +58,7 @@ public:
* @brief Defines the model roles.
*/
enum EventRoles {
NameRole = Qt::UserRole + 1, /**< The name of the room. */
DisplayNameRole, /**< The display name of the room. */
DisplayNameRole = Qt::DisplayRole, /**< The display name of the room. */
AvatarRole, /**< The source URL for the room's avatar. */
CanonicalAliasRole, /**< The room canonical alias. */
TopicRole, /**< The room topic. */

View File

@@ -2,6 +2,7 @@
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "searchmodel.h"
#include "events/stickerevent.h"
#include "messageeventmodel.h"
#include "neochatroom.h"
#include "neochatuser.h"
@@ -42,18 +43,18 @@ void SearchModel::search()
m_job = nullptr;
}
RoomEventFilter filter;
filter.unreadThreadNotifications = none;
filter.lazyLoadMembers = true;
filter.includeRedundantMembers = false;
filter.notRooms = QStringList();
filter.rooms = QStringList{m_room->id()};
filter.containsUrl = false;
SearchJob::RoomEventsCriteria criteria{
.searchTerm = m_searchText,
.keys = {},
.filter =
RoomEventFilter{
.unreadThreadNotifications = none,
.lazyLoadMembers = true,
.includeRedundantMembers = false,
.notRooms = {},
.rooms = {m_room->id()},
.containsUrl = false,
},
.filter = filter,
.orderBy = "recent",
.eventContext = SearchJob::IncludeEventContext{3, 3, true},
.includeState = false,
@@ -96,16 +97,7 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
case ShowAuthorRole:
return true;
case AuthorRole:
return QVariantMap{
{"isLocalUser", event.senderId() == m_room->localUser()->id()},
{"id", event.senderId()},
{"avatarMediaId", m_connection->user(event.senderId())->avatarMediaId(m_room)},
{"avatarUrl", m_connection->user(event.senderId())->avatarUrl(m_room)},
{"displayName", m_connection->user(event.senderId())->displayname(m_room)},
{"display", m_connection->user(event.senderId())->name()},
{"color", dynamic_cast<NeoChatUser *>(m_connection->user(event.senderId()))->color()},
{"object", QVariant::fromValue(m_connection->user(event.senderId()))},
};
return m_room->getUser(event.senderId());
case ShowSectionRole:
if (row == 0) {
return true;
@@ -115,6 +107,72 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
return renderDate(event.originTimestamp());
case TimeRole:
return event.originTimestamp();
case ShowReactionsRole:
return false;
case ShowReadMarkersRole:
return false;
case ReplyAuthorRole:
if (const auto &replyPtr = m_room->getReplyForEvent(event)) {
return m_room->getUser(static_cast<NeoChatUser *>(m_room->user(replyPtr->senderId())));
} else {
return m_room->getUser(nullptr);
}
case ReplyRole:
if (role == ReplyRole) {
auto replyPtr = m_room->getReplyForEvent(event);
if (!replyPtr) {
return {};
}
MessageEventModel::DelegateType type;
if (auto e = eventCast<const RoomMessageEvent>(replyPtr)) {
switch (e->msgtype()) {
case MessageEventType::Emote:
type = MessageEventModel::DelegateType::Emote;
break;
case MessageEventType::Notice:
type = MessageEventModel::DelegateType::Notice;
break;
case MessageEventType::Image:
type = MessageEventModel::DelegateType::Image;
break;
case MessageEventType::Audio:
type = MessageEventModel::DelegateType::Audio;
break;
case MessageEventType::Video:
type = MessageEventModel::DelegateType::Video;
break;
default:
if (e->hasFileContent()) {
type = MessageEventModel::DelegateType::File;
break;
}
type = MessageEventModel::DelegateType::Message;
}
} else if (is<const StickerEvent>(*replyPtr)) {
type = MessageEventModel::DelegateType::Sticker;
} else {
type = MessageEventModel::DelegateType::Other;
}
return QVariantMap{
{"display", m_room->eventToString(*replyPtr, Qt::RichText)},
{"type", type},
};
}
case IsPendingRole:
return false;
case ShowLinkPreviewRole:
return false;
case IsReplyRole:
return !event.contentJson()["m.relates_to"].toObject()["m.in_reply_to"].toObject()["event_id"].toString().isEmpty();
case HighlightRole:
return !m_room->isDirectChat() && m_room->isEventHighlighted(&event);
case EventIdRole:
return event.id();
case ReplyIdRole:
return event.contentJson()["m.relates_to"].toObject()["m.in_reply_to"].toObject()["event_id"].toString();
}
return MessageEventModel::DelegateType::Message;
#endif
@@ -142,6 +200,27 @@ QHash<int, QByteArray> SearchModel::roleNames() const
{SectionRole, "section"},
{TimeRole, "time"},
{ShowAuthorRole, "showAuthor"},
{EventIdRole, "eventId"},
{ExcessReadMarkersRole, "excessReadMarkers"},
{HighlightRole, "isHighlighted"},
{ReadMarkersString, "readMarkersString"},
{PlainTextRole, "plainText"},
{VerifiedRole, "verified"},
{ReplyAuthorRole, "replyAuthor"},
{ProgressInfoRole, "progressInfo"},
{IsReplyRole, "isReply"},
{ShowReactionsRole, "showReactions"},
{ReplyRole, "reply"},
{ReactionRole, "reaction"},
{ReplyMediaInfoRole, "replyMediaInfo"},
{ReadMarkersRole, "readMarkers"},
{IsPendingRole, "isPending"},
{ShowReadMarkersRole, "showReadMarkers"},
{ReplyIdRole, "replyId"},
{MimeTypeRole, "mimeType"},
{ShowLinkPreviewRole, "showLinkPreview"},
{LinkPreviewRole, "linkPreview"},
{SourceRole, "source"},
};
}
@@ -152,8 +231,26 @@ NeoChatRoom *SearchModel::room() const
void SearchModel::setRoom(NeoChatRoom *room)
{
if (m_room) {
disconnect(m_room, nullptr, this, nullptr);
}
m_room = room;
Q_EMIT roomChanged();
#ifdef QUOTIENT_07
connect(m_room, &NeoChatRoom::replyLoaded, this, [this](const auto &eventId, const auto &replyId) {
Q_UNUSED(replyId);
const auto &results = m_result->results;
auto it = std::find_if(results.begin(), results.end(), [eventId](const auto &event) {
return event.result->id() == eventId;
});
if (it == results.end()) {
return;
}
auto row = it - results.begin();
Q_EMIT dataChanged(index(row, 0), index(row, 0), {ReplyRole, ReplyMediaInfoRole, ReplyAuthorRole});
});
#endif
}
// TODO deduplicate with messageeventmodel

View File

@@ -50,17 +50,40 @@ public:
/**
* @brief Defines the model roles.
*
* For documentation of the roles, see MessageEventModel.
*
* Some of the roles exist only for compatibility with the MessageEventModel,
* since the same delegates are used.
*/
enum Roles {
DisplayRole = Qt::DisplayRole, /**< The message string. */
DelegateTypeRole, /**< The type of the event. */
ShowAuthorRole, /**< Whether the author should be shown (always true). */
AuthorRole, /**< The author of the event. */
ShowSectionRole, /**< Whether the section header should be shown. */
SectionRole, /**< The date of the event as a string. */
TimeRole, /**< The timestamp for when the event was sent. */
DisplayRole = Qt::DisplayRole,
DelegateTypeRole,
ShowAuthorRole,
AuthorRole,
ShowSectionRole,
SectionRole,
TimeRole,
EventIdRole,
ExcessReadMarkersRole,
HighlightRole,
ReadMarkersString,
PlainTextRole,
VerifiedRole,
ReplyAuthorRole,
ProgressInfoRole,
IsReplyRole,
ShowReactionsRole,
ReplyRole,
ReactionRole,
ReplyMediaInfoRole,
ReadMarkersRole,
IsPendingRole,
ShowReadMarkersRole,
ReplyIdRole,
MimeTypeRole,
ShowLinkPreviewRole,
LinkPreviewRole,
SourceRole,
};
Q_ENUM(Roles);
SearchModel(QObject *parent = nullptr);

View File

@@ -21,7 +21,7 @@ void SortFilterRoomListModel::setRoomSortOrder(SortFilterRoomListModel::RoomSort
m_sortOrder = sortOrder;
Q_EMIT roomSortOrderChanged();
if (sortOrder == SortFilterRoomListModel::Alphabetical) {
setSortRole(RoomListModel::NameRole);
setSortRole(RoomListModel::DisplayNameRole);
} else if (sortOrder == SortFilterRoomListModel::LastActivity) {
setSortRole(RoomListModel::LastActiveTimeRole);
}
@@ -78,7 +78,8 @@ bool SortFilterRoomListModel::filterAcceptsRow(int source_row, const QModelIndex
{
Q_UNUSED(source_parent);
bool acceptRoom = sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::NameRole).toString().contains(m_filterText, Qt::CaseInsensitive)
bool acceptRoom =
sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::DisplayNameRole).toString().contains(m_filterText, Qt::CaseInsensitive)
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::JoinStateRole).toString() != "upgraded"
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsSpaceRole).toBool() == false;

View File

@@ -14,30 +14,45 @@ StickerModel::StickerModel(QObject *parent)
int StickerModel::rowCount(const QModelIndex &index) const
{
Q_UNUSED(index);
return m_images.size();
}
QVariant StickerModel::data(const QModelIndex &index, int role) const
{
const auto &row = index.row();
const auto &image = m_images[row];
if (role == Url) {
if (role == UrlRole) {
#ifdef QUOTIENT_07
return m_room->connection()->makeMediaUrl(image.url);
#endif
}
if (role == Body) {
if (role == BodyRole) {
if (image.body) {
return *image.body;
}
}
if (role == IsStickerRole) {
if (image.usage) {
return image.usage->isEmpty() || image.usage->contains("sticker"_ls);
}
return true;
}
if (role == IsEmojiRole) {
if (image.usage) {
return image.usage->isEmpty() || image.usage->contains("emoticon"_ls);
}
return true;
}
return {};
}
QHash<int, QByteArray> StickerModel::roleNames() const
{
return {
{StickerModel::Url, "url"},
{StickerModel::Body, "body"},
{UrlRole, "url"},
{BodyRole, "body"},
{IsStickerRole, "isSticker"},
{IsEmojiRole, "isEmoji"},
};
}
ImagePacksModel *StickerModel::model() const
@@ -51,14 +66,11 @@ void StickerModel::setModel(ImagePacksModel *model)
disconnect(m_model, nullptr, this, nullptr);
}
connect(model, &ImagePacksModel::roomChanged, this, [this]() {
beginResetModel();
m_images = m_model->images(m_index);
endResetModel();
reloadImages();
});
beginResetModel();
connect(model, &ImagePacksModel::imagesLoaded, this, &StickerModel::reloadImages);
m_model = model;
m_images = m_model->images(m_index);
endResetModel();
reloadImages();
Q_EMIT modelChanged();
}
@@ -68,13 +80,18 @@ int StickerModel::packIndex() const
}
void StickerModel::setPackIndex(int index)
{
beginResetModel();
m_index = index;
Q_EMIT packIndexChanged();
reloadImages();
}
void StickerModel::reloadImages()
{
beginResetModel();
if (m_model) {
m_images = m_model->images(m_index);
}
endResetModel();
Q_EMIT packIndexChanged();
}
NeoChatRoom *StickerModel::room() const
@@ -84,6 +101,9 @@ NeoChatRoom *StickerModel::room() const
void StickerModel::setRoom(NeoChatRoom *room)
{
if (room) {
disconnect(room->connection(), nullptr, this, nullptr);
}
m_room = room;
Q_EMIT roomChanged();
}

View File

@@ -47,8 +47,10 @@ public:
* @brief Defines the model roles.
*/
enum Roles {
Url = Qt::UserRole + 1, /**< The source mxc URL for the image. */
Body, /**< The image caption, if any. */
UrlRole = Qt::UserRole + 1, /**< The source mxc URL for the image. */
BodyRole, /**< The image caption, if any. */
IsStickerRole, /**< Whether this emoticon is a sticker. */
IsEmojiRole, /**< Whether this emoticon is an emoji. */
};
explicit StickerModel(QObject *parent = nullptr);
@@ -98,4 +100,5 @@ private:
int m_index = 0;
QVector<Quotient::ImagePackEventContent::ImagePackImage> m_images;
NeoChatRoom *m_room;
void reloadImages();
};

View File

@@ -11,7 +11,7 @@ bool UserFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceP
if (m_filterText.length() < 1) {
return false;
}
return sourceModel()->data(sourceModel()->index(sourceRow, 0), UserListModel::NameRole).toString().contains(m_filterText, Qt::CaseInsensitive)
return sourceModel()->data(sourceModel()->index(sourceRow, 0), UserListModel::DisplayNameRole).toString().contains(m_filterText, Qt::CaseInsensitive)
|| sourceModel()->data(sourceModel()->index(sourceRow, 0), UserListModel::UserIdRole).toString().contains(m_filterText, Qt::CaseInsensitive);
}

View File

@@ -64,7 +64,7 @@ QVariant UserListModel::data(const QModelIndex &index, int role) const
return {};
}
auto user = m_users.at(index.row());
if (role == NameRole) {
if (role == DisplayNameRole) {
return user->displayname(m_currentRoom);
}
if (role == UserIdRole) {
@@ -204,7 +204,7 @@ QHash<int, QByteArray> UserListModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
roles[DisplayNameRole] = "name";
roles[UserIdRole] = "userId";
roles[AvatarRole] = "avatar";
roles[ObjectRole] = "user";

View File

@@ -38,13 +38,14 @@ public:
* @brief Defines the model roles.
*/
enum EventRoles {
NameRole = Qt::UserRole + 1, /**< The user's display name in the current room. */
DisplayNameRole = Qt::DisplayRole, /**< The user's display name in the current room. */
UserIdRole, /**< Matrix ID of the user. */
AvatarRole, /**< The source URL for the user's avatar in the current room. */
ObjectRole, /**< The QObject for the user. */
PowerLevelRole, /**< The user's power level in the current room. */
PowerLevelStringRole, /**< The name of the user's power level in the current room. */
};
Q_ENUM(EventRoles)
UserListModel(QObject *parent = nullptr);
@@ -61,7 +62,7 @@ public:
*
* @sa QAbstractItemModel::data
*/
[[nodiscard]] QVariant data(const QModelIndex &index, int role = NameRole) const override;
[[nodiscard]] QVariant data(const QModelIndex &index, int role) const override;
/**
* @brief Number of rows in the model.

View File

@@ -13,6 +13,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
@@ -51,6 +52,7 @@ Comment[es]=Un cliente para Matrix, el protocolo de comunicaciones descentraliza
Comment[eu]=Matrix, deszentralizatutako komunikazio protokolorako, bezero bat
Comment[fi]=Hajautetun Matrix-viestintäyhteyskäytännön asiakasohjelma
Comment[fr]=Un client pour « Matrix », le protocole décentralisé de communications.
Comment[gl]=Un cliente para Matrix, o protocolo de comunicación descentralizada
Comment[hu]=Kliens a matrixhoz, a decentralizált kommunikációs protokollhoz
Comment[ia]=Un cliente per Matrix, le protocollo de communication decentralisate
Comment[id]=Sebuah klien untuk matrix, protokol komunikasi terdecentralisasi
@@ -90,6 +92,7 @@ Name[es]=Nuevo mensaje
Name[eu]=Mezu berria
Name[fi]=Uusi viesti
Name[fr]=Nouveau message
Name[gl]=Nova mensaxe
Name[hu]=Új üzenet
Name[ia]=Nove message
Name[id]=Pesan baru
@@ -126,6 +129,7 @@ Comment[es]=Hay un mensaje nuevo
Comment[eu]=Mezu berri bat dago
Comment[fi]=Saapui uusi viesti
Comment[fr]=Il y a un nouveau message
Comment[gl]=Hai unha nova mensaxe
Comment[hu]=Új üzenet érkezett
Comment[ia]=Il ha un nove message
Comment[id]=Ada pesan baru
@@ -166,6 +170,7 @@ Name[es]=Nueva invitación
Name[eu]=Gonbidapen berria
Name[fi]=Uusi kutsu
Name[fr]=Nouvelle invitation
Name[gl]=Novo convite
Name[ia]=Nove invitation
Name[id]=Undangan Baru
Name[ie]=Nov invitation
@@ -197,6 +202,7 @@ Comment[es]=Hay una nueva invitación a una sala
Comment[eu]=Gela baterako gonbidapen berri bat dago
Comment[fi]=Uusi kutsu huoneeseen
Comment[fr]=Il y a une nouvelle invitation dans un salon.
Comment[gl]=Tes un novo convite para unha sala
Comment[ia]=Il ha un nove invitation a un sala
Comment[id]=Ada undangan baru ke sebuah ruangan
Comment[ie]=Vu have un nov invitation a un chambre

View File

@@ -18,10 +18,12 @@
#include <connection.h>
#include <csapi/account-data.h>
#include <csapi/directory.h>
#include <csapi/event_context.h>
#include <csapi/pushrules.h>
#include <csapi/redaction.h>
#include <csapi/report_content.h>
#include <csapi/room_state.h>
#include <csapi/rooms.h>
#include <csapi/typing.h>
#include <events/encryptionevent.h>
#include <events/reactionevent.h>
@@ -32,6 +34,7 @@
#include <events/roompowerlevelsevent.h>
#include <events/simplestateevents.h>
#include <jobs/downloadfilejob.h>
#ifndef QUOTIENT_07
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <joinstate.h>
@@ -52,6 +55,8 @@
#include "filetransferpseudojob.h"
#include "texthandler.h"
#include <KConfig>
#include <KConfigGroup>
#ifndef Q_OS_ANDROID
#include <KIO/Job>
#endif
@@ -64,8 +69,6 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
: Room(connection, std::move(roomId), joinState)
{
connect(connection, &Connection::accountDataChanged, this, &NeoChatRoom::updatePushNotificationState);
connect(this, &NeoChatRoom::notificationCountChanged, this, &NeoChatRoom::countChanged);
connect(this, &NeoChatRoom::highlightCountChanged, this, &NeoChatRoom::countChanged);
connect(this, &Room::fileTransferCompleted, this, [this] {
setFileUploadingProgress(0);
setHasFileUploading(false);
@@ -73,6 +76,22 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
connect(this, &Room::aboutToAddHistoricalMessages, this, &NeoChatRoom::readMarkerLoadedChanged);
// Load cached event if available.
KConfig dataResource("data", KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup eventCacheGroup(&dataResource, "EventCache");
if (eventCacheGroup.hasKey(id())) {
auto eventJson = QJsonDocument::fromJson(eventCacheGroup.readEntry(id(), QByteArray())).object();
if (!eventJson.isEmpty()) {
auto event = loadEvent<RoomEvent>(eventJson);
if (event != nullptr) {
m_cachedEvent = std::move(event);
}
}
}
connect(this, &Room::addedMessages, this, &NeoChatRoom::cacheLastEvent);
connect(this, &Quotient::Room::eventsHistoryJobChanged, this, &NeoChatRoom::lastActiveTimeChanged);
connect(this, &Room::joinStateChanged, this, [this](JoinState oldState, JoinState newState) {
@@ -83,6 +102,8 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
connect(this, &Room::displaynameChanged, this, &NeoChatRoom::displayNameChanged);
connectSingleShot(this, &Room::baseStateLoaded, this, [this]() {
updatePushNotificationState(QStringLiteral("m.push_rules"));
Q_EMIT canEncryptRoomChanged();
if (this->joinState() != JoinState::Invite) {
return;
@@ -300,9 +321,32 @@ const RoomEvent *NeoChatRoom::lastEvent() const
}
#endif
}
if (m_cachedEvent != nullptr) {
return std::to_address(m_cachedEvent);
}
return nullptr;
}
void NeoChatRoom::cacheLastEvent()
{
auto event = lastEvent();
if (event != nullptr) {
KConfig dataResource("data", KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup eventCacheGroup(&dataResource, "EventCache");
auto eventJson = QJsonDocument(event->fullJson()).toJson();
eventCacheGroup.writeEntry(id(), eventJson);
auto uniqueEvent = loadEvent<RoomEvent>(event->fullJson());
if (event != nullptr) {
m_cachedEvent = std::move(uniqueEvent);
}
}
}
bool NeoChatRoom::lastEventIsSpoiler() const
{
if (auto event = lastEvent()) {
@@ -367,17 +411,12 @@ void NeoChatRoom::onRedaction(const RoomEvent &prevEvent, const RoomEvent & /*af
}
}
void NeoChatRoom::countChanged()
{
if (displayed() && !hasUnreadMessages()) {
resetNotificationCount();
resetHighlightCount();
}
}
QDateTime NeoChatRoom::lastActiveTime()
{
if (timelineSize() == 0) {
if (m_cachedEvent != nullptr) {
return m_cachedEvent->originTimestamp();
}
return QDateTime();
}
@@ -413,13 +452,38 @@ QVariantList NeoChatRoom::getUsers(const QString &keyword, int limit) const
return matchedList;
}
// An empty user is useful for returning as a model value to avoid properties being undefined.
static const QVariantMap emptyUser = {
{"isLocalUser", false},
{"id", QString()},
{"displayName", QString()},
{"avatarSource", QUrl()},
{"avatarMediaId", QString()},
{"color", QColor()},
{"object", QVariant()},
};
QVariantMap NeoChatRoom::getUser(const QString &userID) const
{
NeoChatUser user(userID, connection());
return QVariantMap{{QStringLiteral("id"), user.id()},
{QStringLiteral("displayName"), user.displayname(this)},
{QStringLiteral("avatarMediaId"), user.avatarMediaId(this)},
{QStringLiteral("color"), user.color()}};
NeoChatUser *userObject = static_cast<NeoChatUser *>(user(userID));
return getUser(userObject);
}
QVariantMap NeoChatRoom::getUser(NeoChatUser *user) const
{
if (user == nullptr) {
return emptyUser;
}
return QVariantMap{
{QStringLiteral("isLocalUser"), user->id() == localUser()->id()},
{QStringLiteral("id"), user->id()},
{QStringLiteral("displayName"), user->displayname(this)},
{QStringLiteral("avatarSource"), avatarForMember(user)},
{QStringLiteral("avatarMediaId"), user->avatarMediaId(this)},
{QStringLiteral("color"), user->color()},
{QStringLiteral("object"), QVariant::fromValue(user)},
};
}
QString NeoChatRoom::avatarMediaId() const
@@ -1722,12 +1786,12 @@ void NeoChatRoom::setChatBoxEditId(const QString &editId)
Q_EMIT chatBoxEditIdChanged();
}
NeoChatUser *NeoChatRoom::chatBoxReplyUser() const
QVariantMap NeoChatRoom::chatBoxReplyUser() const
{
if (m_chatBoxReplyId.isEmpty()) {
return nullptr;
return emptyUser;
}
return static_cast<NeoChatUser *>(user((*findInTimeline(m_chatBoxReplyId))->senderId()));
return getUser(static_cast<NeoChatUser *>(user((*findInTimeline(m_chatBoxReplyId))->senderId())));
}
QString NeoChatRoom::chatBoxReplyMessage() const
@@ -1738,12 +1802,12 @@ QString NeoChatRoom::chatBoxReplyMessage() const
return eventToString(*static_cast<const RoomMessageEvent *>(&**findInTimeline(m_chatBoxReplyId)));
}
NeoChatUser *NeoChatRoom::chatBoxEditUser() const
QVariantMap NeoChatRoom::chatBoxEditUser() const
{
if (m_chatBoxEditId.isEmpty()) {
return nullptr;
return emptyUser;
}
return static_cast<NeoChatUser *>(user((*findInTimeline(m_chatBoxEditId))->senderId()));
return getUser(static_cast<NeoChatUser *>(user((*findInTimeline(m_chatBoxEditId))->senderId())));
}
QString NeoChatRoom::chatBoxEditMessage() const
@@ -1785,6 +1849,73 @@ void NeoChatRoom::setSavedText(const QString &savedText)
m_savedText = savedText;
}
void NeoChatRoom::replyLastMessage()
{
const auto &timelineBottom = messageEvents().rbegin();
// set a cap limit of startRow + 35 messages, to prevent loading a lot of messages
// in rooms where the user has not sent many messages
const auto limit = timelineBottom + std::min(35, timelineSize());
for (auto it = timelineBottom; it != limit; ++it) {
auto evt = it->event();
auto e = eventCast<const RoomMessageEvent>(evt);
if (!e) {
continue;
}
auto content = (*it)->contentJson();
if (e->msgtype() != MessageEventType::Unknown) {
QString eventId;
if (content.contains("m.new_content")) {
// The message has been edited so we have to return the id of the original message instead of the replacement
eventId = content["m.relates_to"].toObject()["event_id"].toString();
} else {
// For any message that isn't an edit return the id of the current message
eventId = (*it)->id();
}
setChatBoxReplyId(eventId);
return;
}
}
}
void NeoChatRoom::editLastMessage()
{
const auto &timelineBottom = messageEvents().rbegin();
// set a cap limit of 35 messages, to prevent loading a lot of messages
// in rooms where the user has not sent many messages
const auto limit = timelineBottom + std::min(35, timelineSize());
for (auto it = timelineBottom; it != limit; ++it) {
auto evt = it->event();
auto e = eventCast<const RoomMessageEvent>(evt);
if (!e) {
continue;
}
// check if the current message's sender's id is same as the user's id
if ((*it)->senderId() == localUser()->id()) {
auto content = (*it)->contentJson();
if (e->msgtype() != MessageEventType::Unknown) {
QString eventId;
if (content.contains("m.new_content")) {
// The message has been edited so we have to return the id of the original message instead of the replacement
eventId = content["m.relates_to"].toObject()["event_id"].toString();
} else {
// For any message that isn't an edit return the id of the current message
eventId = (*it)->id();
}
setChatBoxEditId(eventId);
return;
}
}
}
}
bool NeoChatRoom::canEncryptRoom() const
{
#ifdef QUOTIENT_07
@@ -1941,3 +2072,32 @@ QUrl NeoChatRoom::avatarForMember(NeoChatUser *user) const
return url;
#endif
}
const RoomEvent *NeoChatRoom::getReplyForEvent(const RoomEvent &event) const
{
const QString &replyEventId = event.contentJson()["m.relates_to"].toObject()["m.in_reply_to"].toObject()["event_id"].toString();
if (replyEventId.isEmpty()) {
return {};
};
const auto replyIt = findInTimeline(replyEventId);
const RoomEvent *replyPtr = replyIt != historyEdge() ? &**replyIt : nullptr;
if (!replyPtr) {
for (const auto &e : m_extraEvents) {
if (e->id() == replyEventId) {
replyPtr = e.get();
break;
}
}
}
return replyPtr;
}
void NeoChatRoom::loadReply(const QString &eventId, const QString &replyId)
{
auto job = connection()->callApi<GetOneRoomEventJob>(id(), replyId);
connect(job, &BaseJob::success, this, [this, job, eventId, replyId] {
m_extraEvents.push_back(fromJson<event_ptr_tt<RoomEvent>>(job->jsonData()));
Q_EMIT replyLoaded(eventId, replyId);
});
}

View File

@@ -3,6 +3,7 @@
#pragma once
#include <qobjectdefs.h>
#include <room.h>
#include <QCache>
@@ -314,11 +315,26 @@ class NeoChatRoom : public Quotient::Room
Q_PROPERTY(QString chatBoxEditId READ chatBoxEditId WRITE setChatBoxEditId NOTIFY chatBoxEditIdChanged)
/**
* @brief Get the user object for the message being replied to.
* @brief Get the user for the message being replied to.
*
* Returns a nullptr if not replying to a message.
* This is different to getting a NeoChatUser object or Quotient::User object
* as neither of those can provide details like the displayName or avatarMediaId
* without the room context as these can vary from room to room.
*
* Returns an empty user if not replying to a message.
*
* The user QVariantMap has the following properties:
* - isLocalUser - Whether the user is the local user.
* - id - The matrix ID of the user.
* - displayName - Display name in the context of this room.
* - avatarSource - The mxc URL for the user's avatar in the current room.
* - avatarMediaId - Avatar id in the context of this room.
* - color - Color for the user.
* - object - The NeoChatUser object for the user.
*
* @sa getUser, Quotient::User, NeoChatUser
*/
Q_PROPERTY(NeoChatUser *chatBoxReplyUser READ chatBoxReplyUser NOTIFY chatBoxReplyIdChanged)
Q_PROPERTY(QVariantMap chatBoxReplyUser READ chatBoxReplyUser NOTIFY chatBoxReplyIdChanged)
/**
* @brief The content of the message being replied to.
@@ -328,11 +344,26 @@ class NeoChatRoom : public Quotient::Room
Q_PROPERTY(QString chatBoxReplyMessage READ chatBoxReplyMessage NOTIFY chatBoxReplyIdChanged)
/**
* @brief Get the user object for the message being edited.
* @brief Get the user for the message being edited.
*
* Returns a nullptr if not editing a message.
* This is different to getting a NeoChatUser object or Quotient::User object
* as neither of those can provide details like the displayName or avatarMediaId
* without the room context as these can vary from room to room.
*
* Returns an empty user if not replying to a message.
*
* The user QVariantMap has the following properties:
* - isLocalUser - Whether the user is the local user.
* - id - The matrix ID of the user.
* - displayName - Display name in the context of this room.
* - avatarSource - The mxc URL for the user's avatar in the current room.
* - avatarMediaId - Avatar id in the context of this room.
* - color - Color for the user.
* - object - The NeoChatUser object for the user.
*
* @sa getUser, Quotient::User, NeoChatUser
*/
Q_PROPERTY(NeoChatUser *chatBoxEditUser READ chatBoxEditUser NOTIFY chatBoxEditIdChanged)
Q_PROPERTY(QVariantMap chatBoxEditUser READ chatBoxEditUser NOTIFY chatBoxEditIdChanged)
/**
* @brief The content of the message being edited.
@@ -389,18 +420,50 @@ public:
* without the room context as these can vary from room to room. This function
* provides the room context and outputs the result as QVariantMap.
*
* Can be called with an empty QString to return an empty user, which is a useful return
* from models to avoid undefined properties.
*
* @param userID the ID of the user to output.
*
* @return a QVariantMap for the user with the following properties:
* - id - User ID.
* - isLocalUser - Whether the user is the local user.
* - id - The matrix ID of the user.
* - displayName - Display name in the context of this room.
* - avatarSource - The mxc URL for the user's avatar in the current room.
* - avatarMediaId - Avatar id in the context of this room.
* - color - Color for the user.
* - object - The NeoChatUser object for the user.
*
* @sa Quotient::User, NeoChatUser
*/
Q_INVOKABLE [[nodiscard]] QVariantMap getUser(const QString &userID) const;
/**
* @brief Get a user in the context of this room.
*
* This is different to getting a NeoChatUser object or Quotient::User object
* as neither of those can provide details like the displayName or avatarMediaId
* without the room context as these can vary from room to room. This function
* provides the room context and outputs the result as QVariantMap.
*
* Can be called with a nullptr to return an empty user, which is a useful return
* from models to avoid undefined properties.
*
* @param user the user to output.
*
* @return a QVariantMap for the user with the following properties:
* - isLocalUser - Whether the user is the local user.
* - id - The matrix ID of the user.
* - displayName - Display name in the context of this room.
* - avatarSource - The mxc URL for the user's avatar in the current room.
* - avatarMediaId - Avatar id in the context of this room.
* - color - Color for the user.
* - object - The NeoChatUser object for the user.
*
* @sa Quotient::User, NeoChatUser
*/
Q_INVOKABLE [[nodiscard]] QVariantMap getUser(NeoChatUser *user) const;
[[nodiscard]] QVariantList getUsersTyping() const;
[[nodiscard]] QDateTime lastActiveTime();
@@ -703,13 +766,13 @@ public:
QString chatBoxReplyId() const;
void setChatBoxReplyId(const QString &replyId);
NeoChatUser *chatBoxReplyUser() const;
QVariantMap chatBoxReplyUser() const;
QString chatBoxReplyMessage() const;
QString chatBoxEditId() const;
void setChatBoxEditId(const QString &editId);
NeoChatUser *chatBoxEditUser() const;
QVariantMap chatBoxEditUser() const;
QString chatBoxEditMessage() const;
QString chatBoxAttachmentPath() const;
@@ -735,6 +798,20 @@ public:
*/
void setSavedText(const QString &savedText);
/**
* @brief Reply to the last message sent in the timeline.
*
* @note This checks a maximum of the previous 35 message for performance reasons.
*/
Q_INVOKABLE void replyLastMessage();
/**
* @brief Edit the last message sent by the local user.
*
* @note This checks a maximum of the previous 35 message for performance reasons.
*/
Q_INVOKABLE void editLastMessage();
#ifdef QUOTIENT_07
/**
* @brief Get a PollHandler object for the given event Id.
@@ -756,6 +833,18 @@ public:
Q_INVOKABLE [[nodiscard]] QUrl avatarForMember(NeoChatUser *user) const;
/**
* @brief Returns the event that is being replied to. This includes events that were manually loaded using NeoChatRoom::loadReply.
*/
const Quotient::RoomEvent *getReplyForEvent(const Quotient::RoomEvent &event) const;
/**
* Loads the event replyId with the given id from the server and saves it locally.
* For models to update correctly, eventId must be the event that is replying to replyId.
* Intended to load the replied-to event when it isn't available locally.
*/
Q_INVOKABLE void loadReply(const QString &eventId, const QString &replyId);
private:
QSet<const Quotient::RoomEvent *> highlights;
@@ -774,6 +863,8 @@ private:
QCoro::Task<void> doDeleteMessagesByUser(const QString &user, QString reason);
QCoro::Task<void> doUploadFile(QUrl url, QString body = QString());
std::unique_ptr<Quotient::RoomEvent> m_cachedEvent;
QString m_chatBoxText;
QString m_editText;
QString m_chatBoxReplyId;
@@ -785,11 +876,13 @@ private:
#ifdef QUOTIENT_07
QCache<QString, PollHandler> m_polls;
#endif
std::vector<Quotient::event_ptr_tt<Quotient::RoomEvent>> m_extraEvents;
private Q_SLOTS:
void countChanged();
void updatePushNotificationState(QString type);
void cacheLastEvent();
Q_SIGNALS:
void cachedInputChanged();
void busyChanged();
@@ -832,6 +925,7 @@ Q_SIGNALS:
void serverAclPowerLevelChanged();
void spaceChildPowerLevelChanged();
void spaceParentPowerLevelChanged();
void replyLoaded(const QString &eventId, const QString &replyId);
public Q_SLOTS:
/**

View File

@@ -5,7 +5,7 @@
#include <memory>
#include <QJsonArray>
#include <QGuiApplication>
#include <KLocalizedString>
#include <KNotification>
@@ -18,6 +18,7 @@
#endif
#include <connection.h>
#include <csapi/notifications.h>
#include <csapi/pushrules.h>
#include <jobs/basejob.h>
#include <user.h>
@@ -48,6 +49,148 @@ NotificationsManager::NotificationsManager(QObject *parent)
});
}
#ifdef QUOTIENT_07
void NotificationsManager::handleNotifications(QPointer<Connection> connection)
{
if (!m_connActiveJob.contains(connection->user()->id())) {
auto job = connection->callApi<GetNotificationsJob>();
m_connActiveJob.append(connection->user()->id());
connect(job, &BaseJob::success, this, [this, job, connection]() {
m_connActiveJob.removeAll(connection->user()->id());
processNotificationJob(connection, job, !m_oldNotifications.contains(connection->user()->id()));
});
}
}
#endif
void NotificationsManager::processNotificationJob(QPointer<Quotient::Connection> connection, Quotient::GetNotificationsJob *job, bool initialization)
{
if (job == nullptr) {
return;
}
if (connection == nullptr) {
qWarning() << QStringLiteral("No connection for GetNotificationsJob %1").arg(job->objectName());
return;
}
const auto connectionId = connection->user()->id();
// If pagination has occurred set off the next job
auto nextToken = job->jsonData()["next_token"].toString();
if (!nextToken.isEmpty()) {
auto nextJob = connection->callApi<GetNotificationsJob>(nextToken);
m_connActiveJob.append(connectionId);
connect(nextJob, &BaseJob::success, this, [this, nextJob, connection, initialization]() {
m_connActiveJob.removeAll(connection->user()->id());
processNotificationJob(connection, nextJob, initialization);
});
}
const auto notifications = job->jsonData()["notifications"].toArray();
if (initialization) {
m_oldNotifications[connectionId] = QStringList();
for (const auto &n : notifications) {
if (!m_initialTimestamp.contains(connectionId)) {
m_initialTimestamp[connectionId] = n.toObject()["ts"].toDouble();
} else {
qint64 timestamp = n.toObject()["ts"].toDouble();
if (timestamp > m_initialTimestamp[connectionId]) {
m_initialTimestamp[connectionId] = timestamp;
}
}
auto connectionNotifications = m_oldNotifications.value(connectionId);
connectionNotifications += n.toObject()["event"].toObject()["event_id"].toString();
m_oldNotifications[connectionId] = connectionNotifications;
}
return;
}
for (const auto &n : notifications) {
const auto notification = n.toObject();
if (notification["read"].toBool()) {
continue;
}
auto connectionNotifications = m_oldNotifications.value(connectionId);
if (connectionNotifications.contains(notification["event"].toObject()["event_id"].toString())) {
continue;
}
connectionNotifications += notification["event"].toObject()["event_id"].toString();
m_oldNotifications[connectionId] = connectionNotifications;
auto room = connection->room(notification["room_id"].toString());
if (shouldPostNotification(connection, n)) {
// 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);
}
postNotification(dynamic_cast<NeoChatRoom *>(room),
sender->displayname(room),
body,
avatar_image,
notification["event"].toObject()["event_id"].toString(),
true);
}
}
}
bool NotificationsManager::shouldPostNotification(QPointer<Quotient::Connection> connection, const QJsonValue &notification)
{
if (connection == nullptr) {
return false;
}
auto room = connection->room(notification["room_id"].toString());
if (room == nullptr) {
return false;
}
// If the room is the current room and the application is active the notification
// should not be shown.
// This is setup so that if the application is inactive the notification will
// always be posted, even if the room is the current room.
bool isCurrentRoom = RoomManager::instance().currentRoom() && room->id() == RoomManager::instance().currentRoom()->id();
if (isCurrentRoom && QGuiApplication::applicationState() == Qt::ApplicationActive) {
return false;
}
// If the notification timestamp is earlier than the initial timestamp assume
// the notification is old and shouldn't be posted.
qint64 timestamp = notification["ts"].toDouble();
if (timestamp < m_initialTimestamp[connection->user()->id()]) {
return false;
}
return true;
}
void NotificationsManager::postNotification(NeoChatRoom *room,
const QString &sender,
const QString &text,
@@ -55,21 +198,30 @@ void NotificationsManager::postNotification(NeoChatRoom *room,
const QString &replyEventId,
bool canReply)
{
QPixmap img;
img.convertFromImage(icon);
KNotification *notification = new KNotification("message");
if (sender == room->displayName()) {
notification->setTitle(sender);
} else {
notification->setTitle(i18n("%1 (%2)", sender, room->displayName()));
const QString roomId = room->id();
KNotification *notification = m_notifications.value(roomId);
if (!notification) {
notification = new KNotification("message");
m_notifications.insert(roomId, notification);
connect(notification, &KNotification::closed, this, [this, roomId] {
m_notifications.remove(roomId);
});
}
notification->setText(text.toHtmlEscaped());
notification->setPixmap(img);
QString entry;
if (sender == room->displayName()) {
notification->setTitle(sender);
entry = text.toHtmlEscaped();
} else {
notification->setTitle(room->displayName());
entry = i18n("%1: %2", sender, text.toHtmlEscaped());
}
notification->setText(notification->text() + '\n' + entry);
notification->setPixmap(QPixmap::fromImage(icon));
notification->setDefaultAction(i18n("Open NeoChat in this room"));
connect(notification, &KNotification::defaultActivated, this, [=]() {
connect(notification, &KNotification::defaultActivated, this, [notification, room]() {
WindowController::instance().showAndRaiseWindow(notification->xdgActivationToken());
if (!room) {
return;
@@ -96,10 +248,7 @@ void NotificationsManager::postNotification(NeoChatRoom *room,
}
notification->setHint(QStringLiteral("x-kde-origin-name"), room->localUser()->id());
notification->sendEvent();
m_notifications.insert(room->id(), notification);
}
void NotificationsManager::postInviteNotification(NeoChatRoom *room, const QString &title, const QString &sender, const QImage &icon)
@@ -112,7 +261,7 @@ void NotificationsManager::postInviteNotification(NeoChatRoom *room, const QStri
notification->setPixmap(img);
notification->setFlags(KNotification::Persistent);
notification->setDefaultAction(i18n("Open this invitation in NeoChat"));
connect(notification, &KNotification::defaultActivated, this, [=]() {
connect(notification, &KNotification::defaultActivated, this, [notification, room]() {
WindowController::instance().showAndRaiseWindow(notification->xdgActivationToken());
notification->close();
RoomManager::instance().enterRoom(room);

View File

@@ -4,11 +4,18 @@
#pragma once
#include <QImage>
#include <QJsonObject>
#include <QMap>
#include <QObject>
#include <QPointer>
#include <QString>
#include <QJsonObject>
#include <csapi/notifications.h>
#include <jobs/basejob.h>
namespace Quotient
{
class Connection;
}
class KNotification;
class NeoChatRoom;
@@ -181,10 +188,24 @@ public:
*/
QVector<QVariant> getKeywordNotificationActions();
#ifdef QUOTIENT_07
/**
* @brief Handle the notifications for the given connection.
*/
void handleNotifications(QPointer<Quotient::Connection> connection);
#endif
private:
NotificationsManager(QObject *parent = nullptr);
QMultiMap<QString, KNotification *> m_notifications;
QHash<QString, qint64> m_initialTimestamp;
QHash<QString, QStringList> m_oldNotifications;
QStringList m_connActiveJob;
bool shouldPostNotification(QPointer<Quotient::Connection> connection, const QJsonValue &notification);
QHash<QString, KNotification *> m_notifications;
QHash<QString, QPointer<KNotification>> m_invitations;
bool m_globalNotificationsEnabled = false;
@@ -218,6 +239,8 @@ private:
QVector<QVariant> toActions(PushNotificationAction::Action action, const QString &sound = "default");
private Q_SLOTS:
void processNotificationJob(QPointer<Quotient::Connection> connection, Quotient::GetNotificationsJob *job, bool initialization);
void updateNotificationRules(const QString &type);
Q_SIGNALS:

View File

@@ -14,6 +14,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
@@ -50,6 +51,7 @@ Comment[es]=Buscar salas en NeoChat
Comment[eu]=Bilatu gelak NeoChat-en
Comment[fi]=Etsi huoneita NeoChatissä
Comment[fr]=Trouver des salons dans NeoChat
Comment[gl]=Atopa salas en NeoChat
Comment[ia]=Trova salas in NeoChat
Comment[id]=Cari ruangan di NeoChat
Comment[ie]=Trovar chambres in NeoChat

View File

@@ -10,16 +10,47 @@ import QtQuick.Window 2.15
import org.kde.kirigami 2.18 as Kirigami
import org.kde.neochat 1.0
/**
* @brief The component which handles the message sending.
*
* The ChatBox deals with laying out the visual elements with the ChatBar handling
* the core functionality of displaying the current message composition before sending.
*
* This includes support for the following message types:
* - text
* - media (video, image, file)
* - emojis/stickers
* - location
*
* In addition, when replying, this component supports showing the message that is being
* replied to.
*
* @note There is no edit functionality here this, is handled inline by the timeline
* text delegate.
*
* @sa ChatBox
*/
QQC2.Control {
id: root
/**
* @brief The current room that user is viewing.
*/
property NeoChatRoom currentRoom
/**
* @brief The QQC2.TextArea object.
*
* @sa QQC2.TextArea
*/
property alias textField: textField
property bool isReplying: currentRoom.chatBoxReplyId.length > 0
property NeoChatUser replyUser: currentRoom.chatBoxReplyUser
property bool attachmentPaneVisible: currentRoom.chatBoxAttachmentPath.length > 0
signal messageSent()
/**
* @brief The list of actions in the ChatBar.
*
* Each of these will be visualised in the ChatBar so new actions can be added
* by appending to this list.
*/
property list<Kirigami.Action> actions : [
Kirigami.Action {
id: attachmentAction
@@ -96,6 +127,11 @@ QQC2.Control {
}
]
/**
* @brief A message has been sent from the chat bar.
*/
signal messageSent()
leftPadding: 0
rightPadding: 0
topPadding: 0
@@ -120,7 +156,7 @@ QQC2.Control {
QQC2.TextArea {
id: textField
x: Math.round((root.width - chatBoxMaxWidth) / 2) - (root.width > chatBoxMaxWidth ? Kirigami.Units.largeSpacing * 1.5 : 0)
x: Math.round((root.width - chatBarSizeHelper.currentWidth) / 2) - (root.width > chatBarSizeHelper.currentWidth + Kirigami.Units.largeSpacing * 2.5 ? Kirigami.Units.largeSpacing * 1.5 : 0)
topPadding: Kirigami.Units.largeSpacing + (paneLoader.visible ? paneLoader.height : 0)
bottomPadding: Kirigami.Units.largeSpacing
leftPadding: LayoutMirroring.enabled ? actionsRow.width : Kirigami.Units.largeSpacing
@@ -159,7 +195,7 @@ QQC2.Control {
x: textField.cursorRectangle.x
y: textField.cursorRectangle.y - height
onFormattingSelected: chatBar.formatText(format, selectionStart, selectionEnd)
onFormattingSelected: root.formatText(format, selectionStart, selectionEnd)
}
Keys.onDeletePressed: {
@@ -182,7 +218,7 @@ QQC2.Control {
} else if (event.modifiers & Qt.ShiftModifier || Kirigami.Settings.isMobile) {
textField.insert(cursorPosition, "\n")
} else {
chatBar.postMessage();
root.postMessage();
}
}
Keys.onReturnPressed: {
@@ -191,7 +227,7 @@ QQC2.Control {
} else if (event.modifiers & Qt.ShiftModifier || Kirigami.Settings.isMobile) {
textField.insert(cursorPosition, "\n")
} else {
chatBar.postMessage();
root.postMessage();
}
}
Keys.onTabPressed: {
@@ -201,17 +237,11 @@ QQC2.Control {
}
Keys.onPressed: {
if (event.key === Qt.Key_V && event.modifiers & Qt.ControlModifier) {
chatBar.pasteImage();
root.pasteImage();
} else if (event.key === Qt.Key_Up && event.modifiers & Qt.ControlModifier) {
let replyEvent = messageEventModel.getLatestMessageFromRow(0)
if (replyEvent && replyEvent["event_id"]) {
currentRoom.chatBoxReplyId = replyEvent["event_id"]
}
currentRoom.replyLastMessage();
} else if (event.key === Qt.Key_Up && textField.text.length === 0) {
let editEvent = messageEventModel.getLastLocalUserMessageEventId()
if (editEvent) {
currentRoom.chatBoxEditId = editEvent["event_id"]
}
currentRoom.editLastMessage();
} else if (event.key === Qt.Key_Up && completionMenu.visible) {
completionMenu.decrementIndex()
} else if (event.key === Qt.Key_Down && completionMenu.visible) {
@@ -239,20 +269,20 @@ QQC2.Control {
anchors.top: parent.top
anchors.left: parent.left
anchors.leftMargin: root.width > chatBoxMaxWidth ? 0 : Kirigami.Units.largeSpacing
anchors.leftMargin: Kirigami.Units.largeSpacing
anchors.right: parent.right
anchors.rightMargin: root.width > chatBoxMaxWidth ? 0 : (chatBarScrollView.QQC2.ScrollBar.vertical.visible ? Kirigami.Units.largeSpacing * 3.5 : Kirigami.Units.largeSpacing)
anchors.rightMargin: root.width > chatBarSizeHelper.currentWidth ? 0 : (chatBarScrollView.QQC2.ScrollBar.vertical.visible ? Kirigami.Units.largeSpacing * 3.5 : Kirigami.Units.largeSpacing)
active: visible
visible: root.isReplying || root.attachmentPaneVisible
sourceComponent: root.isReplying ? replyPane : attachmentPane
visible: root.currentRoom.chatBoxReplyId.length > 0 || root.currentRoom.chatBoxAttachmentPath.length > 0
sourceComponent: root.currentRoom.chatBoxReplyId.length > 0 ? replyPane : attachmentPane
}
Component {
id: replyPane
ReplyPane {
userName: root.replyUser ? root.replyUser.displayName : ""
userColor: root.replyUser ? root.replyUser.color : ""
userAvatar: root.replyUser ? "image://mxc/" + currentRoom.getUser(root.replyUser.id).avatarMediaId : ""
userName: currentRoom.chatBoxReplyUser.displayName
userColor: currentRoom.chatBoxReplyUser.color
userAvatar: currentRoom.chatBoxReplyUser.avatarSource
text: currentRoom.chatBoxReplyMessage
}
}
@@ -306,9 +336,9 @@ QQC2.Control {
id: cancelButton
anchors.top: parent.top
anchors.right: parent.right
anchors.rightMargin: (root.width - chatBoxMaxWidth) / 2 + Kirigami.Units.largeSpacing + (chatBarScrollView.QQC2.ScrollBar.vertical.visible && !(root.width > chatBoxMaxWidth) ? Kirigami.Units.largeSpacing * 2.5 : 0)
anchors.rightMargin: (root.width - chatBarSizeHelper.currentWidth) / 2 + Kirigami.Units.largeSpacing + (chatBarScrollView.QQC2.ScrollBar.vertical.visible && !(root.width > chatBarSizeHelper.currentWidth) ? Kirigami.Units.largeSpacing * 2.5 : 0)
visible: root.isReplying
visible: root.currentRoom.chatBoxReplyId.length > 0
display: QQC2.AbstractButton.IconOnly
action: Kirigami.Action {
text: i18nc("@action:button", "Cancel reply")
@@ -327,7 +357,7 @@ QQC2.Control {
padding: Kirigami.Units.smallSpacing
spacing: Kirigami.Units.smallSpacing
anchors.right: parent.right
property var requiredMargin: (root.width - chatBoxMaxWidth) / 2 + Kirigami.Units.largeSpacing + (chatBarScrollView.QQC2.ScrollBar.vertical.visible && !(root.width > chatBoxMaxWidth) ? Kirigami.Units.largeSpacing * 2.5 : 0)
property var requiredMargin: (root.width - chatBarSizeHelper.currentWidth) / 2 + Kirigami.Units.largeSpacing + (chatBarScrollView.QQC2.ScrollBar.vertical.visible && !(root.width > chatBarSizeHelper.currentWidth) ? Kirigami.Units.largeSpacing * 2.5 : 0)
anchors.leftMargin: layoutDirection === Qt.RightToLeft ? requiredMargin : 0
anchors.rightMargin: layoutDirection === Qt.RightToLeft ? 0 : requiredMargin
anchors.bottom: parent.bottom
@@ -407,6 +437,17 @@ QQC2.Control {
}
}
DelegateSizeHelper {
id: chatBarSizeHelper
startBreakpoint: Kirigami.Units.gridUnit * 46
endBreakpoint: Kirigami.Units.gridUnit * 66
startPercentWidth: 100
endPercentWidth: Config.compactLayout ? 100 : 85
maxWidth: Config.compactLayout ? -1 : Kirigami.Units.gridUnit * 60
parentWidth: root.width
}
function forceActiveFocus() {
textField.forceActiveFocus();
// set the cursor to the end of the text

View File

@@ -9,15 +9,47 @@ import QtQuick.Layouts 1.15
import org.kde.kirigami 2.15 as Kirigami
import org.kde.neochat 1.0
/**
* @brief A component for typing and sending chat messages.
*
* This is designed to go to the bottom of the timeline and provides all the functionality
* required for the user to send messages to the room.
*
* This includes support for the following message types:
* - text
* - media (video, image, file)
* - emojis/stickers
* - location
*
* In addition when replying this component supports showing the message that is being
* replied to.
*
* @note The main role of this component is to layout the elements. The main functionality
* is handled by ChatBar
*
* @sa ChatBar
*/
ColumnLayout {
id: chatBox
/**
* @brief The current room that user is viewing.
*/
property NeoChatRoom currentRoom
/**
* @brief A message has been sent from the chat bar.
*/
signal messageSent()
property alias chatBar: chatBar
readonly property int extraWidth: width >= Kirigami.Units.gridUnit * 47 ? Math.min((width - Kirigami.Units.gridUnit * 47), Kirigami.Units.gridUnit * 20) : 0
readonly property int chatBoxMaxWidth: Config.compactLayout ? width : Math.min(width, Kirigami.Units.gridUnit * 39 + extraWidth)
/**
* @brief Insert the given text into the ChatBar.
*
* The text is inserted at the current cursor location.
*/
function insertText(text) {
chatBar.insertText(text)
}
spacing: 0
@@ -47,6 +79,8 @@ ColumnLayout {
// lineSpacing is height+leading, so subtract leading once since leading only exists between lines.
Layout.maximumHeight: chatBarFontMetrics.lineSpacing * 8 - chatBarFontMetrics.leading + textField.topPadding + textField.bottomPadding
currentRoom: root.currentRoom
FontMetrics {
id: chatBarFontMetrics
font: chatBar.textField.font
@@ -56,4 +90,6 @@ ColumnLayout {
chatBox.messageSent();
}
}
onActiveFocusChanged: chatBar.forceActiveFocus()
}

View File

@@ -11,10 +11,12 @@ import org.kde.kirigamiaddons.labs.components 1.0 as Components
import org.kde.kirigami 2.15 as Kirigami
import org.kde.neochat 1.0
Components.AbstractMaximizeComponent {
id: root
required property var room
required property NeoChatRoom room
property var location
title: i18n("Choose a Location")

View File

@@ -18,7 +18,7 @@ ColumnLayout {
spacing: 0
MobileForm.FormComboBoxDelegate {
text: i18n("Room")
textRole: "name"
textRole: "displayName"
valueRole: "id"
model: RoomListModel {
id: roomListModel

View File

@@ -80,7 +80,7 @@ QQC2.ScrollView {
Kirigami.PlaceholderMessage {
anchors.centerIn: parent
text: i18n("No emojis")
text: emojiGrid.stickers ? i18n("No stickers") : i18n("No emojis")
visible: emojis.count === 0
}
}

View File

@@ -4,7 +4,7 @@
import QtQuick 2.15
import QtQuick.Controls 2.15 as QQC2
import QtQuick.Layouts 1.15
import org.kde.kirigami 2.15 as Kirigami
import org.kde.kirigami 2.20 as Kirigami
import org.kde.neochat 1.0
ColumnLayout {
@@ -34,33 +34,27 @@ ColumnLayout {
spacing: 0
RowLayout {
Kirigami.NavigationTabBar {
id: types
Layout.fillWidth: true
Layout.preferredHeight: root.categoryIconSize
Kirigami.Theme.colorSet: Kirigami.Theme.View
Item {
Layout.preferredHeight: 1
Layout.fillWidth: true
}
CategoryIcon {
id: emojis
source: "smiley"
text: i18n("Emojis")
t: 0
}
CategoryIcon {
id: stickers
source: "stickers"
text: i18n("Stickers")
t: 1
}
Item {
Layout.preferredHeight: 1
Layout.fillWidth: true
}
background: null
actions: [
Kirigami.Action {
id: emojis
icon.name: "smiley"
text: i18n("Emojis")
checked: true
onTriggered: root.selectedType = 0
},
Kirigami.Action {
id: stickers
icon.name: "stickers"
text: i18n("Stickers")
onTriggered: root.selectedType = 1
}
]
}
QQC2.ScrollView {
@@ -113,7 +107,7 @@ ColumnLayout {
EmojiGrid {
id: emojiGrid
targetIconSize: root.currentCategory === EmojiModel.Custom ? Kirigami.Units.gridUnit * 3 : root.categoryIconSize // Custom emojis are bigger
model: root.selectedType === 1 ? stickerModel : searchField.text.length === 0 ? EmojiModel.emojis(root.currentCategory) : (root.includeCustom ? EmojiModel.filterModel(searchField.text, false) : EmojiModel.filterModelNoCustom(searchField.text, false))
model: root.selectedType === 1 ? emoticonFilterModel : searchField.text.length === 0 ? EmojiModel.emojis(root.currentCategory) : (root.includeCustom ? EmojiModel.filterModel(searchField.text, false) : EmojiModel.filterModelNoCustom(searchField.text, false))
Layout.fillWidth: true
Layout.fillHeight: true
withCustom: root.includeCustom
@@ -121,7 +115,7 @@ ColumnLayout {
header: categories
Keys.forwardTo: searchField
stickers: root.selectedType === 1
onStickerChosen: stickerModel.postSticker(index)
onStickerChosen: stickerModel.postSticker(emoticonFilterModel.mapToSource(emoticonFilterModel.index(index, 0)).row)
}
Kirigami.Separator {
@@ -169,14 +163,22 @@ ColumnLayout {
room: currentRoom
}
EmoticonFilterModel {
id: emoticonFilterModel
sourceModel: stickerModel
showStickers: true
}
Component {
id: emojiDelegate
EmojiDelegate {
Kirigami.NavigationTabButton {
width: root.categoryIconSize
height: width
checked: categories.currentIndex === model.index
emoji: modelData ? modelData.emoji : ""
name: modelData ? modelData.name : ""
text: modelData ? modelData.emoji : ""
QQC2.ToolTip.text: modelData ? modelData.name : ""
QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay
QQC2.ToolTip.visible: hovered
onClicked: {
categories.currentIndex = index;
categories.focus = true;
@@ -186,54 +188,17 @@ ColumnLayout {
Component {
id: stickerDelegate
EmojiDelegate {
Kirigami.NavigationTabButton {
width: root.categoryIconSize
height: width
emoji: model.avatarUrl ?? ""
isImage: true
name: model.displayName ?? ""
onClicked: stickerModel.packIndex = model.index
checked: stickerModel.packIndex === model.index
}
}
component CategoryIcon : Kirigami.Icon {
id: categoryIcons
readonly property bool checked: root.selectedType === t
required property int t
required property string text
Layout.preferredWidth: root.categoryIconSize
Layout.preferredHeight: root.categoryIconSize
QQC2.ToolTip.text: text
QQC2.ToolTip.visible: categoryIconsMouseArea.containsMouse
QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay
MouseArea {
id: categoryIconsMouseArea
hoverEnabled: true
anchors.fill: parent
onClicked: root.selectedType = t
}
Rectangle {
color: categoryIcons.checked ? Kirigami.Theme.highlightColor : "transparent"
radius: Kirigami.Units.smallSpacing
z: -1
anchors {
fill: parent
margins: Kirigami.Units.smallSpacing
}
Rectangle {
radius: Kirigami.Units.smallSpacing
anchors.fill: parent
color: Kirigami.Theme.highlightColor
opacity: categoryIconsMouseArea.containsMouse && !categoryIconsMouseArea.pressed ? 0.2 : 0
contentItem: Image {
source: model.avatarUrl
}
QQC2.ToolTip.text: model.name
QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay
QQC2.ToolTip.visible: hovered && !!model.name
onClicked: stickerModel.packIndex = model.index
}
}
}

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