Compare commits

..

148 Commits

Author SHA1 Message Date
Carl Schwan
8177c1f1bc Port About page to FormCard 2023-08-22 22:03:35 +00:00
Carl Schwan
80171748d8 Port more MobileForm to FormCard
- DevTools
- Network settings
- Push notification
- Permissions
2023-08-22 22:03:35 +00:00
Carl Schwan
6aa2e586de Port to form card 2023-08-22 22:03:35 +00:00
Carl Schwan
9f3012061d ReactionDelegate: Don't bind twice the reaction repeater model
We already are using an alias for this
2023-08-22 21:49:30 +00:00
Tobias Leupold
c1604a9c4f Trayicon tweaks
This fixes two minor inconveniences:

- When closing the chat window and re-showing it from the systray icon, the geometry was not properly restored. The window was always shown in the middle of the screen. Now, one gets the window back with it's actual last position and size.
- It is now possible to not only show the window from the systray icon, but also to close it. This is the way other chat programs do it (Kopete back in the day, Konversation, Quassel IRC etc.)
2023-08-22 20:58:04 +00:00
l10n daemon script
3c7fcee244 GIT_SILENT Sync po/docbooks with svn 2023-08-22 01:47:22 +00:00
Tobias Fella
d33a50a00d Fix json for replies 2023-08-21 19:10:15 +02:00
Tobias Fella
ed033a1c5e Raise compiler settings level to 5.105 2023-08-21 13:02:14 +02:00
l10n daemon script
2b961703ae GIT_SILENT Sync po/docbooks with svn 2023-08-21 01:46:37 +00:00
l10n daemon script
0539665779 GIT_SILENT made messages (after extraction) 2023-08-21 00:46:26 +00:00
James Graham
df127b88e6 Fix Image Replies
Make sure that the image container has it's implicit width/height set so that the correct size can always be calculated. This was breaking images that were a reply to another message (not sure if that's legal because we don't allow but other clients do because I found one).
2023-08-20 18:16:51 +00:00
Joshua Goins
27c4b57f0f Fix link to 'made for matrix' bade 2023-08-20 11:30:05 -04:00
Joshua Goins
f875a23e83 Only close the settings window if there's no accounts left 2023-08-20 15:08:57 +00:00
Joshua Goins
7f5cfbf21c Move the sign out button outside the editor, and close the dialog 2023-08-20 15:08:57 +00:00
Joshua Goins
f7c7643c1c Emit the accepted signal in the logout confirmation dialog 2023-08-20 15:08:57 +00:00
Joshua Goins
692edf52f1 Allow customizing the connection for the logout confirm dialog 2023-08-20 15:08:57 +00:00
Joshua Goins
e48cfaa41f Check if the room is valid before trying to refresh users 2023-08-20 15:08:57 +00:00
Joshua Goins
ba116460d5 Check if there's an active connection before updating notification rules 2023-08-20 15:08:57 +00:00
Joshua Goins
c71672dab3 Remove used logout dialog in main.qml 2023-08-20 15:08:57 +00:00
l10n daemon script
932ef72311 GIT_SILENT Sync po/docbooks with svn 2023-08-20 01:46:49 +00:00
l10n daemon script
7e53a2234f GIT_SILENT made messages (after extraction) 2023-08-20 00:46:36 +00:00
Joshua Goins
a0499e5140 Set sourceSize in for images, improving memory usage and smoothing
In some cases (where we don't get a thumbnail) we load the entire image,
which might be large. Even when we get a thumbnail, the smoothing we
apply doesn't get the best results and the only other option is
mipmapping which is more memory intensive - it stores progressively
smaller images but keeps all of them in memory.

Now the ImageDelegate sets the sourceSize, which helps reduce the memory
footprint (since Qt will throw away whatever parts of the image we don't
need) and makes the images look smoother when scaled. However,
AnimatedImages do not support this so this change introduces a new
property to tell if the image could possibly be animated. It will
erroneously pick up formats that could support animation (e.g. WebP) but
other image formats will still benefit so it's a net positive. The
ImageDelegate will load the correct image component depending on this
property.
2023-08-19 18:20:49 +00:00
Joshua Goins
093ef0a18c Use mxc urls for completion room avatars 2023-08-19 11:49:03 -04:00
Joshua Goins
36bf862ab9 Change the completion proxy model to filter out invalid entries
When auto-completing rooms, there may be some that do not have
canonical addresses (e.g. 1-to-1 chats). These can't be linked anyway,
so skip them and any other unlinkable entries.
2023-08-19 15:45:51 +00:00
Joshua Goins
6d8c1d0780 Fix avatar URLs for rooms
Room avatar URLs don't specify the new mxc:// format the user avatars
use, so we need to carve out a workaround for them.
2023-08-19 15:45:51 +00:00
Joshua Goins
7fe85066a4 Move attachment dialog to ChatBar, where it can actually be used
ChatBar calls to an attachDialog that never comes, so let's have them
move in together.
2023-08-19 15:23:04 +00:00
Tobias Fella
1fefa228e6 Don't check isJobPending in explore page 2023-08-19 14:08:45 +00:00
Joshua Goins
4104e10d95 Add another message when no rooms are found 2023-08-19 14:08:45 +00:00
Joshua Goins
05f3c3ee0a Make the explore page header way prettier, like it is in KCMs 2023-08-19 14:08:45 +00:00
Joshua Goins
0a1c489401 Make the explore page search loading process more obvious
Adds progress bars, lots of them! Now it's easier to tell if NeoChat is
trying it's best to load the public room list.
2023-08-19 14:08:45 +00:00
l10n daemon script
e53d63ad8b GIT_SILENT Sync po/docbooks with svn 2023-08-18 01:44:42 +00:00
l10n daemon script
78541b32f0 GIT_SILENT Sync po/docbooks with svn 2023-08-17 01:46:48 +00:00
Carl Schwan
3bd93996c0 Don't inherit color in TimelineContainer 2023-08-16 23:44:22 +02:00
Heiko Becker
61968aa475 GIT_SILENT Update Appstream for new release
(cherry picked from commit 91b5573016)
2023-08-16 23:33:49 +02:00
Joshua Goins
24d0082048 Use view-list-details instead of expand icon in room drawer 2023-08-16 20:07:46 +00:00
Joshua Goins
2980af11b0 Destroy the correct component in space list context menu 2023-08-16 20:07:46 +00:00
Joshua Goins
91d9406c38 Prevent the TapHandler in AvatarTabButton from triggering clicked()
This caused right-clicks on this component (for example, in the space
drawer) to cause clicked() to be called on the delegate.
2023-08-16 20:07:46 +00:00
Joshua Goins
280d1e38e2 Add icons to the space list context menu items 2023-08-16 20:07:46 +00:00
Joshua Goins
7b520da4b4 Prevent the chat bar from pasting a local file URL if we save the bitmap
There's no point in also putting the file:// URL, so catch the event if
saving the bitmap from the clipboard is successful.
2023-08-16 19:57:22 +00:00
Joshua Goins
419b4cea98 Ensure that the notification avatar is drawn with no pen 2023-08-16 19:46:59 +00:00
Joshua Goins
38824f30ac Further notification avatar improvements
The correct render hint is actually SmoothPixmapTransform, as
Antialiasing only matters for primitives. Also, render a white
background for potentially transparent avatars.
2023-08-16 19:46:59 +00:00
Joshua Goins
9c4d8ef823 Fix the account switcher width so it doesn't spill off the side 2023-08-16 19:39:14 +00:00
Joshua Goins
fe3bf3a638 Pick a better shadow and clean up emoji popup backgrounds
These shadows are now closer to how other popups look.
2023-08-16 19:31:07 +00:00
Joshua Goins
d678a446e2 Don't clip the emoji popups as they destroy shadows 2023-08-16 19:31:07 +00:00
Nicolas Fella
6df60a39b0 Port to KStatusNotifierItem framework 2023-08-16 11:43:56 +00:00
l10n daemon script
6f9fa76ab7 GIT_SILENT Sync po/docbooks with svn 2023-08-16 01:47:00 +00:00
Carl Schwan
6e8b0f001f Add network cache 2023-08-15 15:33:46 +00:00
l10n daemon script
0bfad95d8b GIT_SILENT Sync po/docbooks with svn 2023-08-15 01:48:13 +00:00
Tobias Fella
1b43846196 Remove obsolete quotientMinorVersion property 2023-08-14 18:05:14 +00:00
Tobias Fella
4ea183b139 Improve tooltips in chatbar 2023-08-14 07:54:47 +00:00
Tobias Fella
22fd24549b Wrap room display name in Room Drawer 2023-08-13 20:02:58 +02:00
l10n daemon script
af793fb865 GIT_SILENT Sync po/docbooks with svn 2023-08-13 01:45:51 +00:00
l10n daemon script
13414b5834 GIT_SILENT made messages (after extraction) 2023-08-13 00:46:24 +00:00
l10n daemon script
65a1df4a75 GIT_SILENT Sync po/docbooks with svn 2023-08-12 01:49:08 +00:00
l10n daemon script
d15157703a GIT_SILENT made messages (after extraction) 2023-08-12 00:46:19 +00:00
l10n daemon script
2d21330a36 GIT_SILENT Sync po/docbooks with svn 2023-08-11 01:45:25 +00:00
l10n daemon script
fbc4611d02 GIT_SILENT Sync po/docbooks with svn 2023-08-10 01:47:01 +00:00
l10n daemon script
e257865b19 GIT_SILENT made messages (after extraction) 2023-08-10 00:46:30 +00:00
James Graham
018154f555 No emoji chatbar button on mobile
Hide the emoji button in the `chatbar` and don't instantiate the dialog component on mobile. This isn't needed on mobile as the virtual keyboard can add emojis. Should also save a small amount of memory on mobile from the dialog which is normally always instantiated.
2023-08-09 18:10:53 +00:00
l10n daemon script
80a5daa1f7 GIT_SILENT Sync po/docbooks with svn 2023-08-09 01:48:44 +00:00
Carl Schwan
bf5ce049d9 Port to new settings component 2023-08-08 21:40:05 +00:00
Carl Schwan
58213ee3e6 Display big emoji correctly
We already check with a regex if the message only contains emoji so it is safe
to hardcode the font family as emoji for these messages.
2023-08-08 12:07:16 +02:00
l10n daemon script
2d1862a637 GIT_SILENT Sync po/docbooks with svn 2023-08-08 01:49:39 +00:00
Tobias Fella
67453d9fb8 Remove ifdefs for E2EE 2023-08-07 21:15:11 +00:00
Tobias Fella
3ab04583ae Force plain text in room delegate 2023-08-07 22:58:11 +02:00
l10n daemon script
794683b5d2 GIT_SILENT Sync po/docbooks with svn 2023-08-07 02:08:13 +00:00
l10n daemon script
9f7f5409bd 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-08-07 01:51:19 +00:00
l10n daemon script
7d7b9d7ae0 GIT_SILENT made messages (after extraction) 2023-08-07 00:48:50 +00:00
James Graham
c7c892c51c Fix message long press
Add a tap handler so that long press events in the text of a message can be captured. This should make mobile menus work on text messages again.
2023-08-06 17:08:46 +00:00
l10n daemon script
97903a7cb0 GIT_SILENT Sync po/docbooks with svn 2023-08-06 01:50:23 +00:00
l10n daemon script
0c8f488ac4 GIT_SILENT made messages (after extraction) 2023-08-06 00:46:42 +00:00
Tobias Fella
88368cefaa Remove leftover debug statement 2023-08-06 00:51:28 +02:00
Tobias Fella
ab4bb41979 Fix last active time in devices page 2023-08-05 20:32:47 +02:00
James Graham
c2398b19dc Fix mark all read on room change
Fix it so that the view is correctly positioned at the bottom when the room is changed and make sure this is not seen as a scroll event (i.e. messages are not automatically marked as read but the timer has to time out first and all visible on screen).
2023-08-05 17:38:21 +00:00
James Graham
4b3dac025f Declare currentRoom property
Make sure `currentRoom` is a property for every qml component where it's used in `chatbar`.
2023-08-05 16:50:06 +00:00
l10n daemon script
9eeff06328 GIT_SILENT Sync po/docbooks with svn 2023-08-05 01:46:52 +00:00
l10n daemon script
657a8291d0 GIT_SILENT made messages (after extraction) 2023-08-05 00:46:28 +00:00
James Graham
bc4431462a Chatbox id for all property refs
Change the chatbox id to root and use for all references to it properties. Using root.currentRoom is needed for the chatbar to be visible in KF6
2023-08-04 13:56:26 +00:00
l10n daemon script
fdd8a62873 GIT_SILENT Sync po/docbooks with svn 2023-08-04 01:47:18 +00:00
l10n daemon script
c164228894 GIT_SILENT made messages (after extraction) 2023-08-04 00:46:08 +00:00
Carl Schwan
7d418f0883 Shorten appstream description 2023-08-03 16:17:58 +00:00
Tobias Fella
e90aecbead Port UserDetailDialog to Kirigami.Dialog 2023-08-03 17:26:46 +02:00
l10n daemon script
221c27fbbe GIT_SILENT Sync po/docbooks with svn 2023-08-03 02:09:50 +00:00
l10n daemon script
1907404124 GIT_SILENT Sync po/docbooks with svn 2023-08-02 01:54:58 +00:00
James Graham
81e953dd8c use QTEST_MAIN 2023-08-01 15:57:58 +00:00
James Graham
9311052e39 Move polishcolor to a utils namespace and rename getusercolor 2023-08-01 15:57:58 +00:00
James Graham
648fff20f2 Updates based on comments 2023-08-01 15:57:58 +00:00
James Graham
980211f36a Remove unneeded include 2023-08-01 15:57:58 +00:00
James Graham
25e0e3fa8e Remove NeoChatUser and just use Quotient::User this simplifies things and avoids casting from one to the other which address santizer didn't like 2023-08-01 15:57:58 +00:00
l10n daemon script
403c1ed391 GIT_SILENT Sync po/docbooks with svn 2023-08-01 01:58:12 +00:00
l10n daemon script
c2f76612cf GIT_SILENT made messages (after extraction) 2023-08-01 00:46:09 +00:00
Tobias Fella
2a651b8946 Use pageStack.pushDialogLayer for devtools and inviteuser 2023-07-31 20:44:50 +02:00
Volker Krause
00c0d1c276 Add heading indicator for live locations
Heading isn't covered by any MSC so far, so that is using Itinerary's
vendor prefix for now.
2023-07-31 18:06:52 +02:00
Carl Schwan
0162d91b60 Ensure e2ee is enabled 2023-07-31 07:09:23 +00:00
Carl Schwan
5f41b7b4c1 Fix opening account menu on right click 2023-07-31 07:02:00 +00:00
l10n daemon script
d9691bac7c GIT_SILENT Sync po/docbooks with svn 2023-07-31 02:10:40 +00:00
Tobias Fella
719b916837 Add accessible name to RoomDelegate 2023-07-30 22:57:46 +02:00
Tobias Fella
f9514fe925 Add accessible name to chatbar 2023-07-30 22:57:43 +02:00
Tobias Fella
399b9e6944 Add text and tooltip to section collapse/expand button 2023-07-30 22:29:21 +02:00
l10n daemon script
00cf5c8a5b GIT_SILENT Sync po/docbooks with svn 2023-07-30 01:49:49 +00:00
l10n daemon script
02f26424e2 GIT_SILENT made messages (after extraction) 2023-07-30 00:45:54 +00:00
Tobias Fella
3bd639775a Fix room list icon size in compact room list
BUG: 472682
2023-07-29 19:00:58 +00:00
Tobias Fella
163c1ef407 Html-escape display names in state delegates 2023-07-29 15:42:53 +02:00
Tobias Fella
9997b1074a Make "Close to system tray" string more correct
BUG: 472051
2023-07-29 09:01:14 +00:00
l10n daemon script
f52a25717b GIT_SILENT Sync po/docbooks with svn 2023-07-29 01:46:50 +00:00
l10n daemon script
5746c24b73 GIT_SILENT Sync po/docbooks with svn 2023-07-28 01:55:04 +00:00
l10n daemon script
dca1b22521 GIT_SILENT made messages (after extraction) 2023-07-28 00:47:00 +00:00
l10n daemon script
b15f1461d8 GIT_SILENT Sync po/docbooks with svn 2023-07-27 01:47:22 +00:00
Joshua Goins
24fd7a0f5b Use prettier notification images
Avatars are shown rounded in the main interface, so they should look the
same in the notification tray too. On top of that, if the room is a
group then show that group's icon when applicable in the bottom right.
2023-07-26 08:31:58 +00:00
Joshua Goins
0ac3932303 Add an obvious "upload" button in the account editor
It's not obvious at first glance that you can click on the avatar in the
account editor to upload an image. This adds a new button when there is
no image uploaded.
2023-07-26 08:27:55 +00:00
Joshua Goins
807a9ee779 Fix errors preventing the avatar from being shown when uploaded 2023-07-26 08:27:55 +00:00
Joshua Goins
4f32a168cd Fix settings button tooltip 2023-07-26 02:04:24 -04:00
l10n daemon script
45d2da56c7 GIT_SILENT Sync po/docbooks with svn 2023-07-26 01:49:31 +00:00
l10n daemon script
d794e26d62 GIT_SILENT made messages (after extraction) 2023-07-26 00:46:56 +00:00
l10n daemon script
42cc42642d GIT_SILENT Sync po/docbooks with svn 2023-07-25 01:47:33 +00:00
l10n daemon script
ffd6205bd1 GIT_SILENT Sync po/docbooks with svn 2023-07-24 09:05:17 +00:00
Tobias Fella
9ba6b2f0a5 Fix clearing user search field text when switching rooms 2023-07-24 08:45:51 +00:00
Carl Schwan
f8d3e25f8e Move no connection info message to the top 2023-07-24 08:45:10 +00:00
Carl Schwan
75cd77facb Refactor completion menu
- Use new Avatar
- Use required property in delegate
2023-07-24 08:44:49 +00:00
l10n daemon script
8546d76a54 GIT_SILENT made messages (after extraction) 2023-07-24 07:34:02 +00:00
Tobias Fella
00b7f68a03 Fix nullptr check 2023-07-23 23:10:52 +02:00
Carl Schwan
b486cb905c Add back some spacing around the avatar in the timeline 2023-07-22 18:41:09 +00:00
Carl Schwan
cdd5c9f484 Fix accessibility of StartChatPage and port to new components 2023-07-22 18:41:09 +00:00
Carl Schwan
3e6c426397 Port Avatar usage in Settings KirigamiAddons 2023-07-22 18:41:09 +00:00
Carl Schwan
847f41e1ad Port most Avatar usage to new KirigamiAddons Avatar 2023-07-22 18:41:09 +00:00
Carl Schwan
ed5bb270ff Discard wrong avatar urls 2023-07-22 17:51:03 +00:00
Carl Schwan
c8b4da2b96 Scroll to top of RoomDrawer on loading of header 2023-07-22 17:50:32 +00:00
Tobias Fella
ba5445e135 Stop finding QtKeychain
Has been upstreamed to libQuotient
2023-07-22 16:14:56 +02:00
l10n daemon script
1cca39e105 GIT_SILENT Sync po/docbooks with svn 2023-07-22 01:57:06 +00:00
Carl Schwan
dbf67b984e Fix reply error message when the reply is not loaded yet 2023-07-21 11:24:10 +02:00
l10n daemon script
c9126cf38e GIT_SILENT Sync po/docbooks with svn 2023-07-21 02:04:06 +00:00
Tobias Fella
13988da4fc Add login appium test 2023-07-20 07:14:23 +00:00
Carl Schwan
0847839abc Remove hover effect on timeline events 2023-07-20 08:40:15 +02:00
Carl Schwan
6b55e502a0 Remove duplicated code in QuickSwitcher for RoomDelegate 2023-07-20 08:39:59 +02:00
Carl Schwan
8f81629ac1 Redesign room list
Use KirigamiAddons.Delegated.RoundedItemDelegate
2023-07-20 08:39:57 +02:00
Carl Schwan
7f459cb90f Redesign timeline
Remove border von bubbles and only hilight the bubble on hover
2023-07-20 08:38:51 +02:00
l10n daemon script
420e195313 GIT_SILENT Sync po/docbooks with svn 2023-07-20 01:59:01 +00:00
Carl Schwan
3263a69880 Port to KirigamAddons.Banner 2023-07-19 22:46:36 +02:00
l10n daemon script
b060881f06 GIT_SILENT Sync po/docbooks with svn 2023-07-19 02:41:03 +00:00
Tobias Fella
701e786c1f Require passing tests on windows 2023-07-18 23:23:33 +02:00
Tobias Fella
646c8ba8fe Fix opening user mentions 2023-07-18 05:54:15 +00:00
Tobias Fella
9b31fdea10 Cleanup CMake after depending on libQuotient 0.7 2023-07-18 05:26:49 +00:00
l10n daemon script
ce5dfdee16 GIT_SILENT Sync po/docbooks with svn 2023-07-18 01:55:04 +00:00
Tobias Fella
918e805718 Fix image loading in room avatars 2023-07-17 11:25:52 +00:00
Albert Astals Cid
7debf47833 GIT_SILENT Upgrade release service version to 23.11.70. 2023-07-17 12:53:16 +02:00
Tobias Fella
2c142c36e6 Remove cmake policy 2023-07-17 11:57:19 +02:00
l10n daemon script
3279142498 GIT_SILENT Sync po/docbooks with svn 2023-07-17 01:57:57 +00:00
l10n daemon script
0e08a1aa7e GIT_SILENT made messages (after extraction) 2023-07-17 00:49:09 +00:00
162 changed files with 19809 additions and 18489 deletions

View File

@@ -26,7 +26,7 @@
"name": "kirigamiaddons",
"config-opts": [ "-DBUILD_TESTING=OFF" ],
"buildsystem": "cmake-ninja",
"sources": [ { "type": "git", "url": "https://invent.kde.org/libraries/kirigami-addons.git", "branch": "kf5" } ]
"sources": [ { "type": "git", "url": "https://invent.kde.org/libraries/kirigami-addons.git" } ]
},
{
"name": "kquickimageeditor",

View File

@@ -2,13 +2,13 @@
# SPDX-License-Identifier: CC0-1.0
include:
- project: sysadmin/ci-utilities
file:
- /gitlab-templates/reuse-lint.yml
- /gitlab-templates/android.yml
# - /gitlab-templates/linux.yml
- /gitlab-templates/linux-qt6.yml
- /gitlab-templates/windows.yml
# - /gitlab-templates/freebsd.yml
- /gitlab-templates/flatpak.yml
- /gitlab-templates/craft-android-apks.yml
- 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/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/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

@@ -57,6 +57,11 @@ Dependencies:
- 'on': ['Linux/Qt6', 'FreeBSD/Qt6']
'require':
'frameworks/kdbusaddons': '@latest-kf6'
'frameworks/kstatusnotifieritem': '@latest-kf6'
- 'on': ['Linux/Qt6', 'Linux/Qt5']
'require':
'sdk/selenium-webdriver-at-spi': '@latest-kf6'
Options:
require-passing-tests-on: [ 'Linux/Qt5', 'FreeBSD' ]
require-passing-tests-on: [ 'Linux/Qt5', 'FreeBSD', 'Windows' ]

View File

@@ -8,8 +8,8 @@ cmake_minimum_required(VERSION 3.16)
# KDE Applications version, managed by release script.
set(RELEASE_SERVICE_VERSION_MAJOR "23")
set(RELEASE_SERVICE_VERSION_MINOR "08")
set(RELEASE_SERVICE_VERSION_MICRO "3")
set(RELEASE_SERVICE_VERSION_MINOR "11")
set(RELEASE_SERVICE_VERSION_MICRO "70")
set(RELEASE_SERVICE_VERSION "${RELEASE_SERVICE_VERSION_MAJOR}.${RELEASE_SERVICE_VERSION_MINOR}.${RELEASE_SERVICE_VERSION_MICRO}")
project(NeoChat VERSION ${RELEASE_SERVICE_VERSION})
@@ -27,7 +27,7 @@ set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(KDE_COMPILERSETTINGS_LEVEL 5.84)
set(KDE_COMPILERSETTINGS_LEVEL 5.105)
include(FeatureSummary)
include(ECMSetupVersion)
@@ -93,11 +93,9 @@ set_package_properties(KF${QT_MAJOR_VERSION}Kirigami2 PROPERTIES
)
find_package(KF${QT_MAJOR_VERSION}KirigamiAddons 0.7.2 REQUIRED)
find_package(Qt${QT_MAJOR_VERSION}Keychain)
set_package_properties(Qt${QT_MAJOR_VERSION}Keychain PROPERTIES
TYPE REQUIRED
PURPOSE "Secure storage of account secrets"
)
if(QT_MAJOR_VERSION STREQUAL "6")
find_package(KF6StatusNotifierItem ${KF_MIN_VERSION} REQUIRED)
endif()
if(ANDROID)
find_package(OpenSSL)
@@ -130,6 +128,11 @@ set_package_properties(Quotient${QUOTIENT_SUFFIX} PROPERTIES
PURPOSE "Talk with matrix server"
)
if (NOT TARGET Olm::Olm)
message(FATAL_ERROR "NeoChat requires Quotient with the E2EE feature enabled")
endif()
find_package(cmark)
set_package_properties(cmark PROPERTIES
TYPE REQUIRED
@@ -141,7 +144,6 @@ set_package_properties(cmark PROPERTIES
ecm_find_qmlmodule(org.kde.kquickimageeditor 1.0)
ecm_find_qmlmodule(org.kde.kitemmodels 1.0)
ecm_find_qmlmodule(org.kde.quickcharts 1.0)
ecm_find_qmlmodule(QtLocation ${QTLOCATION_MODULE_QML_VERSION})
find_package(KQuickImageEditor COMPONENTS)
set_package_properties(KQuickImageEditor PROPERTIES
@@ -161,10 +163,6 @@ set_package_properties(KF${QT_MAJOR_VERSION}DocTools PROPERTIES DESCRIPTION
TYPE OPTIONAL
)
if(NOT Quotient${QUOTIENT_SUFFIX}_VERSION_MINOR GREATER 6)
cmake_policy(SET CMP0063 OLD)
endif()
if(ANDROID)
find_package(Sqlite3)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/android/version.gradle.in ${CMAKE_BINARY_DIR}/version.gradle)
@@ -180,9 +178,11 @@ install(FILES org.kde.neochat.tray.svg DESTINATION ${KDE_INSTALL_FULL_ICONDIR}/h
add_definitions(-DQT_NO_FOREACH)
add_subdirectory(src)
if (BUILD_TESTING AND Quotient${QUOTIENT_SUFFIX}_VERSION_MINOR GREATER 6)
if (BUILD_TESTING)
find_package(Qt${QT_MAJOR_VERSION} ${QT_MIN_VERSION} NO_MODULE COMPONENTS Test)
add_subdirectory(autotests)
add_subdirectory(appiumtests)
endif()
if(KF${QT_MAJOR_VERSION}DocTools_FOUND)

View File

@@ -9,7 +9,7 @@
A Qt/QML based Matrix client.
<a href='https://matrix.org'><img src='https://matrix.org/docs/projects/images/made-for-matrix.png' alt='Made for Matrix' height=64 target=_blank /></a>
<a href='https://matrix.org'><img src='https://matrix.org/docs/legacy/made-for-matrix.png' alt='Made for Matrix' height=64 target=_blank /></a>
<a href='https://flathub.org/apps/details/org.kde.neochat'><img width='190px' alt='Download on Flathub' src='https://flathub.org/assets/badges/flathub-badge-i-en.png'/></a>
## Introduction

View File

@@ -0,0 +1,23 @@
# SPDX-License-Identifier: BSD-3-Clause
# SPDX-FileCopyrightText: 2022 Harald Sitter <sitter@kde.org>
if(NOT BUILD_TESTING OR NOT CMAKE_SYSTEM_NAME MATCHES "Linux")
return()
endif()
find_package(SeleniumWebDriverATSPI)
set_package_properties(SeleniumWebDriverATSPI PROPERTIES
DESCRIPTION "Server component for selenium tests using Linux accessibility infrastructure"
PURPOSE "Needed for GUI tests"
URL "https://invent.kde.org/sdk/selenium-webdriver-at-spi"
TYPE OPTIONAL
)
if(NOT SeleniumWebDriverATSPI_FOUND)
return()
endif()
add_test(
NAME logintest
COMMAND selenium-webdriver-at-spi-run ${CMAKE_CURRENT_SOURCE_DIR}/logintest.py
)

View File

@@ -0,0 +1,42 @@
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
from flask import Flask, request, abort
app = Flask(__name__)
@app.route("/_matrix/client/v3/login", methods=["GET"])
def login_get():
result = dict()
result["flows"] = [dict()]
result["flows"][0]["type"] = "m.login.password"
return result
@app.route("/_matrix/client/v3/login", methods=["POST"])
def login_post():
data = request.get_json()
if data["identifier"]["user"] != "user" or data["password"] != "1234":
abort(403)
print(data)
result = dict()
result["access_token"] = "token_1234"
result["device_id"] = "device_1234"
result["user_id"] = "@user:localhost:1234"
return result
@app.route("/_matrix/client/r0/sync")
def sync():
result = dict()
result["next_batch"] = "batch1234"
return result
@app.route("/.well-known/matrix/client")
def well_known():
reply = dict()
reply["m.homeserver"] = dict()
reply["m.homeserver"]["base_url"] = "https://localhost:1234"
return reply
if __name__ == "__main__":
app.run(ssl_context='adhoc', port=1234)

44
appiumtests/logintest.py Executable file
View File

@@ -0,0 +1,44 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021-2022 Harald Sitter <sitter@kde.org>
# SPDX-FileCopyrightText: 2023 Tobias Fella <tobias.fella@kde.org>
import unittest
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
import time
import subprocess
class LoginTest(unittest.TestCase):
@classmethod
def setUpClass(self):
desired_caps = {}
desired_caps["app"] = "neochat --ignore-ssl-errors"
desired_caps["timeouts"] = {'implicit': 10000}
self.driver = webdriver.Remote(
command_executor='http://127.0.0.1:4723',
desired_capabilities=desired_caps)
subprocess.Popen(["python","login-server.py"])
def setUp(self):
pass
def tearDown(self):
if not self._outcome.result.wasSuccessful():
self.driver.get_screenshot_as_file("failed_test_shot_{}.png".format(self.id()))
@classmethod
def tearDownClass(self):
self.driver.quit()
def test_login(self):
self.driver.find_element(by=AppiumBy.NAME, value="Matrix ID").send_keys("@user:localhost:1234")
self.driver.find_element(by=AppiumBy.NAME, value="Continue").click()
self.driver.find_element(by=AppiumBy.NAME, value="Password").send_keys("1234")
self.driver.find_element(by=AppiumBy.NAME, value="Login").click()
self.driver.find_element(by=AppiumBy.NAME, value="Join some rooms to get started").click()
if __name__ == '__main__':
unittest.main()

View File

@@ -10,6 +10,8 @@
#include <Quotient/syncdata.h>
#include <qnamespace.h>
#include "utils.h"
using namespace Quotient;
class TestRoom : public NeoChatRoom
@@ -555,10 +557,10 @@ void TextHandlerTest::receiveRichPlainUrl()
void TextHandlerTest::receiveRichEmote()
{
auto event = room->messageEvents().at(1).get();
auto author = static_cast<NeoChatUser *>(room->user(event->senderId()));
auto author = room->user(event->senderId());
const QString testInputString = QStringLiteral("This is an emote.");
const QString testOutputString = QStringLiteral("* <a href=\"https://matrix.to/#/@example:example.org\" style=\"color:") + author->color().name()
+ QStringLiteral("\">@example:example.org</a> This is an emote.");
const QString testOutputString = QStringLiteral("* <a href=\"https://matrix.to/#/@example:example.org\" style=\"color:")
+ Utils::getUserColor(author->hueF()).name() + QStringLiteral("\">@example:example.org</a> This is an emote.");
TextHandler testTextHandler;
testTextHandler.setData(testInputString);
@@ -602,13 +604,13 @@ void TextHandlerTest::linkPreviewsMatch_data()
QTest::addColumn<QString>("testInputString");
QTest::addColumn<QList<QUrl>>("testOutputLinks");
QTest::newRow("plainHttps") << QStringLiteral("https://kde.org") << QList<QUrl>({QUrl("https://kde.org")});
QTest::newRow("richHttps") << QStringLiteral("<a href=\"https://kde.org\">Rich Link</a>") << QList<QUrl>({QUrl("https://kde.org")});
QTest::newRow("plainWww") << QStringLiteral("www.example.org") << QList<QUrl>({QUrl("www.example.org")});
QTest::newRow("plainHttps") << QStringLiteral("https://kde.org") << QList<QUrl>({QUrl("https://kde.org"_ls)});
QTest::newRow("richHttps") << QStringLiteral("<a href=\"https://kde.org\">Rich Link</a>") << QList<QUrl>({QUrl("https://kde.org"_ls)});
QTest::newRow("plainWww") << QStringLiteral("www.example.org") << QList<QUrl>({QUrl("www.example.org"_ls)});
QTest::newRow("multipleHttps") << QStringLiteral("https://kde.org www.example.org")
<< QList<QUrl>({
QUrl("https://kde.org"),
QUrl("www.example.org"),
QUrl("https://kde.org"_ls),
QUrl("www.example.org"_ls),
});
}
@@ -644,5 +646,5 @@ void TextHandlerTest::linkPreviewsReject()
QCOMPARE(testTextHandler.getLinkPreviews(), testOutputLinks);
}
QTEST_GUILESS_MAIN(TextHandlerTest)
QTEST_MAIN(TextHandlerTest)
#include "texthandlertest.moc"

View File

@@ -46,43 +46,25 @@
<name xml:lang="uk">NeoChat</name>
<name xml:lang="x-test">xxNeoChatxx</name>
<name xml:lang="zh-CN">NeoChat</name>
<summary>A client for matrix, the decentralized communication protocol</summary>
<summary xml:lang="ar">عميل لماتركس، ميفاق الاتصال اللامركزي</summary>
<summary xml:lang="az">Matrix üçün müştəri, mərkəzləşməmiş kommunikasiya protokolu</summary>
<summary xml:lang="ca">Un client de Matrix, el protocol de comunicacions descentralitzat</summary>
<summary xml:lang="ca-valencia">Un client de Matrix, el protocol de comunicacions descentralitzat</summary>
<summary xml:lang="cs">Klient pro decentralizovaný komunikační protokol matrix</summary>
<summary xml:lang="de">Ein Programm für Matrix, das dezentrale Kommunikationsprotokoll</summary>
<summary xml:lang="el">Ένας πελάτης για το Matrix, το αποκεντρωμένο πρωτόκολλο επικοινωνίας</summary>
<summary xml:lang="en-GB">A client for matrix, the decentralised communication protocol</summary>
<summary xml:lang="eo">Kliento por matrix, la malcentra komunikprotokolo</summary>
<summary xml:lang="es">Un cliente para Matrix, el protocolo de comunicaciones descentralizado</summary>
<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>
<summary xml:lang="ie">Un cliente de Matrix, li protocol de communication decentralisat</summary>
<summary xml:lang="it">Un client per matrix, il protocollo di comunicazione decentralizzato</summary>
<summary xml:lang="ka">კლიენტი Matrix-სთვის, დეცენტრალიზებული კომუნიკაციის პროტოკოლისთვის</summary>
<summary xml:lang="ko">Matrix, 분산 대화 프로토콜 클라이언트</summary>
<summary xml:lang="nl">Een client voor matrix, het gedecentraliseerde communicatieprotocol</summary>
<summary xml:lang="nn">Ein klient for Matrix  protokollen for desentralisert kommunikasjon</summary>
<summary xml:lang="pa">ਮੈਟਰਿਕਸ, ਸਰਬ-ਸਾਂਝੇ ਸੰਚਾਰ ਪਰੋਟੋਕਾਲ, ਲਈ ਕਲਾਈਂਟ ਹੈ</summary>
<summary xml:lang="pl">Program do obsługi matriksa, rozproszonego protokołu porozumiewania się</summary>
<summary xml:lang="pt">Um cliente para o Matrix, o protocolo de comunicação descentralizado</summary>
<summary xml:lang="pt-BR">Um cliente do Matrix, o protocolo de comunicação descentralizado</summary>
<summary xml:lang="ru">Клиент для Matrix — децентрализованного коммуникационного протокола</summary>
<summary xml:lang="sk">Klient pre matrix, decentralizovaný komunikačný protokol</summary>
<summary xml:lang="sl">Odjemalec za matrix, decentralizirani komunikacijski protokol</summary>
<summary xml:lang="sv">En klient för Matrix, det decentraliserade kommunikationsprotokollet</summary>
<summary xml:lang="ta">மையமில்லா தகவல் பரிமாற்ற நெறிமுறையான மேட்ரிக்ஸுக்கான செயலி</summary>
<summary xml:lang="tr">Merkezi olmayan iletişim protokolü Matrix için bir istemci</summary>
<summary xml:lang="uk">Клієнт matrix, децентралізованого протоколу обміну даними</summary>
<summary xml:lang="x-test">xxA client for matrix, the decentralized communication protocolxx</summary>
<summary xml:lang="zh-CN">分布式通讯协议 Matrix 的客户端</summary>
<summary>Chat with your friends on matrix</summary>
<summary xml:lang="ar">دردش مع أصدقائك على ماتركس</summary>
<summary xml:lang="ca">Xategeu amb els vostres amics a Matrix</summary>
<summary xml:lang="ca-valencia">Xategeu amb els vostres amics a Matrix</summary>
<summary xml:lang="eo">Babilu kun viaj amikoj sur matrix</summary>
<summary xml:lang="es">Charle con sus amigos en matrix</summary>
<summary xml:lang="eu">Berriketan jardun zure lagunekin «Matrix»en</summary>
<summary xml:lang="fr">Discuter avec vos ami(e)s sur le réseau Matrix</summary>
<summary xml:lang="gl">Charle coas súas amizades en Matrix.</summary>
<summary xml:lang="it">Conversa con i tuoi contatti su matrix</summary>
<summary xml:lang="ka">ესაუბრეთ მეგობრებს Matrix-ზე</summary>
<summary xml:lang="nl">Met uw vrienden chatten op matrix</summary>
<summary xml:lang="nn">Prat med vennar på Matrix</summary>
<summary xml:lang="sl">Klepet z vašimi prijatelji na matrixu</summary>
<summary xml:lang="sv">Chatta med dina vänner på Matrix</summary>
<summary xml:lang="ta">மேட்ரிக்ஸு மூலம் உங்கள் நண்பர்களிடம் பேசலாம்</summary>
<summary xml:lang="tr">Matrix'te arkadaşlarınızla sohbet edin</summary>
<summary xml:lang="uk">Спілкуйтеся з вашими друзями у matrix</summary>
<summary xml:lang="x-test">xxChat with your friends on matrixxx</summary>
<description>
<p>NeoChat is a client for Matrix, the decentralized communication protocol for instant messaging. It allows you to send text messages, videos and audio files to your family, colleagues and friends. It uses KDE frameworks and most notably Kirigami
to provide a convergent experience across multiple platforms.</p>
@@ -112,8 +94,9 @@ to provide a convergent experience across multiple platforms.</p>
<p>NeoChat aims to be a fully featured application for the Matrix specification. As such everything in the current stable specification with the notable exceptions of VoIP, threads and some aspects of End-to-End Encryption are supported. There are a few other smaller omissions due to the fact that the Matrix spec is constantly evolving but the aim remains to provide eventual support for the entire spec.</p>
<p xml:lang="ar">يهدف نيوتشات إلى أن يكون تطبيقًا كامل الميزات لمواصفات ماتركس. على هذا النحو يتم دعم كل شيء في المواصفات المستقرة الحالية مع الاستثناءات الملحوظة لـ VoIP والخيوط وبعض جوانب التشفير من طرف إلى طرف. هناك عدد قليل من الإغفالات الصغيرة الأخرى بسبب حقيقة أن مواصفات ماتركس تتطور باستمرار ، ولكن يبقى الهدف توفير الدعم النهائي للمواصفات بأكملها.</p>
<p xml:lang="ca">NeoChat pretén ser una aplicació amb totes les característiques per a l'especificació de Matrix. Com a tal, s'ha implementat tota l'especificació actual estable amb les notables excepcions de la VoIP, fils i alguns aspectes de l'encriptatge d'extrem a extrem. Hi ha algunes altres omissions més petites a causa del fet que l'especificació de Matrix està evolucionant constantment, però l'objectiu segueix sent proporcionar suport eventual per a tota l'especificació.</p>
<p xml:lang="ca-valencia">NeoChat pretén ser una aplicació amb totes les característiques per a l'especificació de Matrix. Com a tal, s'ha implementat tota l'especificació actual estable amb les notables excepcions de la 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="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="eo">NeoChat celas esti plene kapabla aplikaĵo por la Matrix-specifo. Kiel tia, ĉio en la nuna stabila specifo kun la rimarkindaj esceptoj de VoIP, fadenoj kaj kelkaj aspektoj de Fin-al-Fina Ĉifrado estas subtenataj. Estas kelkaj aliaj pli malgrandaj preterlasoj pro la fakto, ke la Matrix-speco konstante evoluas, sed la celo restas provizi finfine subtenon por la tuta specifaĵo.</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="eu">«NeoChat»ek «Matrix» zehaztapenaren ezaugarri guztiak eskaintzen dituen aplikazio bat izan nahi du. Beraz, egungo zehaztapen egonkorrean dagoen guztiaren euskarria du, VoIP, hariak eta muturren artean zifratzeko salbuespen nabarmenekin. Badira beste ez-betetze txikiago batzuk, «Matrix»en zehaztapena etengabe eboluzioan dagoelako, baina azken helburua zehaztapen osoaren euskarria ematea izaten jarraitzen du.</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>
@@ -137,6 +120,7 @@ to provide a convergent experience across multiple platforms.</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="eo">Pro la naturo de la Matrix-specifevoluo NeoChat ankaŭ subtenas multajn malstabilajn funkciojn. Nuntempe ĉi tiuj estas:</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="eu">«Matrix» zehaztapenaren garapenaren izaeragatik, «Neo¢hat»ek ezaugarri ezegonkor ugari ere onartzen ditu. Gaur egun hauek:</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>
@@ -162,6 +146,7 @@ to provide a convergent experience across multiple platforms.</p>
<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="eo">Enketoj - MSC3381</li>
<li xml:lang="es">Encuestas - MSC3381</li>
<li xml:lang="eu">Polls - MSC3381</li>
<li xml:lang="fi">Kyselyt MSC3381</li>
@@ -173,7 +158,6 @@ to provide a convergent experience across multiple platforms.</p>
<li xml:lang="ko">투표 - MSC3381</li>
<li xml:lang="nl">Polls - MSC3381</li>
<li xml:lang="nn">Avstemmingar  MSC3381</li>
<li xml:lang="pl">Ankiety - MSC3381</li>
<li xml:lang="pt">Inquéritos - MSC3381</li>
<li xml:lang="sl">Polls - MSC3381</li>
<li xml:lang="sv">Polls - MSC3381</li>
@@ -186,6 +170,7 @@ to provide a convergent experience across multiple platforms.</p>
<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="eo">Glumark-Pakoj - MSC2545</li>
<li xml:lang="es">Paquetes de pegatinas - MSC2545</li>
<li xml:lang="eu">Eranskailu paketeak - MSC2545</li>
<li xml:lang="fi">Tarrapakkaukset MSC2545</li>
@@ -197,7 +182,6 @@ to provide a convergent experience across multiple platforms.</p>
<li xml:lang="ko">스티커 팩 - MSC2545</li>
<li xml:lang="nl">Sticker Packs - MSC2545</li>
<li xml:lang="nn">Klistremerke-pakkar  MSC2545</li>
<li xml:lang="pl">Paczki naklejek - MSC2545</li>
<li xml:lang="pt">Pacotes de Autocolantes - MSC2545</li>
<li xml:lang="sl">Sticker Packs - MSC2545</li>
<li xml:lang="sv">Sticker Packs - MSC2545</li>
@@ -210,6 +194,7 @@ to provide a convergent experience across multiple platforms.</p>
<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="eo">Lokaj Eventoj - MSC3488</li>
<li xml:lang="es">Eventos de ubicación - MSC3488</li>
<li xml:lang="eu">Kokaleku-gertaerak - MSC3488</li>
<li xml:lang="fi">Sijaintitapahtumat MSC3488</li>
@@ -221,7 +206,6 @@ to provide a convergent experience across multiple platforms.</p>
<li xml:lang="ko">위치 이벤트 - MSC3488</li>
<li xml:lang="nl">Locatie gebeurtenissen - MSC3488</li>
<li xml:lang="nn">Posisjonshendingar  MSC3488</li>
<li xml:lang="pl">Wydarzenia w miejscach - MSC3488</li>
<li xml:lang="pt">Eventos com Localizações - MSC3488</li>
<li xml:lang="sl">Location Events - MSC3488</li>
<li xml:lang="sv">Location Events - MSC3488</li>
@@ -283,6 +267,52 @@ to provide a convergent experience across multiple platforms.</p>
<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::windows_store::screenshots::1::image">https://cdn.kde.org/screenshots/neochat/NeoChat-Windows-Timeline.png</value>
<value key="KDE::windows_store::screenshots::1::caption">Main view with room list, chat, and room information</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="ar">العرض الرئيسة مع قائمة الغرف والدردشات و معلومات الغرفة</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="ca">Vista principal amb la llista de sales, xats i informació de les sales</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="ca-valencia">Vista principal amb la llista de sales, xats i informació de les sales</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="eo">Ĉefa vido kun ĉambra listo, babilejo kaj ĉambra informo</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="es">Vista principal con la lista de salas, chat e información de la sala</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="eu">Ikuspegi nagusia gela-zerrenda, berriketa, eta gelako informazioarekin</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="fi">Päänäkymä, jossa huoneluettelo, keskustelu ja huoneen tiedot</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="fr">Vue principale avec la liste des salons ainsi que des informations sur les salons et forums de discussions</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="gl">Vista principal coa lista de salas, a charla, e información da sala.</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="it">Vista principale con elenco delle stanze, chat e informazioni sulla stanza</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="ka">მთავარი ხედი სურათების სიით, ჩატით და ოთახის ინფორმაციით</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="ko">대화방 목록, 채팅, 대화방 정보가 표시된 주 보기</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="nl">Hoofdweergave met lijst met rooms, chat en roominformatie</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="nn">Hovudvising med romliste, pratevindauge og rominformasjon</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="pt">A área principal com a lista de salas e com informações sobre a conversa e a sala</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="sl">Glavni pogled s seznamom sob, klepetom in informacijami o sobah</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="sv">Huvudvy med rumslista, chatt, och rumsinformation</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="ta">அரங்குப்பட்டியல், உரையாடல், மற்றும் அரங்குவிவரங்களைக் கொண்டுள்ள பிரதான காட்சி</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="tr">Oda listesini, sohbet penceresini ve oda bilgisini gösteren ana görünüm</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="uk">Головна панель із списком кімнат, спілкуванням та даними щодо кімнати</value>
<value key="KDE::windows_store::screenshots::1::caption" xml:lang="x-test">xxMain view with room list, chat, and room informationxx</value>
<value key="KDE::windows_store::screenshots::2::image">https://cdn.kde.org/screenshots/neochat/NeoChat-Windows-Login.png</value>
<value key="KDE::windows_store::screenshots::2::caption">Login screen</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="ar">شاشة الدخول</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="ca">Pantalla d'inici de sessió</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="ca-valencia">Pantalla d'inici de sessió</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="eo">Ensaluta ekrano</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="es">Pantalla de inicio de sesión</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="eu">Saio-hasteko pantaila</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="fi">Kirjautumisnäkymä</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="fr">Écran de connexion</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="gl">Pantalla de identificación.</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="it">Schermata di accesso</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="ka">შესვლის ეკრანი</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="ko">로그인 화면</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="nl">Aanmeldscherm</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="nn">Innloggingsbilete</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="pt">Ecrã de autenticação</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="sl">Prijavni zaslon</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="sv">Inloggningsfönster</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="ta">நுழைவுத் திரை</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="tr">Oturum açma ekranı</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="uk">Вікно входу</value>
<value key="KDE::windows_store::screenshots::2::caption" xml:lang="x-test">xxLogin screenxx</value>
</custom>
<launchable type="desktop-id">org.kde.neochat.desktop</launchable>
<screenshots>
@@ -292,81 +322,16 @@ to provide a convergent experience across multiple platforms.</p>
<screenshot type="default">
<image>https://cdn.kde.org/screenshots/neochat/application.png</image>
</screenshot>
<screenshot x-kde-os="windows">
<image>https://cdn.kde.org/screenshots/neochat/NeoChat-Windows-Timeline.png</image>
<caption>Main view with room list, chat, and room information</caption>
<caption xml:lang="ar">العرض الرئيسة مع قائمة الغرف والدردشات و معلومات الغرفة</caption>
<caption xml:lang="ca">Vista principal amb la llista de sales, xats i informació de les sales</caption>
<caption xml:lang="ca-valencia">Vista principal amb la llista de sales, xats i informació de les sales</caption>
<caption xml:lang="es">Vista principal con la lista de salas, chat e información de la sala</caption>
<caption xml:lang="eu">Ikuspegi nagusia gela-zerrenda, berriketa, eta gelako informazioarekin</caption>
<caption xml:lang="fi">Päänäkymä, jossa huoneluettelo, keskustelu ja huoneen tiedot</caption>
<caption xml:lang="fr">Vue principale avec la liste des salons ainsi que des informations sur les salons et forums de discussions</caption>
<caption xml:lang="gl">Vista principal coa lista de salas, a charla, e información da sala.</caption>
<caption xml:lang="ia">Vista principal con lista de sala, chat e information de sala</caption>
<caption xml:lang="it">Vista principale con elenco delle stanze, chat e informazioni sulla stanza</caption>
<caption xml:lang="ka">მთავარი ხედი სურათების სიით, ჩატით და ოთახის ინფორმაციით</caption>
<caption xml:lang="ko">대화방 목록, 채팅, 대화방 정보가 표시된 주 보기</caption>
<caption xml:lang="nl">Hoofdweergave met lijst met rooms, chat en roominformatie</caption>
<caption xml:lang="nn">Hovudvising med romliste, pratevindauge og rominformasjon</caption>
<caption xml:lang="pl">Główny widok z wykazem pokojów, rozmowami i szczegółami pokojów</caption>
<caption xml:lang="pt">A área principal com a lista de salas e com informações sobre a conversa e a sala</caption>
<caption xml:lang="sl">Glavni pogled s seznamom sob, klepetom in informacijami o sobah</caption>
<caption xml:lang="sv">Huvudvy med rumslista, chatt, och rumsinformation</caption>
<caption xml:lang="ta">அரங்குப்பட்டியல், உரையாடல், மற்றும் அரங்குவிவரங்களைக் கொண்டுள்ள பிரதான காட்சி</caption>
<caption xml:lang="tr">Oda listesini, sohbet penceresini ve oda bilgisini gösteren ana görünüm</caption>
<caption xml:lang="uk">Головна панель із списком кімнат, спілкуванням та даними щодо кімнати</caption>
<caption xml:lang="x-test">xxMain view with room list, chat, and room informationxx</caption>
</screenshot>
<screenshot x-kde-os="windows">
<image>https://cdn.kde.org/screenshots/neochat/NeoChat-Windows-Login.png</image>
<caption>Login screen</caption>
<caption xml:lang="ar">شاشة الدخول</caption>
<caption xml:lang="ca">Pantalla d'inici de sessió</caption>
<caption xml:lang="ca-valencia">Pantalla d'inici de sessió</caption>
<caption xml:lang="es">Pantalla de inicio de sesión</caption>
<caption xml:lang="eu">Saio-hasteko pantaila</caption>
<caption xml:lang="fi">Kirjautumisnäkymä</caption>
<caption xml:lang="fr">Écran de connexion</caption>
<caption xml:lang="gl">Pantalla de identificación.</caption>
<caption xml:lang="ia">Schermo de accesso</caption>
<caption xml:lang="it">Schermata di accesso</caption>
<caption xml:lang="ka">შესვლის ეკრანი</caption>
<caption xml:lang="ko">로그인 화면</caption>
<caption xml:lang="nl">Aanmeldscherm</caption>
<caption xml:lang="nn">Innloggingsbilete</caption>
<caption xml:lang="pl">Ekran logowania</caption>
<caption xml:lang="pt">Ecrã de autenticação</caption>
<caption xml:lang="sl">Prijavni zaslon</caption>
<caption xml:lang="sv">Inloggningsfönster</caption>
<caption xml:lang="ta">நுழைவுத் திரை</caption>
<caption xml:lang="tr">Oturum açma ekranı</caption>
<caption xml:lang="uk">Вікно входу</caption>
<caption xml:lang="x-test">xxLogin screenxx</caption>
</screenshot>
</screenshots>
<content_rating type="oars-1.1">
<content_attribute id="social-chat">intense</content_attribute>
</content_rating>
<releases>
<release version="23.08.3" date="2023-11-09"/>
<release version="23.08.2" date="2023-10-12"/>
<release version="23.08.0" date="2023-08-24">
<url>https://kde.org/announcements/gear/23.08.0/#neochathttpsappskdeorgneochat</url>
<description>
<p>Apart from a visual overhaul, NeoChat can now display location events and also a map with the location of all the users currently broadcasting their location using Itineray's Matrix integration. Great for locating where your friends are.</p>
</description>
</release>
<release version="23.08.0" date="2023-08-24"/>
<release version="23.04.3" date="2023-07-06"/>
<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">
<url>https://kde.org/announcements/gear/23.04.0/#neochathttpsappskdeorgneochat</url>
<description>
<p>NeoChat improves its design with tweaks that provide a more compact layout and a simpler menu which works better for the collapsed room list.</p>
<p>We have also improved the video controls, added a new command /knock &lt;room-id&gt; to send a knock event to a room, and you can now edit a prior message inline, within the chat pane.</p>
<p>Other usability improvements include an overhaul of the keyboard navigation and shortcuts like Ctrl+PgUp/PgDn that allow you to skip from room to room.</p>
</description>
<artifacts>
<artifact type="binary" platform="x86_64-windows-msvc">
<location>https://download.kde.org/stable/release-service/23.04.0/windows/neochat-23.04.0-512-windows-cl-msvc2019-x86_64.exe</location>

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

@@ -1,225 +0,0 @@
# SPDX-FileCopyrightText: 2023 Scarlett Moore <sgmoore@kde.org>
#
# SPDX-License-Identifier: CC0-1.0
---
name: neochat
base: core22
adopt-info: neochat
grade: stable
confinement: strict
apps:
neochat:
# extensions:
# - kde-neon
command: usr/bin/neochat
common-id: org.kde.neochat
desktop: usr/share/applications/org.kde.neochat.desktop
plugs:
- home
- removable-media
- desktop
- desktop-legacy
- opengl
- wayland
- x11
- audio-playback
- unity7
- network
- network-bind
- network-manager-observe
- password-manager-service
- accounts-service
command-chain:
- snap/command-chain/desktop-launch
assumes:
- snapd2.58.3
compression: lzo
plugs:
desktop:
mount-host-font-cache: false
icon-themes:
interface: content
target: $SNAP/data-dir/icons
default-provider: gtk-common-themes
sound-themes:
interface: content
target: $SNAP/data-dir/sounds
default-provider: gtk-common-themes
kf5-5-111-qt-5-15-11-core22:
content: kf5-5-111-qt-5-15-11-core22-all
interface: content
default-provider: kf5-5-111-qt-5-15-11-core22
target: $SNAP/kf5
environment:
SNAP_DESKTOP_RUNTIME: $SNAP/kf5
QML2_IMPORT_PATH: "$SNAP/usr/lib/$CRAFT_ARCH_TRIPLET/qt5/qml:$SNAP/kf5/usr/lib/$CRAFT_ARCH_TRIPLET/qt5/qml:$SNAP/usr/lib/$CRAFT_ARCH_TRIPLET/qml"
QT_QUICK_CONTROLS_STYLE: org.kde.desktop
XDG_DATA_DIRS: "$SNAP/.local"
XDG_CONFIG_DIRS: "$SNAP/etc/xdg"
hooks:
configure:
plugs:
- desktop
command-chain:
- snap/command-chain/hooks-configure-desktop
layout:
/usr/share/X11:
symlink: $SNAP/kf5/usr/share/X11
slots:
session-dbus-interface:
interface: dbus
name: org.kde.neochat
bus: session
package-repositories:
- type: apt
components:
- main
suites:
- jammy
key-id: 444DABCF3667D0283F894EDDE6D4736255751E5D
url: http://origin.archive.neon.kde.org/user
key-server: keyserver.ubuntu.com
parts:
kde-neon:
source: /snap/snapcraft/current/share/snapcraft/extensions/desktop/kde-neon
source-type: local
plugin: make
make-parameters:
- PLATFORM_PLUG=kf5-5-111-qt-5-15-11-core22
build-snaps:
- kf5-5-111-qt-5-15-11-core22-sdk
build-environment:
- &id001
PATH: /snap/kf5-5-111-qt-5-15-11-core22-sdk/current/usr/bin${PATH:+:$PATH}
- &id002
XDG_DATA_DIRS: $CRAFT_STAGE/usr/share:/snap/kf5-5-111-qt-5-15-11-core22-sdk/current/usr/share:/usr/share${XDG_DATA_DIRS:+:$XDG_DATA_DIRS}
- &id003
XDG_CONFIG_HOME: $CRAFT_STAGE/etc/xdg:/snap/kf5-5-111-qt-5-15-11-core22-sdk/current/etc/xdg:/etc/xdg${XDG_CONFIG_HOME:+:$XDG_CONFIG_HOME}
- &id004
CRAFT_CMAKE_ARGS: -DCMAKE_FIND_ROOT_PATH=/snap/kf5-5-111-qt-5-15-11-core22-sdk/current${CRAFT_CMAKE_ARGS:+:$CRAFT_CMAKE_ARGS}
qtkeychain:
after:
- kde-neon
source: https://github.com/frankosterfeld/qtkeychain.git
source-tag: v0.14.0
source-depth: 0
plugin: cmake
build-packages:
- libsecret-1-dev
stage-packages:
- libsecret-1-0
- gnome-keyring
cmake-parameters:
- "-DKDE_INSTALL_USE_QT_SYS_PATHS=FALSE"
- "-DCMAKE_INSTALL_PREFIX=/usr"
- "-DCMAKE_BUILD_TYPE=RelWithDebInfo"
- "-DENABLE_TESTING=OFF"
- "-DBUILD_TESTING=OFF"
- "-DKDE_SKIP_TEST_SETTINGS=ON"
- "-DCMAKE_FIND_ROOT_PATH=$CRAFT_STAGE\\;/snap/kf5-5-111-qt-5-15-11-core22/current"
- "-DBUILD_TRANSLATIONS=OFF"
- "-DLIBSECRET_SUPPORT=ON"
- "-DKEYCHAIN_DBUS=1"
prime:
- "-usr/include/qt5keychain"
- "-usr/lib/$CRAFT_ARCH_TRIPLET/libqt5keychain.so"
- "-usr/mkspecs"
- "-usr/lib/$CRAFT_ARCH_TRIPLET/cmake"
libmatrixclient:
after:
- kde-neon
- qtkeychain
source: https://github.com/quotient-im/libQuotient.git
source-tag: 0.8.1.2
source-depth: 0
plugin: cmake
build-packages:
- qtmultimedia5-dev
- libolm-dev
- libssl-dev
cmake-parameters:
- "-DCMAKE_INSTALL_PREFIX=/usr"
- "-DCMAKE_BUILD_TYPE=RelWithDebInfo"
- "-DENABLE_TESTING=OFF"
- "-DBUILD_TESTING=OFF"
- "-DKDE_SKIP_TEST_SETTINGS=ON"
- "-DQuotient_ENABLE_E2EE=ON"
- "-DBUILDING_SHARED_QUOTIENT=ON"
- "-DCMAKE_FIND_ROOT_PATH=$CRAFT_STAGE\\;/snap/kf5-5-111-qt-5-15-11-core22/current"
neochat:
after:
- kde-neon
- qtkeychain
- libmatrixclient
parse-info:
- usr/share/metainfo/org.kde.neochat.appdata.xml
source: .
source-type: local
plugin: cmake
build-packages:
- cmark
- gcc-10
- g++-10
- libcmark-dev
- kquickimageeditor-dev
- libkf5qqc2desktopstyle-dev
- qcoro-qt5-dev
- kirigami-addons-dev
- reuse
- libkf5doctools-dev
- qtbase5-private-dev
- qml-module-org-kde-kquickimageeditor
- qml-module-org-kde-qqc2desktopstyle
- kirigami-addons-data
- qml-module-org-kde-kirigamiaddons
- qml-module-org-kde-quickcharts
- libsqlite3-dev
- libolm-dev
stage-packages:
- libcmark0.30.2
- qml-module-org-kde-kquickimageeditor
- qml-module-org-kde-qqc2desktopstyle
- kirigami-addons-data
- qml-module-org-kde-kirigamiaddons
- qml-module-org-kde-quickcharts
- qml-module-org-kde-kirigami2
- reuse
- libsqlite3-0
- libolm3
cmake-parameters:
- "-DKDE_INSTALL_USE_QT_SYS_PATHS=FALSE"
- "-DCMAKE_INSTALL_PREFIX=/usr"
- "-DCMAKE_BUILD_TYPE=Release"
- "-DENABLE_TESTING=OFF"
- "-DBUILD_TESTING=OFF"
- "-DKDE_SKIP_TEST_SETTINGS=ON"
- "-DNEOCHAT_FLATPAK=ON"
- "-DCMAKE_FIND_ROOT_PATH=$CRAFT_STAGE\\;/snap/kf5-5-111-qt-5-15-11-core22-sdk/current"
- "-DKDE_INSTALL_PLUGINDIR=/usr/lib/$CRAFT_ARCH_TRIPLET/qt5/plugins/"
prime:
- "-usr/lib/*/cmake/*"
- "-usr/include/*"
- "-usr/share/ECM/*"
- "-usr/share/doc/*"
- "-usr/share/man/*"
- "-usr/share/icons/breeze-dark*"
- "-usr/bin/X11"
- "-usr/lib/gcc/$CRAFT_ARCH_TRIPLET/6.0.0"
- "-usr/lib/aspell/*"
- "-usr/share/lintian"
build-environment: &id005
- *id001
- *id002
- *id003
- *id004
cleanup:
after:
- kde-neon
- neochat
plugin: nil
override-prime: |
set -eux
# find $CRAFT_PRIME/usr/share/doc/ -type f -not -name 'copyright' -delete
# find $CRAFT_PRIME/usr/share -type d -empty -delete | /bin/true
# # Unused libraries found by linter

View File

@@ -5,7 +5,6 @@
configure_file(qml/Page/RoomList/RoomDelegate.qml ${CMAKE_CURRENT_BINARY_DIR}/qml/Page/RoomList/RoomDelegate.qml)
configure_file(qml/Component/QuickSwitcher.qml ${CMAKE_CURRENT_BINARY_DIR}/qml/Component/QuickSwitcher.qml)
configure_file(qml/Dialog/UserDetailDialog.qml ${CMAKE_CURRENT_BINARY_DIR}/qml/Dialog/UserDetailDialog.qml)
configure_file(qml/Dialog/PowerLevelDialog.qml ${CMAKE_CURRENT_BINARY_DIR}/qml/Dialog/PowerLevelDialog.qml)
configure_file(qml/Component/Timeline/AudioDelegate.qml ${CMAKE_CURRENT_BINARY_DIR}/qml/Component/Timeline/AudioDelegate.qml)
configure_file(qml/Component/Timeline/VideoDelegate.qml ${CMAKE_CURRENT_BINARY_DIR}/qml/Component/Timeline/VideoDelegate.qml)
@@ -44,8 +43,6 @@ add_library(neochat STATIC
roommanager.h
neochatroom.cpp
neochatroom.h
neochatuser.cpp
neochatuser.h
models/userlistmodel.cpp
models/userlistmodel.h
models/userfiltermodel.cpp
@@ -127,6 +124,7 @@ add_library(neochat STATIC
locationhelper.h
events/pollevent.cpp
pollhandler.cpp
utils.h
)
ecm_qt_declare_logging_category(neochat
@@ -157,6 +155,9 @@ if(NOT ANDROID)
target_sources(neochat PRIVATE colorschemer.cpp colorschemer.h)
if (NOT WIN32 AND NOT APPLE)
target_sources(neochat PRIVATE trayicon_sni.cpp trayicon_sni.h)
if(QT_MAJOR_VERSION STREQUAL "6")
target_link_libraries(neochat PRIVATE KF6::StatusNotifierItem)
endif()
else()
target_sources(neochat PRIVATE trayicon.cpp trayicon.h)
endif()
@@ -175,7 +176,7 @@ else()
endif()
target_include_directories(neochat PRIVATE ${CMAKE_BINARY_DIR})
target_link_libraries(neochat PUBLIC Qt::Core Qt::Quick Qt::Qml Qt::Gui Qt::Multimedia Qt::Network Qt::QuickControls2 KF${QT_MAJOR_VERSION}::I18n KF${QT_MAJOR_VERSION}::Kirigami2 KF${QT_MAJOR_VERSION}::Notifications KF${QT_MAJOR_VERSION}::ConfigCore KF${QT_MAJOR_VERSION}::ConfigGui KF${QT_MAJOR_VERSION}::CoreAddons KF${QT_MAJOR_VERSION}::SonnetCore KF${QT_MAJOR_VERSION}::ItemModels Quotient${QUOTIENT_SUFFIX} cmark::cmark ${QTKEYCHAIN_LIBRARIES} QCoro::Core)
target_link_libraries(neochat PUBLIC Qt::Core Qt::Quick Qt::Qml Qt::Gui Qt::Multimedia Qt::Network Qt::QuickControls2 KF${QT_MAJOR_VERSION}::I18n KF${QT_MAJOR_VERSION}::Kirigami2 KF${QT_MAJOR_VERSION}::Notifications KF${QT_MAJOR_VERSION}::ConfigCore KF${QT_MAJOR_VERSION}::ConfigGui KF${QT_MAJOR_VERSION}::CoreAddons KF${QT_MAJOR_VERSION}::SonnetCore KF${QT_MAJOR_VERSION}::ItemModels Quotient${QUOTIENT_SUFFIX} cmark::cmark QCoro::Core)
kconfig_add_kcfg_files(neochat GENERATE_MOC neochatconfig.kcfgc)
if(NEOCHAT_FLATPAK)

View File

@@ -44,7 +44,7 @@ void ActionsHandler::handleNewMessage()
if (!m_room->chatBoxAttachmentPath().isEmpty()) {
QUrl url(m_room->chatBoxAttachmentPath());
auto path = url.isLocalFile() ? url.toLocalFile() : url.toString();
m_room->uploadFile(path, m_room->chatBoxText().isEmpty() ? path.mid(path.lastIndexOf('/') + 1) : m_room->chatBoxText());
m_room->uploadFile(QUrl(path), m_room->chatBoxText().isEmpty() ? path.mid(path.lastIndexOf(u'/') + 1) : m_room->chatBoxText());
m_room->setChatBoxAttachmentPath({});
m_room->setChatBoxText({});
return;
@@ -97,7 +97,7 @@ QString ActionsHandler::handleMentions(QString handledText, const bool &isEdit)
void ActionsHandler::handleMessage(const QString &text, QString handledText, const bool &isEdit)
{
if (NeoChatConfig::allowQuickEdit()) {
QRegularExpression sed("^s/([^/]*)/([^/]*)(/g)?$");
QRegularExpression sed(QStringLiteral("^s/([^/]*)/([^/]*)(/g)?$"));
auto match = sed.match(text);
if (match.hasMatch()) {
const QString regex = match.captured(1);
@@ -113,13 +113,13 @@ void ActionsHandler::handleMessage(const QString &text, QString handledText, con
} else {
originalString = event->plainBody();
}
if (flags == "/g") {
m_room->postHtmlMessage(handledText, originalString.replace(regex, replacement), event->msgtype(), "", event->id());
if (flags == "/g"_ls) {
m_room->postHtmlMessage(handledText, originalString.replace(regex, replacement), event->msgtype(), {}, event->id());
} else {
m_room->postHtmlMessage(handledText,
originalString.replace(originalString.indexOf(regex), regex.size(), replacement),
event->msgtype(),
"",
{},
event->id());
}
return;
@@ -133,7 +133,7 @@ void ActionsHandler::handleMessage(const QString &text, QString handledText, con
if (handledText.startsWith(QLatin1Char('/'))) {
for (const auto &action : ActionsModel::instance().allActions()) {
if (handledText.indexOf(action.prefix) == 1
&& (handledText.indexOf(" ") == action.prefix.length() + 1 || handledText.length() == action.prefix.length() + 1)) {
&& (handledText.indexOf(" "_ls) == action.prefix.length() + 1 || handledText.length() == action.prefix.length() + 1)) {
handledText = action.handle(handledText.mid(action.prefix.length() + 1).trimmed(), m_room);
if (action.messageType.has_value()) {
messageType = *action.messageType;
@@ -152,30 +152,30 @@ void ActionsHandler::handleMessage(const QString &text, QString handledText, con
textHandler.setData(handledText);
handledText = textHandler.handleSendText();
if (handledText.count("<p>") == 1 && handledText.count("</p>") == 1) {
handledText.remove("<p>");
handledText.remove("</p>");
if (handledText.count("<p>"_ls) == 1 && handledText.count("</p>"_ls) == 1) {
handledText.remove("<p>"_ls);
handledText.remove("</p>"_ls);
}
if (handledText.length() == 0) {
return;
}
m_room->postMessage(text, handledText, messageType, m_room->chatBoxReplyId(), isEdit ? m_room->chatBoxEditId() : "");
m_room->postMessage(text, handledText, messageType, m_room->chatBoxReplyId(), isEdit ? m_room->chatBoxEditId() : QString());
}
void ActionsHandler::checkEffects(const QString &text)
{
std::optional<QString> effect = std::nullopt;
if (text.contains("\u2744")) {
if (text.contains(QStringLiteral("\u2744"))) {
effect = QLatin1String("snowflake");
} else if (text.contains("\u1F386")) {
} else if (text.contains(QStringLiteral("\u1F386"))) {
effect = QLatin1String("fireworks");
} else if (text.contains("\u2F387")) {
} else if (text.contains(QStringLiteral("\u2F387"))) {
effect = QLatin1String("fireworks");
} else if (text.contains("\u1F389")) {
} else if (text.contains(QStringLiteral("\u1F389"))) {
effect = QLatin1String("confetti");
} else if (text.contains("\u1F38A")) {
} else if (text.contains(QStringLiteral("\u1F38A"))) {
effect = QLatin1String("confetti");
}
if (effect.has_value()) {

View File

@@ -225,7 +225,7 @@ void ChatDocumentHandler::complete(int index)
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);
cursor.insertText(name % " ");
cursor.insertText(name + QStringLiteral(" "));
cursor.setPosition(at);
cursor.setPosition(cursor.position() + name.size(), QTextCursor::KeepAnchor);
cursor.setKeepPositionOnInsert(true);
@@ -246,7 +246,7 @@ void ChatDocumentHandler::complete(int index)
QTextCursor cursor(document()->textDocument());
cursor.setPosition(at);
cursor.setPosition(cursorPosition(), QTextCursor::KeepAnchor);
cursor.insertText(alias % " ");
cursor.insertText(alias + QStringLiteral(" "));
cursor.setPosition(at);
cursor.setPosition(cursor.position() + alias.size(), QTextCursor::KeepAnchor);
cursor.setKeepPositionOnInsert(true);

View File

@@ -104,12 +104,12 @@ class ChatDocumentHandler : public QObject
/**
* @brief The color to highlight user mentions.
*/
Q_PROPERTY(QColor mentionColor READ mentionColor WRITE setMentionColor NOTIFY mentionColorChanged);
Q_PROPERTY(QColor mentionColor READ mentionColor WRITE setMentionColor NOTIFY mentionColorChanged)
/**
* @brief The color to highlight spelling errors.
*/
Q_PROPERTY(QColor errorColor READ errorColor WRITE setErrorColor NOTIFY errorColorChanged);
Q_PROPERTY(QColor errorColor READ errorColor WRITE setErrorColor NOTIFY errorColorChanged)
public:
explicit ChatDocumentHandler(QObject *parent = nullptr);

View File

@@ -35,15 +35,15 @@
#include <Quotient/connection.h>
#include <Quotient/csapi/content-repo.h>
#include <Quotient/csapi/logout.h>
#include <Quotient/csapi/notifications.h>
#include <Quotient/csapi/profile.h>
#include <Quotient/eventstats.h>
#include <Quotient/jobs/downloadfilejob.h>
#include <Quotient/qt_connection_util.h>
#include <Quotient/csapi/notifications.h>
#include <Quotient/eventstats.h>
#include <Quotient/user.h>
#include "neochatconfig.h"
#include "neochatroom.h"
#include "neochatuser.h"
#include "notificationsmanager.h"
#include "roommanager.h"
#include "windowcontroller.h"
@@ -60,7 +60,6 @@ Controller::Controller(QObject *parent)
: QObject(parent)
{
Connection::setRoomType<NeoChatRoom>();
Connection::setUserType<NeoChatUser>();
setApplicationProxy();
@@ -125,9 +124,21 @@ Controller &Controller::instance()
return _instance;
}
void Controller::showWindow()
void Controller::toggleWindow()
{
WindowController::instance().showAndRaiseWindow(QString());
auto &instance = WindowController::instance();
auto window = instance.window();
if (window->isVisible()) {
if (window->windowStates() & Qt::WindowMinimized) {
window->showNormal();
window->requestActivate();
} else {
window->close();
}
} else {
instance.showAndRaiseWindow({});
instance.window()->requestActivate();
}
}
void Controller::logout(Connection *conn, bool serverSideLogout)
@@ -137,7 +148,7 @@ void Controller::logout(Connection *conn, bool serverSideLogout)
return;
}
SettingsGroup("Accounts").remove(conn->userId());
SettingsGroup("Accounts"_ls).remove(conn->userId());
QKeychain::DeletePasswordJob job(qAppName());
job.setAutoDelete(true);
@@ -201,7 +212,7 @@ void Controller::dropConnection(Connection *c)
void Controller::invokeLogin()
{
const auto accounts = SettingsGroup("Accounts").childGroups();
const auto accounts = SettingsGroup("Accounts"_ls).childGroups();
QString id = NeoChatConfig::self()->activeConnection();
for (const auto &accountId : accounts) {
AccountSettings account{accountId};
@@ -215,7 +226,7 @@ void Controller::invokeLogin()
AccountSettings account{accountId};
QString accessToken;
if (accessTokenLoadingJob->error() == QKeychain::Error::NoError) {
accessToken = accessTokenLoadingJob->binaryData();
accessToken = QString::fromLatin1(accessTokenLoadingJob->binaryData());
} else {
return;
}
@@ -230,10 +241,10 @@ void Controller::invokeLogin()
}
});
connect(connection, &Connection::loginError, this, [this, connection](const QString &error, const QString &) {
if (error == "Unrecognised access token") {
if (error == "Unrecognised access token"_ls) {
Q_EMIT errorOccured(i18n("Login Failed: Access Token invalid or revoked"));
logout(connection, false);
} else if (error == "Connection closed") {
} else if (error == "Connection closed"_ls) {
Q_EMIT errorOccured(i18n("Login Failed: %1", error));
// Failed due to network connection issue. This might happen when the homeserver is
// temporary down, or the user trying to re-launch NeoChat in a network that cannot
@@ -331,7 +342,7 @@ bool Controller::supportSystemTray() const
#ifdef Q_OS_ANDROID
return false;
#else
QString de = getenv("XDG_CURRENT_DESKTOP");
auto de = QString::fromLatin1(qgetenv("XDG_CURRENT_DESKTOP"));
return de != QStringLiteral("GNOME") && de != QStringLiteral("Pantheon");
#endif
}
@@ -343,18 +354,18 @@ void Controller::changePassword(Connection *connection, const QString &currentPa
if (job->error() == 103) {
QJsonObject replyData = job->jsonData();
QJsonObject authData;
authData["session"] = replyData["session"];
authData["password"] = currentPassword;
authData["type"] = "m.login.password";
authData["user"] = connection->user()->id();
QJsonObject identifier = {{"type", "m.id.user"}, {"user", connection->user()->id()}};
authData["identifier"] = identifier;
authData["session"_ls] = replyData["session"_ls];
authData["password"_ls] = currentPassword;
authData["type"_ls] = "m.login.password"_ls;
authData["user"_ls] = connection->user()->id();
QJsonObject identifier = {{"type"_ls, "m.id.user"_ls}, {"user"_ls, connection->user()->id()}};
authData["identifier"_ls] = identifier;
NeochatChangePasswordJob *innerJob = connection->callApi<NeochatChangePasswordJob>(newPassword, false, authData);
connect(innerJob, &BaseJob::success, this, [this]() {
Q_EMIT passwordStatus(PasswordStatus::Success);
});
connect(innerJob, &BaseJob::failure, this, [innerJob, this]() {
if (innerJob->jsonData()["errcode"] == "M_FORBIDDEN") {
if (innerJob->jsonData()["errcode"_ls] == "M_FORBIDDEN"_ls) {
Q_EMIT passwordStatus(PasswordStatus::Wrong);
} else {
Q_EMIT passwordStatus(PasswordStatus::Other);
@@ -400,10 +411,10 @@ void Controller::setQuitOnLastWindowClosed()
if (NeoChatConfig::self()->systemTray()) {
m_trayIcon = new TrayIcon(this);
m_trayIcon->show();
connect(m_trayIcon, &TrayIcon::showWindow, this, &Controller::showWindow);
connect(m_trayIcon, &TrayIcon::toggleWindow, this, &Controller::toggleWindow);
} else {
if (m_trayIcon) {
disconnect(m_trayIcon, &TrayIcon::showWindow, this, &Controller::showWindow);
disconnect(m_trayIcon, &TrayIcon::toggleWindow, this, &Controller::toggleWindow);
delete m_trayIcon;
m_trayIcon = nullptr;
}
@@ -449,7 +460,7 @@ void Controller::setActiveConnection(Connection *connection)
Q_EMIT isOnlineChanged(true);
});
connect(connection, &Connection::requestFailed, this, [](BaseJob *job) {
if (dynamic_cast<DownloadFileJob *>(job) && job->jsonData()["errcode"].toString() == "M_TOO_LARGE"_ls) {
if (dynamic_cast<DownloadFileJob *>(job) && job->jsonData()["errcode"_ls].toString() == "M_TOO_LARGE"_ls) {
RoomManager::instance().warning(i18n("File too large to download."), i18n("Contact your matrix server administrator for support."));
}
});
@@ -487,7 +498,7 @@ NeochatDeleteDeviceJob::NeochatDeleteDeviceJob(const QString &deviceId, const Om
void Controller::createRoom(const QString &name, const QString &topic)
{
auto createRoomJob = m_connection->createRoom(Connection::PublishRoom, "", name, topic, QStringList());
auto createRoomJob = m_connection->createRoom(Connection::PublishRoom, QString(), name, topic, QStringList());
connect(createRoomJob, &CreateRoomJob::failure, this, [this, createRoomJob] {
Q_EMIT errorOccured(i18n("Room creation failed: %1", createRoomJob->errorString()));
});
@@ -523,16 +534,16 @@ bool Controller::isOnline() const
// TODO: Remove in favor of RoomManager::joinRoom
void Controller::joinRoom(const QString &alias)
{
if (!alias.contains(":")) {
if (!alias.contains(":"_ls)) {
Q_EMIT errorOccured(i18n("The room id you are trying to join is not valid"));
return;
}
const auto knownServer = alias.mid(alias.indexOf(":") + 1);
const auto knownServer = alias.mid(alias.indexOf(":"_ls) + 1);
RoomManager::instance().joinRoom(m_connection, alias, QStringList{knownServer});
}
void Controller::openOrCreateDirectChat(NeoChatUser *user)
void Controller::openOrCreateDirectChat(User *user)
{
const auto existing = activeConnection()->directChats();
@@ -582,11 +593,6 @@ bool Controller::hasWindowSystem() const
#endif
}
bool Controller::encryptionSupported() const
{
return Quotient::encryptionSupported();
}
void Controller::forceRefreshTextDocument(QQuickTextDocument *textDocument, QQuickItem *item)
{
// HACK: Workaround bug QTBUG 93281
@@ -631,12 +637,6 @@ int Controller::activeConnectionIndex() const
return result - m_accountRegistry.accounts().begin();
}
int Controller::quotientMinorVersion() const
{
// TODO libQuotient 0.7: Replace with version function from libQuotient
return 7;
}
bool Controller::isFlatpak() const
{
#ifdef NEOCHAT_FLATPAK
@@ -652,9 +652,9 @@ void Controller::setActiveAccountLabel(const QString &label)
return;
}
QJsonObject json{
{"account_label", label},
{"account_label"_ls, label},
};
m_connection->setAccountData("org.kde.neochat.account_label", json);
m_connection->setAccountData("org.kde.neochat.account_label"_ls, json);
}
QString Controller::activeAccountLabel() const
@@ -662,7 +662,7 @@ QString Controller::activeAccountLabel() const
if (!m_connection) {
return {};
}
return m_connection->accountDataJson("org.kde.neochat.account_label")["account_label"].toString();
return m_connection->accountDataJson("org.kde.neochat.account_label"_ls)["account_label"_ls].toString();
}
QVariantList Controller::getSupportedRoomVersions(Quotient::Connection *connection)
@@ -672,9 +672,9 @@ QVariantList Controller::getSupportedRoomVersions(Quotient::Connection *connecti
QVariantList supportedRoomVersions;
for (const Quotient::Connection::SupportedRoomVersion &v : roomVersions) {
QVariantMap roomVersionMap;
roomVersionMap.insert("id", v.id);
roomVersionMap.insert("status", v.status);
roomVersionMap.insert("isStable", v.isStable());
roomVersionMap.insert("id"_ls, v.id);
roomVersionMap.insert("status"_ls, v.status);
roomVersionMap.insert("isStable"_ls, v.isStable());
supportedRoomVersions.append(roomVersionMap);
}

View File

@@ -14,7 +14,6 @@
#include <Quotient/settings.h>
class NeoChatRoom;
class NeoChatUser;
class TrayIcon;
class QWindow;
class QQuickTextDocument;
@@ -23,6 +22,7 @@ namespace Quotient
{
class Connection;
class Room;
class User;
}
namespace QKeychain
@@ -87,20 +87,6 @@ class Controller : public QObject
*/
Q_PROPERTY(bool isOnline READ isOnline NOTIFY isOnlineChanged)
/**
* @brief Whether the ecryption support has been enabled.
*/
Q_PROPERTY(bool encryptionSupported READ encryptionSupported CONSTANT)
/**
* @brief The current minor version number of libQuotient being used.
*
* This is the only way to gate NeoChat features by libQuotient version in QML.
*
* @note No major version because libQuotient doesn't have any; All are 0.x.
*/
Q_PROPERTY(int quotientMinorVersion READ quotientMinorVersion CONSTANT)
/**
* @brief Whether NeoChat is running as a flatpak.
*
@@ -183,7 +169,7 @@ public:
*
* If a direct chat with the user doesn't exist one is created and then joined.
*/
Q_INVOKABLE void openOrCreateDirectChat(NeoChatUser *user);
Q_INVOKABLE void openOrCreateDirectChat(Quotient::User *user);
[[nodiscard]] bool supportSystemTray() const;
@@ -194,8 +180,6 @@ public:
bool isOnline() const;
bool encryptionSupported() const;
/**
* @brief Sets the QNetworkProxy for the application.
*
@@ -203,8 +187,6 @@ public:
*/
Q_INVOKABLE void setApplicationProxy();
int quotientMinorVersion() const;
bool isFlatpak() const;
/**
@@ -252,7 +234,7 @@ private:
private Q_SLOTS:
void invokeLogin();
void showWindow();
void toggleWindow();
void setQuitOnLastWindowClosed();
Q_SIGNALS:

File diff suppressed because it is too large Load Diff

View File

@@ -10,29 +10,29 @@ ImagePackEventContent::ImagePackEventContent(const QJsonObject &json)
{
if (json.contains(QStringLiteral("pack"))) {
pack = ImagePackEventContent::Pack{
fromJson<Omittable<QString>>(json["pack"].toObject()["display_name"]),
fromJson<Omittable<QUrl>>(json["pack"].toObject()["avatar_url"]),
fromJson<Omittable<QStringList>>(json["pack"].toObject()["usage"]),
fromJson<Omittable<QString>>(json["pack"].toObject()["attribution"]),
fromJson<Omittable<QString>>(json["pack"_ls].toObject()["display_name"_ls]),
fromJson<Omittable<QUrl>>(json["pack"_ls].toObject()["avatar_url"_ls]),
fromJson<Omittable<QStringList>>(json["pack"_ls].toObject()["usage"_ls]),
fromJson<Omittable<QString>>(json["pack"_ls].toObject()["attribution"_ls]),
};
} else {
pack = none;
}
const auto &keys = json["images"].toObject().keys();
const auto &keys = json["images"_ls].toObject().keys();
for (const auto &k : keys) {
Omittable<EventContent::ImageInfo> info;
if (json["images"][k].toObject().contains(QStringLiteral("info"))) {
info = EventContent::ImageInfo(QUrl(json["images"][k]["url"].toString()), json["images"][k]["info"].toObject(), k);
if (json["images"_ls][k].toObject().contains(QStringLiteral("info"))) {
info = EventContent::ImageInfo(QUrl(json["images"_ls][k]["url"_ls].toString()), json["images"_ls][k]["info"_ls].toObject(), k);
} else {
info = none;
}
images += ImagePackImage{
k,
fromJson<QUrl>(json["images"][k]["url"].toString()),
fromJson<Omittable<QString>>(json["images"][k]["body"]),
fromJson<QUrl>(json["images"_ls][k]["url"_ls].toString()),
fromJson<Omittable<QString>>(json["images"_ls][k]["body"_ls]),
info,
fromJson<Omittable<QStringList>>(json["images"][k]["usage"]),
fromJson<Omittable<QStringList>>(json["images"_ls][k]["usage"_ls]),
};
}
}
@@ -42,20 +42,20 @@ void ImagePackEventContent::fillJson(QJsonObject *o) const
if (pack) {
QJsonObject packJson;
if (pack->displayName) {
packJson["display_name"] = *pack->displayName;
packJson["display_name"_ls] = *pack->displayName;
}
if (pack->usage) {
QJsonArray usageJson;
for (const auto &usage : *pack->usage) {
usageJson += usage;
}
packJson["usage"] = usageJson;
packJson["usage"_ls] = usageJson;
}
if (pack->avatarUrl) {
packJson["avatar_url"] = pack->avatarUrl->toString();
packJson["avatar_url"_ls] = pack->avatarUrl->toString();
}
if (pack->attribution) {
packJson["attribution"] = *pack->attribution;
packJson["attribution"_ls] = *pack->attribution;
}
(*o)["pack"_ls] = packJson;
}
@@ -63,16 +63,16 @@ void ImagePackEventContent::fillJson(QJsonObject *o) const
QJsonObject imagesJson;
for (const auto &image : images) {
QJsonObject imageJson;
imageJson["url"] = image.url.toString();
imageJson["url"_ls] = image.url.toString();
if (image.body) {
imageJson["body"] = *image.body;
imageJson["body"_ls] = *image.body;
}
if (image.usage) {
QJsonArray usageJson;
for (const auto &usage : *image.usage) {
usageJson += usage;
}
imageJson["usage"] = usageJson;
imageJson["usage"_ls] = usageJson;
}
imagesJson[image.shortcode] = imageJson;
}

View File

@@ -12,12 +12,12 @@ PollStartEvent::PollStartEvent(const QJsonObject &obj)
int PollStartEvent::maxSelections() const
{
return contentJson()["org.matrix.msc3381.poll.start"]["max_selections"].toInt();
return contentJson()["org.matrix.msc3381.poll.start"_ls]["max_selections"_ls].toInt();
}
QString PollStartEvent::question() const
{
return contentJson()["org.matrix.msc3381.poll.start"]["question"]["body"].toString();
return contentJson()["org.matrix.msc3381.poll.start"_ls]["question"_ls]["body"_ls].toString();
}
PollResponseEvent::PollResponseEvent(const QJsonObject &obj)
@@ -32,7 +32,7 @@ PollEndEvent::PollEndEvent(const QJsonObject &obj)
PollResponseEvent::PollResponseEvent(const QString &pollStartEventId, QStringList responses)
: RoomEvent(basicJson(TypeId,
{{"org.matrix.msc3381.poll.response", QJsonObject{{"answers", QJsonArray::fromStringList(responses)}}},
{"m.relates_to", QJsonObject{{"rel_type", "m.reference"}, {"event_id", pollStartEventId}}}}))
{{"org.matrix.msc3381.poll.response"_ls, QJsonObject{{"answers"_ls, QJsonArray::fromStringList(responses)}}},
{"m.relates_to"_ls, QJsonObject{{"rel_type"_ls, "m.reference"_ls}, {"event_id"_ls, pollStartEventId}}}}))
{
}

View File

@@ -62,14 +62,14 @@ void LinkPreviewer::loadUrlPreview()
Q_EMIT loadedChanged();
auto conn = m_currentRoom->connection();
GetUrlPreviewJob *job = conn->callApi<GetUrlPreviewJob>(m_url.toString());
GetUrlPreviewJob *job = conn->callApi<GetUrlPreviewJob>(m_url);
connect(job, &BaseJob::success, this, [this, job, conn]() {
const auto json = job->jsonData();
m_title = json["og:title"].toString().trimmed();
m_description = json["og:description"].toString().trimmed().replace("\n", " ");
m_title = json["og:title"_ls].toString().trimmed();
m_description = json["og:description"_ls].toString().trimmed().replace("\n"_ls, " "_ls);
auto imageUrl = QUrl(json["og:image"].toString());
auto imageUrl = QUrl(json["og:image"_ls].toString());
if (imageUrl.isValid() && imageUrl.scheme() == QStringLiteral("mxc")) {
m_imageSource = conn->makeMediaUrl(imageUrl);
} else {

View File

@@ -87,32 +87,32 @@ public:
QMutexLocker locker(&mutex);
QByteArray buf;
QTextStream str(&buf);
str << QDateTime::currentDateTime().toString(Qt::ISODate) << " [";
str << QDateTime::currentDateTime().toString(Qt::ISODate) << QStringLiteral(" [");
switch (type) {
case QtDebugMsg:
str << "DEBUG";
str << QStringLiteral("DEBUG");
break;
case QtInfoMsg:
str << "INFO ";
str << QStringLiteral("INFO ");
break;
case QtWarningMsg:
str << "WARN ";
str << QStringLiteral("WARN ");
break;
case QtFatalMsg:
str << "FATAL";
str << QStringLiteral("FATAL");
break;
case QtCriticalMsg:
str << "CRITICAL";
str << QStringLiteral("CRITICAL");
break;
}
str << "] " << context.category << ": ";
str << QStringLiteral("] ") << context.category << QStringLiteral(": ");
if (context.file && *context.file && context.line) {
str << context.file << ":" << context.line << ": ";
str << context.file << QStringLiteral(":") << context.line << QStringLiteral(": ");
}
if (context.function && *context.function) {
str << context.function << ": ";
str << context.function << QStringLiteral(": ");
}
str << message << "\n";
str << message << QStringLiteral("\n");
str.flush();
file.write(buf.constData(), buf.size());
file.flush();
@@ -129,18 +129,18 @@ public:
if (file.isOpen()) {
file.close();
}
auto filePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator() + appName;
const auto &filePath = QStringLiteral("%1%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), QDir::separator(), appName);
QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator());
auto entryList = dir.entryList({appName + QStringLiteral(".*")});
std::sort(entryList.begin(), entryList.end(), [](const auto &left, const auto &right) {
auto leftIndex = left.split(".").last().toInt();
auto rightIndex = right.split(".").last().toInt();
auto leftIndex = left.split(QStringLiteral(".")).last().toInt();
auto rightIndex = right.split(QStringLiteral(".")).last().toInt();
return leftIndex > rightIndex;
});
for (const auto &entry : entryList) {
bool ok = false;
const auto index = entry.split(".").last().toInt(&ok);
const auto index = entry.split(QStringLiteral(".")).last().toInt(&ok);
if (!ok) {
continue;
}
@@ -151,8 +151,8 @@ public:
file.remove();
continue;
}
const QString newName = filePath + QStringLiteral(".%1").arg(index + 1);
const bool success = file.copy(newName);
const auto &newName = QStringLiteral("%1.%2").arg(filePath, QString::number(index + 1));
const auto success = file.copy(newName);
if (success) {
file.remove();
} else {
@@ -216,7 +216,7 @@ void initLogging()
oldCategoryFilter = QLoggingCategory::installFilter(filter);
oldHandler = qInstallMessageHandler(messageHandler);
sInstance->setOrigHandler(oldHandler);
sInstance->setName("neochat.log");
sInstance->setName(QStringLiteral("neochat.log"));
}
#include "logger.moc"

View File

@@ -33,12 +33,12 @@ 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]+)?$");
QRegularExpression validator(QStringLiteral("^\\@?[a-zA-Z0-9\\._=\\-/]+\\:[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]+)*(\\:[0-9]+)?$"));
if (!validator.match(m_matrixId).hasMatch()) {
return;
}
if (m_matrixId == "@") {
if (m_matrixId == QLatin1Char('@')) {
return;
}
@@ -120,8 +120,8 @@ QString Login::matrixId() const
void Login::setMatrixId(const QString &matrixId)
{
m_matrixId = matrixId;
if (!m_matrixId.startsWith('@')) {
m_matrixId.prepend('@');
if (!m_matrixId.startsWith(QLatin1Char('@'))) {
m_matrixId.prepend(QLatin1Char('@'));
}
Q_EMIT matrixIdChanged();
}
@@ -155,7 +155,7 @@ void Login::login()
// Some servers do not have a .well_known file. So we login via the username part from the mxid,
// rather than with the full mxid, as that would lead to an invalid user.
auto username = m_matrixId.mid(1, m_matrixId.indexOf(":") - 1);
auto username = m_matrixId.mid(1, m_matrixId.indexOf(QLatin1Char(':')) - 1);
m_connection->loginWithPassword(username, m_password, m_deviceName, QString());
}

View File

@@ -3,7 +3,9 @@
#include <QCommandLineParser>
#include <QIcon>
#include <QNetworkDiskCache>
#include <QNetworkProxyFactory>
#include <QObject>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQmlNetworkAccessManagerFactory>
@@ -28,10 +30,11 @@
#include "neochat-version.h"
#include <Quotient/keyverificationsession.h>
#include <Quotient/accountregistry.h>
#include <Quotient/keyverificationsession.h>
#include <Quotient/networkaccessmanager.h>
#include <Quotient/room.h>
#include <Quotient/user.h>
#include <Quotient/util.h>
#include "actionshandler.h"
@@ -75,7 +78,6 @@
#include "models/webshortcutmodel.h"
#include "neochatconfig.h"
#include "neochatroom.h"
#include "neochatuser.h"
#include "notificationsmanager.h"
#include "pollhandler.h"
#include "roommanager.h"
@@ -88,7 +90,6 @@
#endif
#include "models/completionmodel.h"
#include "models/statemodel.h"
#include "neochatuser.h"
#ifdef HAVE_RUNNER
#include "runner.h"
@@ -105,7 +106,17 @@ class NetworkAccessManagerFactory : public QQmlNetworkAccessManagerFactory
{
QNetworkAccessManager *create(QObject *) override
{
return NetworkAccessManager::instance();
auto nam = NetworkAccessManager::instance();
nam->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
nam->enableStrictTransportSecurityStore(true, QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1String("/hsts/"));
nam->setStrictTransportSecurityEnabled(true);
auto namDiskCache = new QNetworkDiskCache(nam);
namDiskCache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1String("/nam/"));
nam->setCache(namDiskCache);
return nam;
}
};
@@ -132,7 +143,7 @@ int main(int argc, char *argv[])
QGuiApplication app(argc, argv);
QQuickStyle::setStyle(QStringLiteral("org.kde.breeze"));
#else
QIcon::setFallbackThemeName("breeze");
QIcon::setFallbackThemeName("breeze"_ls);
QApplication app(argc, argv);
// Default to org.kde.desktop style unless the user forces another style
if (qEnvironmentVariableIsEmpty("QT_QUICK_CONTROLS_STYLE")) {
@@ -154,7 +165,7 @@ int main(int argc, char *argv[])
#endif
KLocalizedString::setApplicationDomain("neochat");
QGuiApplication::setOrganizationName("KDE");
QGuiApplication::setOrganizationName("KDE"_ls);
KAboutData about(QStringLiteral("neochat"),
i18n("NeoChat"),
@@ -185,15 +196,14 @@ int main(int argc, char *argv[])
initLogging();
#if Quotient_VERSION_MINOR == 8
#ifdef Quotient_E2EE_ENABLED
Connection::setEncryptionDefault(true);
#endif
#endif
#ifdef NEOCHAT_FLATPAK
// Copy over the included FontConfig configuration to the
// app's config dir:
QFile::copy("/app/etc/fonts/conf.d/99-noto-mono-color-emoji.conf", "/var/config/fontconfig/conf.d/99-noto-mono-color-emoji.conf");
QFile::copy(QStringLiteral("/app/etc/fonts/conf.d/99-noto-mono-color-emoji.conf"),
QStringLiteral("/var/config/fontconfig/conf.d/99-noto-mono-color-emoji.conf"));
#endif
Clipboard clipboard;
@@ -255,13 +265,13 @@ int main(int argc, char *argv[])
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<PushNotificationKind>("org.kde.neochat", 1, 0, "PushNotificationKind", "ENUM");
qmlRegisterUncreatableType<PushNotificationSection>("org.kde.neochat", 1, 0, "PushNotificationSection", "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<RoomMessageEvent>("org.kde.neochat", 1, 0, "RoomMessageEvent", "ENUM"_ls);
qmlRegisterUncreatableType<PushNotificationKind>("org.kde.neochat", 1, 0, "PushNotificationKind", "ENUM"_ls);
qmlRegisterUncreatableType<PushNotificationSection>("org.kde.neochat", 1, 0, "PushNotificationSection", "ENUM"_ls);
qmlRegisterUncreatableType<PushNotificationState>("org.kde.neochat", 1, 0, "PushNotificationState", "ENUM"_ls);
qmlRegisterUncreatableType<PushNotificationAction>("org.kde.neochat", 1, 0, "PushNotificationAction", "ENUM"_ls);
qmlRegisterUncreatableType<NeoChatRoomType>("org.kde.neochat", 1, 0, "NeoChatRoomType", "ENUM"_ls);
qmlRegisterUncreatableType<User>("org.kde.neochat", 1, 0, "User", {});
qmlRegisterUncreatableType<NeoChatRoom>("org.kde.neochat", 1, 0, "NeoChatRoom", {});
qRegisterMetaType<User *>("User*");
@@ -271,18 +281,16 @@ int main(int argc, char *argv[])
qRegisterMetaType<Connection *>("Connection*");
qRegisterMetaType<MessageEventType>("MessageEventType");
qRegisterMetaType<NeoChatRoom *>("NeoChatRoom*");
qRegisterMetaType<NeoChatUser *>("NeoChatUser*");
qRegisterMetaType<User *>("User*");
qRegisterMetaType<GetRoomEventsJob *>("GetRoomEventsJob*");
qRegisterMetaType<QMimeType>("QMimeType");
#ifdef Quotient_E2EE_ENABLED
qRegisterMetaType<KeyVerificationSession *>("KeyVerificationSession*");
qmlRegisterUncreatableType<KeyVerificationSession>("org.kde.neochat", 1, 0, "KeyVerificationSession", {});
qRegisterMetaType<QVector<EmojiEntry>>("QVector<EmojiEntry>");
#endif
qmlRegisterSingletonType("org.kde.neochat", 1, 0, "About", [](QQmlEngine *engine, QJSEngine *) -> QJSValue {
return engine->toScriptValue(KAboutData::applicationData());
});
qmlRegisterSingletonType(QUrl("qrc:/OsmLocationPlugin.qml"), "org.kde.neochat", 1, 0, "OsmLocationPlugin");
qmlRegisterSingletonType(QUrl("qrc:/OsmLocationPlugin.qml"_ls), "org.kde.neochat", 1, 0, "OsmLocationPlugin");
qmlRegisterSingletonType("org.kde.neochat", 1, 0, "LocationHelper", [](QQmlEngine *engine, QJSEngine *) -> QJSValue {
return engine->toScriptValue(LocationHelper());
});
@@ -325,11 +333,18 @@ int main(int argc, char *argv[])
QCommandLineParser parser;
parser.setApplicationDescription(i18n("Client for the matrix communication protocol"));
parser.addPositionalArgument(QStringLiteral("urls"), i18n("Supports matrix: url scheme"));
parser.addOption(QCommandLineOption("ignore-ssl-errors"_ls, i18n("Ignore all SSL Errors, e.g., unsigned certificates.")));
about.setupCommandLine(&parser);
parser.process(app);
about.processCommandLine(&parser);
if (parser.isSet("ignore-ssl-errors"_ls)) {
QObject::connect(NetworkAccessManager::instance(), &QNetworkAccessManager::sslErrors, NetworkAccessManager::instance(), [](QNetworkReply *reply) {
reply->ignoreSslErrors();
});
}
engine.addImageProvider(QLatin1String("mxc"), new MatrixImageProvider);
engine.addImageProvider(QLatin1String("blurhash"), new BlurhashImageProvider);
@@ -344,7 +359,7 @@ int main(int argc, char *argv[])
#ifdef HAVE_RUNNER
Runner runner;
QDBusConnection::sessionBus().registerObject("/RoomRunner", &runner, QDBusConnection::ExportScriptableContents);
QDBusConnection::sessionBus().registerObject("/RoomRunner"_ls, &runner, QDBusConnection::ExportScriptableContents);
#endif
QWindow *window = windowFromEngine(&engine);

View File

@@ -25,13 +25,13 @@ ThumbnailResponse::ThumbnailResponse(QString id, QSize size)
mediaId,
QString::number(requestedSize.width()),
QString::number(requestedSize.height())))
, errorStr("Image request hasn't started")
, errorStr("Image request hasn't started"_ls)
{
if (requestedSize.isEmpty()) {
requestedSize.setHeight(100);
requestedSize.setWidth(100);
}
if (mediaId.count('/') != 1) {
if (mediaId.count(QLatin1Char('/')) != 1) {
if (mediaId.startsWith(QLatin1Char('/'))) {
mediaId = mediaId.mid(1);
} else {

View File

@@ -138,7 +138,7 @@ QCoro::Task<void> AccountEmoticonModel::doSetEmoticonImage(int index, QUrl sourc
if (job->error() != BaseJob::NoError) {
co_return;
}
m_images->images[index].url = job->contentUri().toString();
m_images->images[index].url = job->contentUri();
m_images->images[index].info = none;
QJsonObject data;
m_images->fillJson(&data);

View File

@@ -14,9 +14,10 @@
using Action = ActionsModel::Action;
using namespace Quotient;
QStringList rainbowColors{"#ff2b00", "#ff5500", "#ff8000", "#ffaa00", "#ffd500", "#ffff00", "#d4ff00", "#aaff00", "#80ff00", "#55ff00", "#2bff00", "#00ff00",
"#00ff2b", "#00ff55", "#00ff80", "#00ffaa", "#00ffd5", "#00ffff", "#00d4ff", "#00aaff", "#007fff", "#0055ff", "#002bff", "#0000ff",
"#2a00ff", "#5500ff", "#7f00ff", "#aa00ff", "#d400ff", "#ff00ff", "#ff00d4", "#ff00aa", "#ff0080", "#ff0055", "#ff002b", "#ff0000"};
QStringList rainbowColors{"#ff2b00"_ls, "#ff5500"_ls, "#ff8000"_ls, "#ffaa00"_ls, "#ffd500"_ls, "#ffff00"_ls, "#d4ff00"_ls, "#aaff00"_ls, "#80ff00"_ls,
"#55ff00"_ls, "#2bff00"_ls, "#00ff00"_ls, "#00ff2b"_ls, "#00ff55"_ls, "#00ff80"_ls, "#00ffaa"_ls, "#00ffd5"_ls, "#00ffff"_ls,
"#00d4ff"_ls, "#00aaff"_ls, "#007fff"_ls, "#0055ff"_ls, "#002bff"_ls, "#0000ff"_ls, "#2a00ff"_ls, "#5500ff"_ls, "#7f00ff"_ls,
"#aa00ff"_ls, "#d400ff"_ls, "#ff00ff"_ls, "#ff00d4"_ls, "#ff00aa"_ls, "#ff0080"_ls, "#ff0055"_ls, "#ff002b"_ls, "#ff0000"_ls};
auto leaveRoomLambda = [](const QString &text, NeoChatRoom *room) {
if (text.isEmpty()) {
@@ -260,7 +261,7 @@ QVector<ActionsModel::Action> actions{
}
Q_EMIT room->showMessage(NeoChatRoom::Info, i18nc("Knocking room <roomname>.", "Knocking room %1.", text));
auto connection = Controller::instance().activeConnection();
const auto knownServer = roomName.mid(roomName.indexOf(":") + 1);
const auto knownServer = roomName.mid(roomName.indexOf(":"_ls) + 1);
if (parts.length() >= 2) {
RoomManager::instance().knockRoom(connection, roomName, parts[1], QStringList{knownServer});
} else {
@@ -450,7 +451,7 @@ QVector<ActionsModel::Action> actions{
i18nc("You are not allowed to ban <username> from this room.", "You are not allowed to ban %1 from this room.", parts[0]));
return QString();
}
room->ban(parts[0], parts.size() > 1 ? parts.mid(1).join(" ") : QString());
room->ban(parts[0], parts.size() > 1 ? parts.mid(1).join(QLatin1Char(' ')) : QString());
Q_EMIT room->showMessage(NeoChatRoom::Positive, i18nc("<username> was banned from this room.", "%1 was banned from this room.", parts[0]));
return QString();
},
@@ -527,7 +528,7 @@ QVector<ActionsModel::Action> actions{
i18nc("You are not allowed to kick <username> from this room", "You are not allowed to kick %1 from this room.", parts[0]));
return QString();
}
room->kickMember(parts[0], parts.size() > 1 ? parts.mid(1).join(" ") : QString());
room->kickMember(parts[0], parts.size() > 1 ? parts.mid(1).join(QLatin1Char(' ')) : QString());
Q_EMIT room->showMessage(NeoChatRoom::Positive, i18nc("<username> was kicked from this room.", "%1 was kicked from this room.", parts[0]));
return QString();
},

View File

@@ -75,13 +75,13 @@ QString CollapseStateProxyModel::aggregateEventToString(int sourceRow) const
}
}
chunks.removeDuplicates();
QString text = "<style>a {text-decoration: none;}</style>"; // There can be links in the event text so make sure all are styled.
QString text = QStringLiteral("<style>a {text-decoration: none;}</style>"); // There can be links in the event text so make sure all are styled.
// The author text is either "n users" if > 1 user or the matrix.to link to a single user.
QString userText = uniqueAuthors.length() > 1 ? i18ncp("n users", " %1 user ", " %1 users ", uniqueAuthors.length())
: QStringLiteral("<a href=\"https://matrix.to/#/%1\" style=\"color: %2\">%3</a> ")
.arg(uniqueAuthors[0].toMap()["id"].toString(),
uniqueAuthors[0].toMap()["color"].toString(),
uniqueAuthors[0].toMap()["displayName"].toString().toHtmlEscaped());
.arg(uniqueAuthors[0].toMap()[QStringLiteral("id")].toString(),
uniqueAuthors[0].toMap()[QStringLiteral("color")].toString(),
uniqueAuthors[0].toMap()[QStringLiteral("displayName")].toString().toHtmlEscaped());
text += userText;
text += chunks.takeFirst();
@@ -104,9 +104,9 @@ QVariantList CollapseStateProxyModel::stateEventsList(int sourceRow) const
QVariantList stateEvents;
for (int i = sourceRow; i >= 0; i--) {
auto nextState = QVariantMap{
{"author", sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorRole)},
{"authorDisplayName", sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorDisplayNameRole).toString()},
{"text", sourceModel()->data(sourceModel()->index(i, 0), Qt::DisplayRole).toString()},
{QStringLiteral("author"), sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorRole)},
{QStringLiteral("authorDisplayName"), sourceModel()->data(sourceModel()->index(i, 0), MessageEventModel::AuthorDisplayNameRole).toString()},
{QStringLiteral("text"), sourceModel()->data(sourceModel()->index(i, 0), Qt::DisplayRole).toString()},
};
stateEvents.append(nextState);
if (i > 0

View File

@@ -66,8 +66,8 @@ QVariant CompletionModel::data(const QModelIndex &index, int role) const
if (m_autoCompletionType == Command) {
if (role == DisplayNameRole) {
return m_filterModel->data(filterIndex, ActionsModel::Prefix).toString() + QStringLiteral(" ")
+ m_filterModel->data(filterIndex, ActionsModel::Parameters).toString();
return QStringLiteral("%1 %2").arg(m_filterModel->data(filterIndex, ActionsModel::Prefix).toString(),
m_filterModel->data(filterIndex, ActionsModel::Parameters).toString());
}
if (role == SubtitleRole) {
return m_filterModel->data(filterIndex, ActionsModel::Description);
@@ -87,7 +87,8 @@ QVariant CompletionModel::data(const QModelIndex &index, int role) const
return m_filterModel->data(filterIndex, RoomListModel::CanonicalAliasRole);
}
if (role == IconNameRole) {
return m_filterModel->data(filterIndex, RoomListModel::AvatarRole);
return QStringLiteral("mxc://%1")
.arg(m_roomListModel->connection()->makeMediaUrl(m_filterModel->data(filterIndex, RoomListModel::AvatarRole).toUrl()).toString());
}
}
if (m_autoCompletionType == Emoji) {

View File

@@ -40,12 +40,12 @@ class CompletionModel : public QAbstractListModel
*
* @sa AutoCompletionType
*/
Q_PROPERTY(AutoCompletionType autoCompletionType READ autoCompletionType NOTIFY autoCompletionTypeChanged);
Q_PROPERTY(AutoCompletionType autoCompletionType READ autoCompletionType NOTIFY autoCompletionTypeChanged)
/**
* @brief The RoomListModel to be used for room completions.
*/
Q_PROPERTY(RoomListModel *roomListModel READ roomListModel WRITE setRoomListModel NOTIFY roomListModelChanged);
Q_PROPERTY(RoomListModel *roomListModel READ roomListModel WRITE setRoomListModel NOTIFY roomListModelChanged)
public:
/**

View File

@@ -11,6 +11,11 @@ bool CompletionProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &so
if (m_filterText.isEmpty()) {
return false;
}
if (sourceModel()->data(sourceModel()->index(sourceRow, 0), filterRole()).toString().isEmpty()) {
return false;
}
return (sourceModel()->data(sourceModel()->index(sourceRow, 0), filterRole()).toString().startsWith(m_filterText, Qt::CaseInsensitive)
&& !m_fullText.startsWith(sourceModel()->data(sourceModel()->index(sourceRow, 0), filterRole()).toString()))
|| (m_secondaryFilterRole != -1

View File

@@ -21,14 +21,14 @@ void CustomEmojiModel::fetchEmojis()
return;
}
const auto &data = Controller::instance().activeConnection()->accountData("im.ponies.user_emotes");
const auto &data = Controller::instance().activeConnection()->accountData("im.ponies.user_emotes"_ls);
if (data == nullptr) {
return;
}
QJsonObject emojis = data->contentJson()["images"].toObject();
QJsonObject emojis = data->contentJson()["images"_ls].toObject();
// TODO: Remove with stable migration
const auto legacyEmojis = data->contentJson()["emoticons"].toObject();
const auto legacyEmojis = data->contentJson()["emoticons"_ls].toObject();
for (const auto &emoji : legacyEmojis.keys()) {
if (!emojis.contains(emoji)) {
emojis[emoji] = legacyEmojis[emoji];
@@ -41,9 +41,9 @@ void CustomEmojiModel::fetchEmojis()
for (const auto &emoji : emojis.keys()) {
const auto &data = emojis[emoji];
const auto e = emoji.startsWith(":") ? emoji : (QStringLiteral(":") + emoji + QStringLiteral(":"));
const auto e = emoji.startsWith(":"_ls) ? emoji : (QStringLiteral(":") + emoji + QStringLiteral(":"));
m_emojis << CustomEmoji{e, data.toObject()["url"].toString(), QRegularExpression(e)};
m_emojis << CustomEmoji{e, data.toObject()["url"_ls].toString(), QRegularExpression(e)};
}
endResetModel();
@@ -56,19 +56,19 @@ void CustomEmojiModel::addEmoji(const QString &name, const QUrl &location)
auto job = Controller::instance().activeConnection()->uploadFile(location.toLocalFile());
connect(job, &BaseJob::success, this, [name, location, job] {
const auto &data = Controller::instance().activeConnection()->accountData("im.ponies.user_emotes");
const auto &data = Controller::instance().activeConnection()->accountData("im.ponies.user_emotes"_ls);
auto json = data != nullptr ? data->contentJson() : QJsonObject();
auto emojiData = json["images"].toObject();
auto emojiData = json["images"_ls].toObject();
QString url;
url = job->contentUri().toString();
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();
imageInfo["w"_ls] = image.width();
imageInfo["h"_ls] = image.height();
imageInfo["mimetype"_ls] = QMimeDatabase().mimeTypeForFile(location.toLocalFile()).name();
imageInfo["size"_ls] = image.sizeInBytes();
emojiData[QStringLiteral("%1").arg(name)] = QJsonObject({
{QStringLiteral("url"), url},
@@ -77,8 +77,8 @@ void CustomEmojiModel::addEmoji(const QString &name, const QUrl &location)
{"usage"_ls, "emoticon"_ls},
});
json["images"] = emojiData;
Controller::instance().activeConnection()->setAccountData("im.ponies.user_emotes", json);
json["images"_ls] = emojiData;
Controller::instance().activeConnection()->setAccountData("im.ponies.user_emotes"_ls, json);
});
}
@@ -86,30 +86,30 @@ void CustomEmojiModel::removeEmoji(const QString &name)
{
using namespace Quotient;
const auto &data = Controller::instance().activeConnection()->accountData("im.ponies.user_emotes");
const auto &data = Controller::instance().activeConnection()->accountData("im.ponies.user_emotes"_ls);
Q_ASSERT(data);
auto json = data->contentJson();
const QString _name = name.mid(1).chopped(1);
auto emojiData = json["images"].toObject();
auto emojiData = json["images"_ls].toObject();
if (emojiData.contains(name)) {
emojiData.remove(name);
json["images"] = emojiData;
json["images"_ls] = emojiData;
}
if (emojiData.contains(_name)) {
emojiData.remove(_name);
json["images"] = emojiData;
json["images"_ls] = emojiData;
}
emojiData = json["emoticons"].toObject();
emojiData = json["emoticons"_ls].toObject();
if (emojiData.contains(name)) {
emojiData.remove(name);
json["emoticons"] = emojiData;
json["emoticons"_ls] = emojiData;
}
if (emojiData.contains(_name)) {
emojiData.remove(_name);
json["emoticons"] = emojiData;
json["emoticons"_ls] = emojiData;
}
Controller::instance().activeConnection()->setAccountData("im.ponies.user_emotes", json);
Controller::instance().activeConnection()->setAccountData("im.ponies.user_emotes"_ls, json);
}
CustomEmojiModel::CustomEmojiModel(QObject *parent)
@@ -174,7 +174,7 @@ QHash<int, QByteArray> CustomEmojiModel::roleNames() const
QString CustomEmojiModel::preprocessText(const QString &text)
{
auto parts = text.split("```");
auto parts = text.split("```"_ls);
bool skip = true;
for (auto &part : parts) {
skip = !skip;
@@ -187,7 +187,7 @@ QString CustomEmojiModel::preprocessText(const QString &text)
QStringLiteral(R"(<img data-mx-emoticon="" src="%1" alt="%2" title="%2" height="32" vertical-align="middle" />)").arg(emoji.url, emoji.name));
}
}
return parts.join("```");
return parts.join("```"_ls);
}
QVariantList CustomEmojiModel::filterModel(const QString &filter)

View File

@@ -65,7 +65,6 @@ QVariant DevicesModel::data(const QModelIndex &index, int role) const
if (device.deviceId == m_connection->deviceId()) {
return This;
}
#ifdef Quotient_E2EE_ENABLED
if (!m_connection->isKnownE2eeCapableDevice(m_connection->userId(), device.deviceId)) {
return Unencrypted;
}
@@ -74,9 +73,6 @@ QVariant DevicesModel::data(const QModelIndex &index, int role) const
} else {
return Unverified;
}
#else
return Unverified;
#endif
}
return {};
}
@@ -117,11 +113,11 @@ void DevicesModel::logout(const QString &deviceId, const QString &password)
if (job->error() != BaseJob::Success) {
QJsonObject replyData = job->jsonData();
QJsonObject authData;
authData["session"] = replyData["session"];
authData["password"] = password;
authData["type"] = "m.login.password";
QJsonObject identifier = {{"type", "m.id.user"}, {"user", Controller::instance().activeConnection()->user()->id()}};
authData["identifier"] = identifier;
authData["session"_ls] = replyData["session"_ls];
authData["password"_ls] = password;
authData["type"_ls] = "m.login.password"_ls;
QJsonObject identifier = {{"type"_ls, "m.id.user"_ls}, {"user"_ls, Controller::instance().activeConnection()->user()->id()}};
authData["identifier"_ls] = identifier;
auto *innerJob = Controller::instance().activeConnection()->callApi<NeochatDeleteDeviceJob>(m_devices[index].deviceId, authData);
connect(innerJob, &BaseJob::success, this, onSuccess);
} else {
@@ -161,7 +157,6 @@ void DevicesModel::setConnection(Connection *connection)
Q_EMIT connectionChanged();
fetchDevices();
#ifdef Quotient_E2EE_ENABLED
connect(m_connection, &Connection::sessionVerified, this, [this](const QString &userId, const QString &deviceId) {
Q_UNUSED(deviceId);
if (userId == Controller::instance().activeConnection()->userId()) {
@@ -171,7 +166,6 @@ void DevicesModel::setConnection(Connection *connection)
connect(m_connection, &Connection::finishedQueryingKeys, this, [this]() {
fetchDevices();
});
#endif
}
#include "moc_devicesmodel.cpp"

View File

@@ -8,7 +8,7 @@
class DevicesProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
Q_PROPERTY(int type READ type WRITE setType NOTIFY typeChanged);
Q_PROPERTY(int type READ type WRITE setType NOTIFY typeChanged)
public:
DevicesProxyModel(QObject *parent = nullptr);

View File

@@ -63,7 +63,7 @@ QHash<int, QByteArray> EmojiModel::roleNames() const
QVariantList EmojiModel::history() const
{
return m_settings.value("Editor/emojis", QVariantList()).toList();
return m_settings.value(QStringLiteral("Editor/emojis"), QVariantList()).toList();
}
QVariantList EmojiModel::filterModel(const QString &filter, bool limit)
@@ -105,7 +105,7 @@ void EmojiModel::emojiUsed(const QVariant &modelData)
}
list.push_front(modelData);
m_settings.setValue("Editor/emojis", list);
m_settings.setValue(QStringLiteral("Editor/emojis"), list);
Q_EMIT historyChanged();
}
@@ -133,8 +133,8 @@ QVariantList EmojiModel::emojis(Category category) const
QVariantList EmojiModel::tones(const QString &baseEmoji) const
{
if (baseEmoji.endsWith("tone")) {
return EmojiTones::_tones.values(baseEmoji.split(":")[0]);
if (baseEmoji.endsWith(QStringLiteral("tone"))) {
return EmojiTones::_tones.values(baseEmoji.split(QStringLiteral(":"))[0]);
}
return EmojiTones::_tones.values(baseEmoji);
}
@@ -145,54 +145,54 @@ QVariantList EmojiModel::categories() const
{
return QVariantList{
{QVariantMap{
{"category", EmojiModel::HistoryNoCustom},
{"name", i18nc("Previously used emojis", "History")},
{"emoji", QStringLiteral("⌛️")},
{QStringLiteral("category"), EmojiModel::HistoryNoCustom},
{QStringLiteral("name"), i18nc("Previously used emojis", "History")},
{QStringLiteral("emoji"), QStringLiteral("⌛️")},
}},
{QVariantMap{
{"category", EmojiModel::Smileys},
{"name", i18nc("'Smileys' is a category of emoji", "Smileys")},
{"emoji", QStringLiteral("😏")},
{QStringLiteral("category"), EmojiModel::Smileys},
{QStringLiteral("name"), i18nc("'Smileys' is a category of emoji", "Smileys")},
{QStringLiteral("emoji"), QStringLiteral("😏")},
}},
{QVariantMap{
{"category", EmojiModel::People},
{"name", i18nc("'People' is a category of emoji", "People")},
{"emoji", QStringLiteral("🙋‍♂️")},
{QStringLiteral("category"), EmojiModel::People},
{QStringLiteral("name"), i18nc("'People' is a category of emoji", "People")},
{QStringLiteral("emoji"), QStringLiteral("🙋‍♂️")},
}},
{QVariantMap{
{"category", EmojiModel::Nature},
{"name", i18nc("'Nature' is a category of emoji", "Nature")},
{"emoji", QStringLiteral("🌲")},
{QStringLiteral("category"), EmojiModel::Nature},
{QStringLiteral("name"), i18nc("'Nature' is a category of emoji", "Nature")},
{QStringLiteral("emoji"), QStringLiteral("🌲")},
}},
{QVariantMap{
{"category", EmojiModel::Food},
{"name", i18nc("'Food' is a category of emoji", "Food")},
{"emoji", QStringLiteral("🍛")},
{QStringLiteral("category"), EmojiModel::Food},
{QStringLiteral("name"), i18nc("'Food' is a category of emoji", "Food")},
{QStringLiteral("emoji"), QStringLiteral("🍛")},
}},
{QVariantMap{
{"category", EmojiModel::Activities},
{"name", i18nc("'Activities' is a category of emoji", "Activities")},
{"emoji", QStringLiteral("🚁")},
{QStringLiteral("category"), EmojiModel::Activities},
{QStringLiteral("name"), i18nc("'Activities' is a category of emoji", "Activities")},
{QStringLiteral("emoji"), QStringLiteral("🚁")},
}},
{QVariantMap{
{"category", EmojiModel::Travel},
{"name", i18nc("'Travel' is a category of emoji", "Travel")},
{"emoji", QStringLiteral("🚅")},
{QStringLiteral("category"), EmojiModel::Travel},
{QStringLiteral("name"), i18nc("'Travel' is a category of emoji", "Travel")},
{QStringLiteral("emoji"), QStringLiteral("🚅")},
}},
{QVariantMap{
{"category", EmojiModel::Objects},
{"name", i18nc("'Objects' is a category of emoji", "Objects")},
{"emoji", QStringLiteral("💡")},
{QStringLiteral("category"), EmojiModel::Objects},
{QStringLiteral("name"), i18nc("'Objects' is a category of emoji", "Objects")},
{QStringLiteral("emoji"), QStringLiteral("💡")},
}},
{QVariantMap{
{"category", EmojiModel::Symbols},
{"name", i18nc("'Symbols' is a category of emoji", "Symbols")},
{"emoji", QStringLiteral("🔣")},
{QStringLiteral("category"), EmojiModel::Symbols},
{QStringLiteral("name"), i18nc("'Symbols' is a category of emoji", "Symbols")},
{QStringLiteral("emoji"), QStringLiteral("🔣")},
}},
{QVariantMap{
{"category", EmojiModel::Flags},
{"name", i18nc("'Flags' is a category of emoji", "Flags")},
{"emoji", QStringLiteral("🏁")},
{QStringLiteral("category"), EmojiModel::Flags},
{QStringLiteral("name"), i18nc("'Flags' is a category of emoji", "Flags")},
{QStringLiteral("emoji"), QStringLiteral("🏁")},
}},
};
}
@@ -203,15 +203,15 @@ QVariantList EmojiModel::categoriesWithCustom() const
cats.removeAt(0);
cats.insert(0,
QVariantMap{
{"category", EmojiModel::History},
{"name", i18nc("Previously used emojis", "History")},
{"emoji", QStringLiteral("⌛️")},
{QStringLiteral("category"), EmojiModel::History},
{QStringLiteral("name"), i18nc("Previously used emojis", "History")},
{QStringLiteral("emoji"), QStringLiteral("⌛️")},
});
cats.insert(1,
QVariantMap{
{"category", EmojiModel::Custom},
{"name", i18nc("'Custom' is a category of emoji", "Custom")},
{"emoji", QStringLiteral("🖼️")},
{QStringLiteral("category"), EmojiModel::Custom},
{QStringLiteral("name"), i18nc("'Custom' is a category of emoji", "Custom")},
{QStringLiteral("emoji"), QStringLiteral("🖼️")},
});
;
return cats;

View File

@@ -33,7 +33,7 @@ struct Emoji {
{
arch >> object.unicode;
arch >> object.shortName;
object.isCustom = object.unicode.startsWith("image://");
object.isCustom = object.unicode.startsWith(QStringLiteral("image://"));
return arch;
}

View File

@@ -82,8 +82,9 @@ void ImagePacksModel::reloadImages()
// 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", m_showStickers ? i18nc("As in 'The user's own Stickers'", "Own Stickers") : i18nc("As in 'The user's own emojis", "Own Emojis")},
json["pack"_ls] = QJsonObject{
{"display_name"_ls,
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()) {
@@ -104,8 +105,8 @@ void ImagePacksModel::reloadImages()
for (const auto &packKey : packs.keys()) {
if (const auto &pack = stickerRoom->currentState().get<ImagePackEvent>(packKey)) {
const auto packContent = pack->content();
if ((!packContent.pack || !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"_ls) && showEmoticons())
|| (packContent.pack->usage->contains("sticker"_ls) && showStickers()))
&& !packContent.images.isEmpty()) {
m_events += packContent;
}
@@ -115,12 +116,12 @@ void ImagePacksModel::reloadImages()
}
// Load emoticons from the current room
auto events = m_room->currentState().eventsOfType("im.ponies.room_emotes");
auto events = m_room->currentState().eventsOfType("im.ponies.room_emotes"_ls);
for (const auto &event : events) {
auto packContent = eventCast<const ImagePackEvent>(event)->content();
if (packContent.pack.has_value()) {
if (!packContent.pack->usage || (packContent.pack->usage->contains("emoticon") && showEmoticons())
|| (packContent.pack->usage->contains("sticker") && showStickers())) {
if (!packContent.pack->usage || (packContent.pack->usage->contains("emoticon"_ls) && showEmoticons())
|| (packContent.pack->usage->contains("sticker"_ls) && showStickers())) {
m_events += packContent;
}
}

View File

@@ -8,6 +8,8 @@
#include <QDebug>
#include <cmath>
using namespace Quotient;
bool operator<(const LiveLocationData &lhs, const LiveLocationData &rhs)
@@ -76,7 +78,7 @@ QVariant LiveLocationsModel::data(const QModelIndex &index, int roleName) const
return longitude.toFloat();
}
case AssetRole:
return data.beaconInfo["org.matrix.msc3488.asset"_ls].toObject()["type"].toString();
return data.beaconInfo["org.matrix.msc3488.asset"_ls].toObject()["type"_ls].toString();
case AuthorRole:
return m_room->getUser(data.senderId);
case IsLiveRole: {
@@ -88,6 +90,11 @@ QVariant LiveLocationsModel::data(const QModelIndex &index, int roleName) const
const auto timeout = data.beaconInfo.value("timeout"_ls).toDouble(600000);
return lastTs + timeout >= QDateTime::currentDateTime().toMSecsSinceEpoch();
}
case HeadingRole: {
bool success = false;
const auto heading = data.beacon["org.matrix.msc3488.location"_ls].toObject()["org.kde.itinerary.heading"_ls].toString().toDouble(&success);
return success ? heading : NAN;
}
}
return {};
@@ -101,6 +108,7 @@ QHash<int, QByteArray> LiveLocationsModel::roleNames() const
r.insert(AssetRole, "asset");
r.insert(AuthorRole, "author");
r.insert(IsLiveRole, "isLive");
r.insert(HeadingRole, "heading");
return r;
}
@@ -121,7 +129,7 @@ QRectF LiveLocationsModel::boundingBox() const
void LiveLocationsModel::addEvent(const Quotient::RoomEvent *event)
{
if (event->isStateEvent() && event->matrixType() == "org.matrix.msc3672.beacon_info") {
if (event->isStateEvent() && event->matrixType() == "org.matrix.msc3672.beacon_info"_ls) {
LiveLocationData data;
data.senderId = event->senderId();
data.beaconInfo = event->contentJson();

View File

@@ -49,6 +49,7 @@ public:
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. */
HeadingRole, /**< Heading in degree (not part of any MSC yet, using an Itinerary extension). */
};
Q_ENUM(Roles)

View File

@@ -3,6 +3,8 @@
#include "locationsmodel.h"
#include <QGuiApplication>
using namespace Quotient;
LocationsModel::LocationsModel(QObject *parent)
@@ -13,7 +15,7 @@ LocationsModel::LocationsModel(QObject *parent)
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"] == "m.location") {
if (event->contentJson()["msgtype"_ls] == "m.location"_ls) {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
@@ -23,7 +25,7 @@ LocationsModel::LocationsModel(QObject *parent)
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"] == "m.location") {
if (event->contentJson()["msgtype"_ls] == "m.location"_ls) {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
@@ -34,7 +36,7 @@ LocationsModel::LocationsModel(QObject *parent)
if (!is<RoomMessageEvent>(*event)) {
continue;
}
if (event->contentJson()["msgtype"] == "m.location") {
if (event->contentJson()["msgtype"_ls] == "m.location"_ls) {
const auto &e = *event;
addLocation(eventCast<const RoomMessageEvent>(&e));
}
@@ -43,11 +45,15 @@ LocationsModel::LocationsModel(QObject *parent)
});
connect(this, &LocationsModel::rowsInserted, this, &LocationsModel::boundingBoxChanged);
connect(static_cast<QGuiApplication *>(QGuiApplication::instance()), &QGuiApplication::paletteChanged, this, [this] {
Q_EMIT dataChanged(index(0, 0), index(rowCount() - 1, 0), {AuthorRole});
});
}
void LocationsModel::addLocation(const RoomMessageEvent *event)
{
const auto uri = event->contentJson()["org.matrix.msc3488.location"]["uri"].toString();
const auto uri = event->contentJson()["org.matrix.msc3488.location"_ls]["uri"_ls].toString();
const auto parts = uri.mid(4).split(QLatin1Char(','));
if (parts.size() < 2) {
qWarning() << "invalid geo: URI" << uri;
@@ -61,7 +67,7 @@ void LocationsModel::addLocation(const RoomMessageEvent *event)
.latitude = latitude,
.longitude = longitude,
.content = event->contentJson(),
.author = dynamic_cast<NeoChatUser *>(m_room->user(event->senderId())),
.author = m_room->user(event->senderId()),
};
endInsertRows();
}

View File

@@ -10,6 +10,7 @@
#include "neochatroom.h"
#include <Quotient/events/roommessageevent.h>
#include <Quotient/user.h>
class LocationsModel : public QAbstractListModel
{
@@ -51,7 +52,7 @@ private:
float latitude;
float longitude;
QJsonObject content;
NeoChatUser *author;
Quotient::User *author;
};
QList<LocationData> m_locations;
void addLocation(const Quotient::RoomMessageEvent *event);

View File

@@ -25,7 +25,7 @@ QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const
{
if (role == SourceRole) {
if (mapToSource(index).data(MessageEventModel::DelegateTypeRole).toInt() == MessageEventModel::DelegateType::Image) {
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()["source"].toUrl();
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QStringLiteral("source")].toUrl();
} else if (mapToSource(index).data(MessageEventModel::DelegateTypeRole).toInt() == MessageEventModel::DelegateType::Video) {
auto progressInfo = mapToSource(index).data(MessageEventModel::ProgressInfoRole).value<Quotient::FileTransferInfo>();
@@ -39,7 +39,7 @@ QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const
}
}
if (role == TempSourceRole) {
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()["tempInfo"].toMap()["source"].toUrl();
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QStringLiteral("tempInfo")].toMap()[QStringLiteral("source")].toUrl();
}
if (role == TypeRole) {
if (mapToSource(index).data(MessageEventModel::DelegateTypeRole).toInt() == MessageEventModel::DelegateType::Image) {
@@ -52,10 +52,10 @@ QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const
return mapToSource(index).data(Qt::DisplayRole);
}
if (role == SourceWidthRole) {
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()["width"].toFloat();
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QStringLiteral("width")].toFloat();
}
if (role == SourceHeightRole) {
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()["height"].toFloat();
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QStringLiteral("height")].toFloat();
}
return sourceModel()->data(mapToSource(index), role);

View File

@@ -20,12 +20,12 @@
#include <QDebug>
#include <QGuiApplication>
#include <QMovie>
#include <QTimeZone>
#include <KLocalizedString>
#include "models/reactionmodel.h"
#include "neochatuser.h"
#include "texthandler.h"
using namespace Quotient;
@@ -78,7 +78,7 @@ MessageEventModel::MessageEventModel(QObject *parent)
: QAbstractListModel(parent)
{
connect(static_cast<QGuiApplication *>(QGuiApplication::instance()), &QGuiApplication::paletteChanged, this, [this] {
Q_EMIT dataChanged(index(0, 0), index(rowCount() - 1, 0), {AuthorRole, ReplyRole});
Q_EMIT dataChanged(index(0, 0), index(rowCount() - 1, 0), {AuthorRole, ReplyAuthor, ReadMarkersRole});
});
}
@@ -531,7 +531,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
}
if (role == AuthorRole) {
auto author = static_cast<NeoChatUser *>(isPending ? m_currentRoom->localUser() : m_currentRoom->user(evt.senderId()));
auto author = isPending ? m_currentRoom->localUser() : m_currentRoom->user(evt.senderId());
return m_currentRoom->getUser(author);
}
@@ -579,7 +579,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
if (isPending) {
// A pending event with an m.new_content key will be merged into the
// original event so don't show.
if (evt.contentJson().contains("m.new_content")) {
if (evt.contentJson().contains("m.new_content"_ls)) {
return EventStatus::Hidden;
}
return pendingIt->deliveryStatus();
@@ -668,18 +668,18 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
}
if (role == IsReplyRole) {
return !evt.contentJson()["m.relates_to"].toObject()["m.in_reply_to"].toObject()["event_id"].toString().isEmpty();
return !evt.contentJson()["m.relates_to"_ls].toObject()["m.in_reply_to"_ls].toObject()["event_id"_ls].toString().isEmpty();
}
if (role == ReplyIdRole) {
return evt.contentJson()["m.relates_to"].toObject()["m.in_reply_to"].toObject()["event_id"].toString();
return evt.contentJson()["m.relates_to"_ls].toObject()["m.in_reply_to"_ls].toObject()["event_id"_ls].toString();
}
if (role == ReplyAuthor) {
auto replyPtr = m_currentRoom->getReplyForEvent(evt);
if (replyPtr) {
auto replyUser = static_cast<NeoChatUser *>(m_currentRoom->user(replyPtr->senderId()));
auto replyUser = m_currentRoom->user(replyPtr->senderId());
return m_currentRoom->getUser(replyUser);
} else {
return m_currentRoom->getUser(nullptr);
@@ -733,8 +733,8 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
}
return QVariantMap{
{"display", m_currentRoom->eventToString(*replyPtr, Qt::RichText)},
{"type", type},
{"display"_ls, m_currentRoom->eventToString(*replyPtr, Qt::RichText)},
{"type"_ls, type},
};
}
@@ -789,7 +789,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
}
if (role == AssetRole) {
const auto assetType = evt.contentJson()["org.matrix.msc3488.asset"].toObject()["type"].toString();
const auto assetType = evt.contentJson()["org.matrix.msc3488.asset"_ls].toObject()["type"_ls].toString();
if (assetType.isEmpty()) {
return {};
}
@@ -808,7 +808,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
QVariantList users;
users.reserve(userIds.size());
for (const auto &userId : userIds) {
auto user = static_cast<NeoChatUser *>(m_currentRoom->user(userId));
auto user = m_currentRoom->user(userId);
users += m_currentRoom->getUser(user);
}
@@ -820,7 +820,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
userIds.remove(m_currentRoom->localUser()->id());
if (userIds.count() > 5) {
return QStringLiteral("+ ") + QString::number(userIds.count() - 5);
return QStringLiteral("+ %1").arg(userIds.count() - 5);
} else {
return QString();
}
@@ -836,7 +836,7 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
*/
QString readMarkersString = i18np("1 user: ", "%1 users: ", userIds.size());
for (const auto &userId : userIds) {
auto user = static_cast<NeoChatUser *>(m_currentRoom->user(userId));
auto user = m_currentRoom->user(userId);
readMarkersString += user->displayname(m_currentRoom) + i18nc("list separator", ", ");
}
readMarkersString.chop(2);
@@ -866,30 +866,28 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
}
if (role == VerifiedRole) {
#ifdef Quotient_E2EE_ENABLED
if (evt.originalEvent()) {
auto encrypted = dynamic_cast<const EncryptedEvent *>(evt.originalEvent());
Q_ASSERT(encrypted);
return m_currentRoom->connection()->isVerifiedSession(encrypted->sessionId().toLatin1());
}
#endif
return false;
}
if (role == DisplayNameForInitialsRole) {
auto user = static_cast<NeoChatUser *>(isPending ? m_currentRoom->localUser() : m_currentRoom->user(evt.senderId()));
auto user = isPending ? m_currentRoom->localUser() : m_currentRoom->user(evt.senderId());
return user->displayname(m_currentRoom).remove(QStringLiteral(" (%1)").arg(user->id()));
}
if (role == AuthorDisplayNameRole) {
if (is<RoomMemberEvent>(evt) && !evt.unsignedJson()["prev_content"]["displayname"].isNull() && evt.stateKey() == evt.senderId()) {
auto previousDisplayName = evt.unsignedJson()["prev_content"]["displayname"].toString().toHtmlEscaped();
if (is<RoomMemberEvent>(evt) && !evt.unsignedJson()["prev_content"_ls]["displayname"_ls].isNull() && evt.stateKey() == evt.senderId()) {
auto previousDisplayName = evt.unsignedJson()["prev_content"_ls]["displayname"_ls].toString().toHtmlEscaped();
if (previousDisplayName.isEmpty()) {
previousDisplayName = evt.senderId();
}
return previousDisplayName;
} else {
auto author = static_cast<NeoChatUser *>(isPending ? m_currentRoom->localUser() : m_currentRoom->user(evt.senderId()));
auto author = isPending ? m_currentRoom->localUser() : m_currentRoom->user(evt.senderId());
return m_currentRoom->htmlSafeMemberName(author->id());
}
}
@@ -945,76 +943,79 @@ QVariantMap MessageEventModel::getMediaInfoFromFileInfo(const EventContent::File
// Get the mxc URL for the media.
if (!fileInfo->url().isValid() || eventId.isEmpty()) {
mediaInfo["source"] = QUrl();
mediaInfo["source"_ls] = QUrl();
} else {
QUrl source = m_currentRoom->makeMediaUrl(eventId, fileInfo->url());
if (source.isValid() && source.scheme() == QStringLiteral("mxc")) {
mediaInfo["source"] = source;
mediaInfo["source"_ls] = source;
} else {
mediaInfo["source"] = QUrl();
mediaInfo["source"_ls] = QUrl();
}
}
auto mimeType = fileInfo->mimeType;
// Add the MIME type for the media if available.
mediaInfo["mimeType"] = mimeType.name();
mediaInfo["mimeType"_ls] = mimeType.name();
// Add the MIME type icon if available.
mediaInfo["mimeIcon"] = mimeType.iconName();
mediaInfo["mimeIcon"_ls] = mimeType.iconName();
// Add media size if available.
mediaInfo["size"] = fileInfo->payloadSize;
mediaInfo["size"_ls] = fileInfo->payloadSize;
// Add parameter depending on media type.
if (mimeType.name().contains(QStringLiteral("image"))) {
if (auto castInfo = static_cast<const EventContent::ImageContent *>(fileInfo)) {
mediaInfo["width"] = castInfo->imageSize.width();
mediaInfo["height"] = castInfo->imageSize.height();
mediaInfo["width"_ls] = castInfo->imageSize.width();
mediaInfo["height"_ls] = castInfo->imageSize.height();
// TODO: Images in certain formats (e.g. WebP) will be erroneously marked as animated, even if they are static.
mediaInfo["animated"_ls] = QMovie::supportedFormats().contains(mimeType.preferredSuffix().toUtf8());
if (!isThumbnail) {
QVariantMap tempInfo;
auto thumbnailInfo = getMediaInfoFromFileInfo(castInfo->thumbnailInfo(), eventId, true);
if (thumbnailInfo["source"].toUrl().scheme() == "mxc") {
if (thumbnailInfo["source"_ls].toUrl().scheme() == "mxc"_ls) {
tempInfo = thumbnailInfo;
} else {
QString blurhash = castInfo->originalInfoJson["xyz.amorgan.blurhash"].toString();
QString blurhash = castInfo->originalInfoJson["xyz.amorgan.blurhash"_ls].toString();
if (blurhash.isEmpty()) {
tempInfo["source"] = QUrl();
tempInfo["source"_ls] = QUrl();
} else {
tempInfo["source"] = QUrl("image://blurhash/" + blurhash);
tempInfo["source"_ls] = QUrl("image://blurhash/"_ls + blurhash);
}
}
mediaInfo["tempInfo"] = tempInfo;
mediaInfo["tempInfo"_ls] = tempInfo;
}
}
}
if (mimeType.name().contains(QStringLiteral("video"))) {
if (auto castInfo = static_cast<const EventContent::VideoContent *>(fileInfo)) {
mediaInfo["width"] = castInfo->imageSize.width();
mediaInfo["height"] = castInfo->imageSize.height();
mediaInfo["duration"] = castInfo->duration;
mediaInfo["width"_ls] = castInfo->imageSize.width();
mediaInfo["height"_ls] = castInfo->imageSize.height();
mediaInfo["duration"_ls] = castInfo->duration;
if (!isThumbnail) {
QVariantMap tempInfo;
auto thumbnailInfo = getMediaInfoFromFileInfo(castInfo->thumbnailInfo(), eventId, true);
if (thumbnailInfo["source"].toUrl().scheme() == "mxc") {
if (thumbnailInfo["source"_ls].toUrl().scheme() == "mxc"_ls) {
tempInfo = thumbnailInfo;
} else {
QString blurhash = castInfo->originalInfoJson["xyz.amorgan.blurhash"].toString();
QString blurhash = castInfo->originalInfoJson["xyz.amorgan.blurhash"_ls].toString();
if (blurhash.isEmpty()) {
tempInfo["source"] = QUrl();
tempInfo["source"_ls] = QUrl();
} else {
tempInfo["source"] = QUrl("image://blurhash/" + blurhash);
tempInfo["source"_ls] = QUrl("image://blurhash/"_ls + blurhash);
}
}
mediaInfo["tempInfo"] = tempInfo;
mediaInfo["tempInfo"_ls] = tempInfo;
}
}
}
if (mimeType.name().contains(QStringLiteral("audio"))) {
if (auto castInfo = static_cast<const EventContent::AudioContent *>(fileInfo)) {
mediaInfo["duration"] = castInfo->duration;
mediaInfo["duration"_ls] = castInfo->duration;
}
}
@@ -1062,13 +1063,13 @@ void MessageEventModel::createReactionModelForEvent(const Quotient::RoomMessageE
return;
};
QMap<QString, QList<NeoChatUser *>> reactions = {};
QMap<QString, QList<Quotient::User *>> reactions = {};
for (const auto &a : annotations) {
if (a->isRedacted()) { // Just in case?
continue;
}
if (const auto &e = eventCast<const ReactionEvent>(a)) {
reactions[e->key()].append(static_cast<NeoChatUser *>(m_currentRoom->user(e->senderId())));
reactions[e->key()].append(m_currentRoom->user(e->senderId()));
}
}
@@ -1095,7 +1096,7 @@ void MessageEventModel::createReactionModelForEvent(const Quotient::RoomMessageE
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()));
m_reactionModels[eventId] = new ReactionModel(this, res, m_currentRoom->localUser());
} else {
if (m_reactionModels.contains(eventId)) {
delete m_reactionModels[eventId];

View File

@@ -25,7 +25,7 @@ void PublicRoomListModel::setConnection(Connection *conn)
beginResetModel();
nextBatch = "";
nextBatch = QString();
attempted = false;
rooms.clear();
m_server.clear();
@@ -41,6 +41,7 @@ void PublicRoomListModel::setConnection(Connection *conn)
if (job) {
job->abandon();
job = nullptr;
Q_EMIT loadingChanged();
}
if (m_connection) {
@@ -67,15 +68,17 @@ void PublicRoomListModel::setServer(const QString &value)
beginResetModel();
nextBatch = "";
nextBatch = QString();
attempted = false;
rooms.clear();
Q_EMIT loadingChanged();
endResetModel();
if (job) {
job->abandon();
job = nullptr;
Q_EMIT loadingChanged();
}
if (m_connection) {
@@ -101,7 +104,7 @@ void PublicRoomListModel::setKeyword(const QString &value)
beginResetModel();
nextBatch = "";
nextBatch = QString();
attempted = false;
rooms.clear();
@@ -110,6 +113,7 @@ void PublicRoomListModel::setKeyword(const QString &value)
if (job) {
job->abandon();
job = nullptr;
Q_EMIT loadingChanged();
}
if (m_connection) {
@@ -133,6 +137,7 @@ void PublicRoomListModel::next(int count)
}
job = m_connection->callApi<QueryPublicRoomsJob>(m_server, count, nextBatch, QueryPublicRoomsJob::Filter{m_keyword, {}});
Q_EMIT loadingChanged();
connect(job, &BaseJob::finished, this, [this] {
attempted = true;
@@ -150,6 +155,7 @@ void PublicRoomListModel::next(int count)
}
this->job = nullptr;
Q_EMIT loadingChanged();
});
}
@@ -186,7 +192,7 @@ QVariant PublicRoomListModel::data(const QModelIndex &index, int role) const
auto avatarUrl = room.avatarUrl;
if (avatarUrl.isEmpty()) {
return "";
return {};
}
return avatarUrl.url().remove(0, 6);
}
@@ -253,4 +259,9 @@ bool PublicRoomListModel::hasMore() const
return !(attempted && nextBatch.isEmpty());
}
bool PublicRoomListModel::loading() const
{
return job != nullptr;
}
#include "moc_publicroomlistmodel.cpp"

View File

@@ -48,6 +48,11 @@ class PublicRoomListModel : public QAbstractListModel
*/
Q_PROPERTY(bool hasMore READ hasMore NOTIFY hasMoreChanged)
/**
* @biref Whether the model is still loading.
*/
Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged)
public:
/**
* @brief Defines the model roles.
@@ -98,6 +103,8 @@ public:
[[nodiscard]] bool hasMore() const;
[[nodiscard]] bool loading() const;
/**
* @brief Load the next set of rooms.
*
@@ -111,6 +118,7 @@ private:
QString m_keyword;
bool attempted = false;
bool m_loading = false;
QString nextBatch;
QVector<Quotient::PublicRoomsChunk> rooms;
@@ -122,4 +130,5 @@ Q_SIGNALS:
void serverChanged();
void keywordChanged();
void hasMoreChanged();
void loadingChanged();
};

View File

@@ -69,18 +69,20 @@ PushRuleModel::PushRuleModel(QObject *parent)
void PushRuleModel::controllerConnectionChanged()
{
connect(Controller::instance().activeConnection(), &Quotient::Connection::accountDataChanged, this, &PushRuleModel::updateNotificationRules);
updateNotificationRules("m.push_rules");
if (Controller::instance().activeConnection()) {
connect(Controller::instance().activeConnection(), &Quotient::Connection::accountDataChanged, this, &PushRuleModel::updateNotificationRules);
updateNotificationRules(QStringLiteral("m.push_rules"));
}
}
void PushRuleModel::updateNotificationRules(const QString &type)
{
if (type != "m.push_rules") {
if (type != QStringLiteral("m.push_rules")) {
return;
}
const QJsonObject ruleDataJson = Controller::instance().activeConnection()->accountDataJson("m.push_rules");
const Quotient::PushRuleset ruleData = Quotient::fromJson<Quotient::PushRuleset>(ruleDataJson["global"].toObject());
const QJsonObject ruleDataJson = Controller::instance().activeConnection()->accountDataJson(QStringLiteral("m.push_rules"));
const Quotient::PushRuleset ruleData = Quotient::fromJson<Quotient::PushRuleset>(ruleDataJson[QStringLiteral("global")].toObject());
beginResetModel();
m_rules.clear();
@@ -201,7 +203,7 @@ bool PushRuleModel::globalNotificationsEnabled() const
void PushRuleModel::setGlobalNotificationsEnabled(bool enabled)
{
setNotificationRuleEnabled("override", ".m.rule.master", !enabled);
setNotificationRuleEnabled(QStringLiteral("override"), QStringLiteral(".m.rule.master"), !enabled);
}
bool PushRuleModel::globalNotificationsSet() const
@@ -302,26 +304,26 @@ void PushRuleModel::addKeyword(const QString &keyword, const QString &roomId)
kind = PushNotificationKind::Override;
Quotient::PushCondition roomCondition;
roomCondition.kind = "event_match";
roomCondition.key = "room_id";
roomCondition.kind = QStringLiteral("event_match");
roomCondition.key = QStringLiteral("room_id");
roomCondition.pattern = roomId;
pushConditions.append(roomCondition);
Quotient::PushCondition keywordCondition;
keywordCondition.kind = "event_match";
keywordCondition.key = "content.body";
keywordCondition.kind = QStringLiteral("event_match");
keywordCondition.key = QStringLiteral("content.body");
keywordCondition.pattern = keyword;
pushConditions.append(keywordCondition);
}
auto job = Controller::instance().activeConnection()->callApi<Quotient::SetPushRuleJob>("global",
auto job = Controller::instance().activeConnection()->callApi<Quotient::SetPushRuleJob>(QLatin1String("global"),
PushNotificationKind::kindString(kind),
keyword,
actions,
QLatin1String(""),
QLatin1String(""),
QString(),
QString(),
pushConditions,
roomId.isEmpty() ? keyword : QLatin1String(""));
roomId.isEmpty() ? keyword : QString());
connect(job, &Quotient::BaseJob::failure, this, [job, keyword]() {
qWarning() << QLatin1String("Unable to set push rule for keyword %1: ").arg(keyword) << job->errorString();
});
@@ -340,7 +342,7 @@ void PushRuleModel::removeKeyword(const QString &keyword)
}
auto kind = PushNotificationKind::kindString(m_rules[index].kind);
auto job = Controller::instance().activeConnection()->callApi<Quotient::DeletePushRuleJob>("global", kind, m_rules[index].id);
auto job = Controller::instance().activeConnection()->callApi<Quotient::DeletePushRuleJob>(QStringLiteral("global"), kind, m_rules[index].id);
connect(job, &Quotient::BaseJob::failure, this, [this, job, index]() {
qWarning() << QLatin1String("Unable to remove push rule for keyword %1: ").arg(m_rules[index].id) << job->errorString();
});
@@ -348,10 +350,10 @@ void PushRuleModel::removeKeyword(const QString &keyword)
void PushRuleModel::setNotificationRuleEnabled(const QString &kind, const QString &ruleId, bool enabled)
{
auto job = Controller::instance().activeConnection()->callApi<Quotient::IsPushRuleEnabledJob>("global", kind, ruleId);
auto job = Controller::instance().activeConnection()->callApi<Quotient::IsPushRuleEnabledJob>(QStringLiteral("global"), kind, ruleId);
connect(job, &Quotient::BaseJob::success, this, [job, kind, ruleId, enabled]() {
if (job->enabled() != enabled) {
Controller::instance().activeConnection()->callApi<Quotient::SetPushRuleEnabledJob>("global", kind, ruleId, enabled);
Controller::instance().activeConnection()->callApi<Quotient::SetPushRuleEnabledJob>(QStringLiteral("global"), kind, ruleId, enabled);
}
});
}
@@ -359,13 +361,13 @@ void PushRuleModel::setNotificationRuleEnabled(const QString &kind, const QStrin
void PushRuleModel::setNotificationRuleActions(const QString &kind, const QString &ruleId, PushNotificationAction::Action action)
{
QVector<QVariant> actions;
if (ruleId == ".m.rule.call") {
actions = actionToVariant(action, "ring");
if (ruleId == QStringLiteral(".m.rule.call")) {
actions = actionToVariant(action, QStringLiteral("ring"));
} else {
actions = actionToVariant(action);
}
Controller::instance().activeConnection()->callApi<Quotient::SetPushRuleActionsJob>("global", kind, ruleId, actions);
Controller::instance().activeConnection()->callApi<Quotient::SetPushRuleActionsJob>(QStringLiteral("global"), kind, ruleId, actions);
}
PushNotificationAction::Action PushRuleModel::variantToAction(const QVector<QVariant> &actions, bool enabled)
@@ -383,10 +385,10 @@ PushNotificationAction::Action PushRuleModel::variantToAction(const QVector<QVar
}
QJsonObject action = i.toJsonObject();
if (action["set_tweak"].toString() == "sound") {
if (action[QStringLiteral("set_tweak")].toString() == QStringLiteral("sound")) {
isNoisy = true;
} else if (action["set_tweak"].toString() == "highlight") {
if (action["value"].toString() != "false") {
} else if (action[QStringLiteral("set_tweak")].toString() == QStringLiteral("highlight")) {
if (action[QStringLiteral("value")].toString() != QStringLiteral("false")) {
highlightEnabled = true;
}
}
@@ -423,19 +425,19 @@ QVector<QVariant> PushRuleModel::actionToVariant(PushNotificationAction::Action
QVector<QVariant> actions;
if (action != PushNotificationAction::Off) {
actions.append("notify");
actions.append(QStringLiteral("notify"));
} else {
actions.append("dont_notify");
actions.append(QStringLiteral("dont_notify"));
}
if (action == PushNotificationAction::Noisy || action == PushNotificationAction::NoisyHighlight) {
QJsonObject soundTweak;
soundTweak.insert("set_tweak", "sound");
soundTweak.insert("value", sound);
soundTweak.insert(QStringLiteral("set_tweak"), QStringLiteral("sound"));
soundTweak.insert(QStringLiteral("value"), sound);
actions.append(soundTweak);
}
if (action == PushNotificationAction::Highlight || action == PushNotificationAction::NoisyHighlight) {
QJsonObject highlightTweak;
highlightTweak.insert("set_tweak", "highlight");
highlightTweak.insert(QStringLiteral("set_tweak"), QStringLiteral("highlight"));
actions.append(highlightTweak);
}

View File

@@ -236,6 +236,6 @@ private:
void setNotificationRuleEnabled(const QString &kind, const QString &ruleId, bool enabled);
void setNotificationRuleActions(const QString &kind, const QString &ruleId, PushNotificationAction::Action action);
PushNotificationAction::Action variantToAction(const QVector<QVariant> &actions, bool enabled);
QVector<QVariant> actionToVariant(PushNotificationAction::Action action, const QString &sound = "default");
QVector<QVariant> actionToVariant(PushNotificationAction::Action action, const QString &sound = QStringLiteral("default"));
};
Q_DECLARE_METATYPE(PushRuleModel *)

View File

@@ -7,9 +7,9 @@
#include <KLocalizedString>
#include "neochatuser.h"
#include <Quotient/user.h>
ReactionModel::ReactionModel(QObject *parent, QList<Reaction> reactions, NeoChatUser *localUser)
ReactionModel::ReactionModel(QObject *parent, QList<Reaction> reactions, Quotient::User *localUser)
: QAbstractListModel(parent)
, m_localUser(localUser)
{
@@ -31,7 +31,7 @@ QVariant ReactionModel::data(const QModelIndex &index, int role) const
if (role == TextRole) {
if (reaction.authors.count() > 1) {
return reaction.reaction + QStringLiteral(" %1").arg(reaction.authors.count());
return QStringLiteral("%1 %2").arg(reaction.reaction, reaction.authors.count());
} else {
return reaction.reaction;
}
@@ -52,7 +52,7 @@ QVariant ReactionModel::data(const QModelIndex &index, int role) const
text += i18nc("Separate the usernames of users", " and ");
}
}
text += reaction.authors.at(i).toMap()["displayName"].toString();
text += reaction.authors.at(i).toMap()[QStringLiteral("displayName")].toString();
}
if (reaction.authors.count() > 3) {
@@ -74,7 +74,7 @@ QVariant ReactionModel::data(const QModelIndex &index, int role) const
if (role == HasLocalUser) {
for (auto author : reaction.authors) {
if (author.toMap()["id"] == m_localUser->id()) {
if (author.toMap()[QStringLiteral("id")] == m_localUser->id()) {
return true;
}
}

View File

@@ -5,7 +5,10 @@
#include <QAbstractListModel>
class NeoChatUser;
namespace Quotient
{
class User;
}
/**
* @class ReactionModel
@@ -36,7 +39,7 @@ public:
HasLocalUser, /**< Whether the local user is in the list of authors. */
};
explicit ReactionModel(QObject *parent = nullptr, QList<Reaction> reactions = {}, NeoChatUser *localUser = nullptr);
explicit ReactionModel(QObject *parent = nullptr, QList<Reaction> reactions = {}, Quotient::User *localUser = nullptr);
/**
* @brief Get the given role value at the given index.
@@ -67,6 +70,6 @@ public:
private:
QList<Reaction> m_reactions;
NeoChatUser *m_localUser;
Quotient::User *m_localUser;
};
Q_DECLARE_METATYPE(ReactionModel *)

View File

@@ -40,19 +40,19 @@ RoomListModel::RoomListModel(QObject *parent)
#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
#ifndef Q_OS_ANDROID
// copied from Telegram desktop
const auto launcherUrl = "application://org.kde.neochat.desktop";
const auto launcherUrl = "application://org.kde.neochat.desktop"_ls;
// Gnome requires that count is a 64bit integer
const qint64 counterSlice = std::min(m_notificationCount, 9999);
QVariantMap dbusUnityProperties;
if (counterSlice > 0) {
dbusUnityProperties["count"] = counterSlice;
dbusUnityProperties["count-visible"] = true;
dbusUnityProperties["count"_ls] = counterSlice;
dbusUnityProperties["count-visible"_ls] = true;
} else {
dbusUnityProperties["count-visible"] = false;
dbusUnityProperties["count-visible"_ls] = false;
}
auto signal = QDBusMessage::createSignal("/com/canonical/unity/launcherentry/neochat", "com.canonical.Unity.LauncherEntry", "Update");
auto signal = QDBusMessage::createSignal("/com/canonical/unity/launcherentry/neochat"_ls, "com.canonical.Unity.LauncherEntry"_ls, "Update"_ls);
signal.setArguments({launcherUrl, dbusUnityProperties});
@@ -297,9 +297,9 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
return NeoChatRoomType::Normal;
}
QJsonObject contentJson = creationEvent->contentJson();
QJsonObject::const_iterator typeIter = contentJson.find("type");
QJsonObject::const_iterator typeIter = contentJson.find("type"_ls);
if (typeIter != contentJson.end()) {
if (typeIter.value().toString() == "m.space") {
if (typeIter.value().toString() == "m.space"_ls) {
return NeoChatRoomType::Space;
}
}
@@ -400,7 +400,7 @@ QString RoomListModel::categoryName(int category)
case NeoChatRoomType::Space:
return i18n("Spaces");
default:
return "Deadbeef";
return {};
}
}

View File

@@ -163,7 +163,7 @@ private:
QMap<int, bool> m_categoryVisibility;
int m_notificationCount = 0;
QString m_activeSpaceId = "";
QString m_activeSpaceId;
void connectRoomSignals(NeoChatRoom *room);

View File

@@ -5,13 +5,14 @@
#include "messageeventmodel.h"
#include "neochatroom.h"
#include "neochatuser.h"
#include <QGuiApplication>
#include <Quotient/connection.h>
#include <Quotient/events/stickerevent.h>
#include <KLocalizedString>
#include <Quotient/connection.h>
using namespace Quotient;
// TODO search only in the current room
@@ -19,6 +20,9 @@ using namespace Quotient;
SearchModel::SearchModel(QObject *parent)
: QAbstractListModel(parent)
{
connect(static_cast<QGuiApplication *>(QGuiApplication::instance()), &QGuiApplication::paletteChanged, this, [this] {
Q_EMIT dataChanged(index(0, 0), index(rowCount() - 1, 0), {AuthorRole, ReadMarkersRole});
});
}
QString SearchModel::searchText() const
@@ -53,7 +57,7 @@ void SearchModel::search()
.searchTerm = m_searchText,
.keys = {},
.filter = filter,
.orderBy = "recent",
.orderBy = "recent"_ls,
.eventContext = SearchJob::IncludeEventContext{3, 3, true},
.includeState = false,
.groupings = none,
@@ -109,7 +113,7 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
return false;
case ReplyAuthorRole:
if (const auto &replyPtr = m_room->getReplyForEvent(event)) {
return m_room->getUser(static_cast<NeoChatUser *>(m_room->user(replyPtr->senderId())));
return m_room->getUser(m_room->user(replyPtr->senderId()));
} else {
return m_room->getUser(nullptr);
}
@@ -153,8 +157,8 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
}
return QVariantMap{
{"display", m_room->eventToString(*replyPtr, Qt::RichText)},
{"type", type},
{"display"_ls, m_room->eventToString(*replyPtr, Qt::RichText)},
{"type"_ls, type},
};
}
case IsPendingRole:
@@ -162,13 +166,13 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
case ShowLinkPreviewRole:
return false;
case IsReplyRole:
return !event.contentJson()["m.relates_to"].toObject()["m.in_reply_to"].toObject()["event_id"].toString().isEmpty();
return !event.contentJson()["m.relates_to"_ls].toObject()["m.in_reply_to"_ls].toObject()["event_id"_ls].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 event.contentJson()["m.relates_to"_ls].toObject()["m.in_reply_to"_ls].toObject()["event_id"_ls].toString();
}
return MessageEventModel::DelegateType::Message;
}
@@ -257,7 +261,7 @@ QString renderDate(const QDateTime &timestamp)
return i18n("The day before yesterday");
}
if (date > QDate::currentDate().addDays(-7)) {
return date.toString("dddd");
return date.toString("dddd"_ls);
}
return QLocale::system().toString(date, QLocale::ShortFormat);

View File

@@ -15,8 +15,8 @@
ServerListModel::ServerListModel(QObject *parent)
: QAbstractListModel(parent)
{
KConfig dataResource("data", KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup serverGroup(&dataResource, "Servers");
KConfig dataResource(QStringLiteral("data"), KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup serverGroup(&dataResource, QStringLiteral("Servers"));
QString domain = Controller::instance().activeConnection()->domain();
@@ -91,8 +91,8 @@ int ServerListModel::rowCount(const QModelIndex &parent) const
void ServerListModel::checkServer(const QString &url)
{
KConfig dataResource("data", KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup serverGroup(&dataResource, "Servers");
KConfig dataResource(QStringLiteral("data"), KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup serverGroup(&dataResource, QStringLiteral("Servers"));
if (!serverGroup.hasKey(url)) {
if (Quotient::isJobPending(m_checkServerJob)) {
@@ -108,8 +108,8 @@ void ServerListModel::checkServer(const QString &url)
void ServerListModel::addServer(const QString &url)
{
KConfig dataResource("data", KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup serverGroup(&dataResource, "Servers");
KConfig dataResource(QStringLiteral("data"), KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup serverGroup(&dataResource, QStringLiteral("Servers"));
if (!serverGroup.hasKey(url)) {
Server newServer = Server{
@@ -129,8 +129,8 @@ void ServerListModel::addServer(const QString &url)
void ServerListModel::removeServerAtIndex(int row)
{
KConfig dataResource("data", KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup serverGroup(&dataResource, "Servers");
KConfig dataResource(QStringLiteral("data"), KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup serverGroup(&dataResource, QStringLiteral("Servers"));
serverGroup.deleteEntry(data(index(row), UrlRole).toString());
beginRemoveRows(QModelIndex(), row, row);

View File

@@ -80,7 +80,7 @@ bool SortFilterRoomListModel::filterAcceptsRow(int source_row, const QModelIndex
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::JoinStateRole).toString() != QStringLiteral("upgraded")
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsSpaceRole).toBool() == false;
if (m_activeSpaceId.isEmpty()) {

View File

@@ -27,7 +27,7 @@ bool SortFilterSpaceListModel::filterAcceptsRow(int source_row, const QModelInde
{
Q_UNUSED(source_parent);
return sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsSpaceRole).toBool()
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::JoinStateRole).toString() != "upgraded"
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::JoinStateRole).toString() != QStringLiteral("upgraded")
&& !sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsChildSpaceRole).toBool();
}

View File

@@ -26,8 +26,7 @@ QVariant StateModel::data(const QModelIndex &index, int role) const
int StateModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_room->currentState().events().size();
return !m_room || parent.isValid() ? 0 : m_room->currentState().events().size();
}
NeoChatRoom *StateModel::room() const
@@ -37,8 +36,12 @@ NeoChatRoom *StateModel::room() const
void StateModel::setRoom(NeoChatRoom *room)
{
if (m_room == room) {
return;
}
m_room = room;
Q_EMIT roomChanged();
beginResetModel();
m_stateEvents.clear();
m_stateEvents = m_room->currentState().events().keys();

View File

@@ -109,13 +109,13 @@ void StickerModel::setRoom(NeoChatRoom *room)
void StickerModel::postSticker(int index)
{
const auto &image = m_images[index];
const auto &body = image.body ? *image.body : image.shortcode;
const auto &body = image.body ? *image.body : QString();
QJsonObject infoJson;
if (image.info) {
infoJson["w"] = image.info->imageSize.width();
infoJson["h"] = image.info->imageSize.height();
infoJson["mimetype"] = image.info->mimeType.name();
infoJson["size"] = image.info->payloadSize;
infoJson["w"_ls] = image.info->imageSize.width();
infoJson["h"_ls] = image.info->imageSize.height();
infoJson["mimetype"_ls] = image.info->mimeType.name();
infoJson["size"_ls] = image.info->payloadSize;
// TODO thumbnail
}
QJsonObject content{
@@ -123,7 +123,7 @@ void StickerModel::postSticker(int index)
{"url"_ls, image.url.toString()},
{"info"_ls, infoJson},
};
m_room->postJson("m.sticker", content);
m_room->postJson("m.sticker"_ls, content);
}
#include "moc_stickermodel.cpp"

View File

@@ -138,7 +138,7 @@ QVariant UserDirectoryListModel::data(const QModelIndex &index, int role) const
return displayName;
}
return "Unknown User";
return QStringLiteral("Unknown User");
}
if (role == AvatarRole) {
auto avatarUrl = user.avatarUrl;

View File

@@ -3,6 +3,8 @@
#include "userlistmodel.h"
#include <QGuiApplication>
#include <Quotient/connection.h>
#include <Quotient/events/roompowerlevelsevent.h>
@@ -14,6 +16,9 @@ UserListModel::UserListModel(QObject *parent)
: QAbstractListModel(parent)
, m_currentRoom(nullptr)
{
connect(static_cast<QGuiApplication *>(QGuiApplication::instance()), &QGuiApplication::paletteChanged, this, [this]() {
refreshAllUsers();
});
}
void UserListModel::setRoom(NeoChatRoom *room)
@@ -71,8 +76,7 @@ QVariant UserListModel::data(const QModelIndex &index, int role) const
return user->id();
}
if (role == AvatarRole) {
auto neoChatUser = static_cast<NeoChatUser *>(user);
return m_currentRoom->avatarForMember(neoChatUser);
return m_currentRoom->avatarForMember(user);
}
if (role == ObjectRole) {
return QVariant::fromValue(user);
@@ -159,17 +163,19 @@ void UserListModel::refreshAllUsers()
}
m_users.clear();
m_users = m_currentRoom->users();
std::sort(m_users.begin(), m_users.end(), m_currentRoom->memberSorter());
if (m_currentRoom != nullptr) {
m_users = m_currentRoom->users();
std::sort(m_users.begin(), m_users.end(), m_currentRoom->memberSorter());
for (User *user : std::as_const(m_users)) {
connect(user, &User::defaultAvatarChanged, this, [this, user]() {
refreshUser(user, {AvatarRole});
for (User *user : std::as_const(m_users)) {
connect(user, &User::defaultAvatarChanged, this, [this, user]() {
refreshUser(user, {AvatarRole});
});
}
connect(m_currentRoom->connection(), &Connection::loggedOut, this, [this]() {
setRoom(nullptr);
});
}
connect(m_currentRoom->connection(), &Connection::loggedOut, this, [this]() {
setRoom(nullptr);
});
endResetModel();
Q_EMIT usersRefreshed();
}

View File

@@ -62,7 +62,7 @@ void KWebShortcutModel::setSelectedText(const QString &selectedText)
}
QString searchText = selectedText;
searchText = searchText.replace('\n', ' ').replace('\r', ' ').simplified();
searchText = searchText.replace(QLatin1Char('\n'), QLatin1Char(' ')).replace(QLatin1Char('\r'), QLatin1Char(' ')).simplified();
if (searchText.isEmpty()) {
endResetModel();
return;
@@ -115,7 +115,7 @@ void KWebShortcutModel::trigger(const QString &data)
#ifdef HAVE_KIO
KUriFilterData filterData(data);
if (KUriFilter::self()->filterSearchUri(filterData, KUriFilter::WebShortcutFilter)) {
Q_EMIT openUrl(filterData.uri().url());
Q_EMIT openUrl(filterData.uri());
}
#else
Q_UNUSED(data);
@@ -125,7 +125,7 @@ void KWebShortcutModel::trigger(const QString &data)
void KWebShortcutModel::configureWebShortcuts()
{
#ifdef HAVE_KIO
auto job = new KIO::CommandLauncherJob("kcmshell5", QStringList() << "webshortcuts", this);
auto job = new KIO::CommandLauncherJob(QStringLiteral("kcmshell5"), QStringList() << QStringLiteral("webshortcuts"), this);
job->exec();
#endif
}

View File

@@ -4,8 +4,10 @@
#include "neochatroom.h"
#include <QFileInfo>
#include <QGuiApplication>
#include <QMetaObject>
#include <QMimeDatabase>
#include <QPalette>
#include <QTemporaryFile>
#include <QTextDocument>
@@ -13,6 +15,7 @@
#include <QMediaPlayer>
#include <Quotient/jobs/basejob.h>
#include <Quotient/user.h>
#include <qcoro/qcorosignal.h>
#include <Quotient/connection.h>
@@ -43,6 +46,7 @@
#include "neochatconfig.h"
#include "notificationsmanager.h"
#include "texthandler.h"
#include "utils.h"
#include <KConfig>
#include <KConfigGroup>
@@ -66,8 +70,8 @@ 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");
KConfig dataResource("data"_ls, KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup eventCacheGroup(&dataResource, "EventCache"_ls);
if (eventCacheGroup.hasKey(id())) {
auto eventJson = QJsonDocument::fromJson(eventCacheGroup.readEntry(id(), QByteArray())).object();
@@ -117,7 +121,7 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
Q_EMIT defaultUrlPreviewStateChanged();
});
connect(this, &Room::accountDataChanged, this, [this](QString type) {
if (type == "org.matrix.room.preview_urls") {
if (type == "org.matrix.room.preview_urls"_ls) {
Q_EMIT urlPreviewEnabledChanged();
}
});
@@ -163,15 +167,15 @@ QCoro::Task<void> NeoChatRoom::doUploadFile(QUrl url, QString body)
}
auto mime = QMimeDatabase().mimeTypeForUrl(url);
url.setScheme("file");
url.setScheme("file"_ls);
QFileInfo fileInfo(url.isLocalFile() ? url.toLocalFile() : url.toString());
EventContent::TypedBase *content;
if (mime.name().startsWith("image/")) {
if (mime.name().startsWith("image/"_ls)) {
QImage image(url.toLocalFile());
content = new EventContent::ImageContent(url, fileInfo.size(), mime, image.size(), fileInfo.fileName());
} else if (mime.name().startsWith("audio/")) {
} else if (mime.name().startsWith("audio/"_ls)) {
content = new EventContent::AudioContent(url, fileInfo.size(), mime, fileInfo.fileName());
} else if (mime.name().startsWith("video/")) {
} else if (mime.name().startsWith("video/"_ls)) {
QMediaPlayer player;
#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0)
player.setSource(url);
@@ -234,10 +238,10 @@ QVariantList NeoChatRoom::getUsersTyping() const
QVariantList userVariants;
for (User *user : users) {
userVariants.append(QVariantMap{
{"id", user->id()},
{"avatarMediaId", user->avatarMediaId(this)},
{"displayName", user->displayname(this)},
{"display", user->name()},
{"id"_ls, user->id()},
{"avatarMediaId"_ls, user->avatarMediaId(this)},
{"displayName"_ls, user->displayname(this)},
{"display"_ls, user->name()},
});
}
return userVariants;
@@ -310,8 +314,8 @@ void NeoChatRoom::cacheLastEvent()
{
auto event = lastEvent();
if (event != nullptr) {
KConfig dataResource("data", KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup eventCacheGroup(&dataResource, "EventCache");
KConfig dataResource("data"_ls, KConfig::SimpleConfig, QStandardPaths::AppDataLocation);
KConfigGroup eventCacheGroup(&dataResource, "EventCache"_ls);
auto eventJson = QJsonDocument(event->fullJson()).toJson();
eventCacheGroup.writeEntry(id(), eventJson);
@@ -328,9 +332,9 @@ bool NeoChatRoom::lastEventIsSpoiler() const
{
if (auto event = lastEvent()) {
if (auto e = eventCast<const RoomMessageEvent>(event)) {
if (e->hasTextContent() && e->content() && e->mimeType().name() == "text/html") {
if (e->hasTextContent() && e->content() && e->mimeType().name() == "text/html"_ls) {
auto htmlBody = static_cast<const Quotient::EventContent::TextContent *>(e->content())->body;
return htmlBody.contains("data-mx-spoiler");
return htmlBody.contains("data-mx-spoiler"_ls);
}
}
}
@@ -412,11 +416,11 @@ QVariantList NeoChatRoom::getUsers(const QString &keyword, int limit) const
int count = 0;
for (const auto u : userList) {
if (u->displayname(this).contains(keyword, Qt::CaseInsensitive)) {
NeoChatUser user(u->id(), u->connection());
Quotient::User user(u->id(), u->connection());
QVariantMap userVariant{{QStringLiteral("id"), user.id()},
{QStringLiteral("displayName"), user.displayname(this)},
{QStringLiteral("avatarMediaId"), user.avatarMediaId(this)},
{QStringLiteral("color"), user.color()}};
{QStringLiteral("color"), Utils::getUserColor(user.hueF())}};
matchedList.append(QVariant::fromValue(userVariant));
count++;
@@ -431,22 +435,21 @@ QVariantList NeoChatRoom::getUsers(const QString &keyword, int limit) const
// 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()},
{"isLocalUser"_ls, false},
{"id"_ls, QString()},
{"displayName"_ls, QString()},
{"avatarSource"_ls, QUrl()},
{"avatarMediaId"_ls, QString()},
{"color"_ls, QColor()},
{"object"_ls, QVariant()},
};
QVariantMap NeoChatRoom::getUser(const QString &userID) const
{
NeoChatUser *userObject = static_cast<NeoChatUser *>(user(userID));
return getUser(userObject);
return getUser(user(userID));
}
QVariantMap NeoChatRoom::getUser(NeoChatUser *user) const
QVariantMap NeoChatRoom::getUser(User *user) const
{
if (user == nullptr) {
return emptyUser;
@@ -458,7 +461,7 @@ QVariantMap NeoChatRoom::getUser(NeoChatUser *user) const
{QStringLiteral("displayName"), user->displayname(this)},
{QStringLiteral("avatarSource"), avatarForMember(user)},
{QStringLiteral("avatarMediaId"), user->avatarMediaId(this)},
{QStringLiteral("color"), user->color()},
{QStringLiteral("color"), Utils::getUserColor(user->hueF())},
{QStringLiteral("object"), QVariant::fromValue(user)},
};
}
@@ -497,7 +500,7 @@ QString NeoChatRoom::eventToString(const RoomEvent &evt, Qt::TextFormat format,
if (fileCaption.isEmpty()) {
fileCaption = e.plainBody();
} else if (e.content()->fileInfo()->originalName != e.plainBody()) {
fileCaption = e.plainBody() + " | " + fileCaption;
fileCaption = e.plainBody() + " | "_ls + fileCaption;
}
textHandler.setData(fileCaption);
return !fileCaption.isEmpty() ? textHandler.handleRecievePlainText(Qt::PlainText, stripNewlines) : i18n("a file");
@@ -513,7 +516,7 @@ QString NeoChatRoom::eventToString(const RoomEvent &evt, Qt::TextFormat format,
textHandler.setData(body);
Qt::TextFormat inputFormat;
if (e.mimeType().name() == "text/plain") {
if (e.mimeType().name() == "text/plain"_ls) {
inputFormat = Qt::PlainText;
} else {
inputFormat = Qt::RichText;
@@ -539,7 +542,7 @@ QString NeoChatRoom::eventToString(const RoomEvent &evt, Qt::TextFormat format,
if (prettyPrint) {
subjectName = QStringLiteral("<a href=\"https://matrix.to/#/%1\" style=\"color: %2\">%3</a>")
.arg(e.userId(), static_cast<NeoChatUser *>(user(e.userId()))->color().name(), subjectName);
.arg(e.userId(), Utils::getUserColor(user(e.userId())->hueF()).name(), subjectName);
}
// The below code assumes senderName output in AuthorRole
@@ -641,8 +644,8 @@ QString NeoChatRoom::eventToString(const RoomEvent &evt, Qt::TextFormat format,
return i18n("activated End-to-End Encryption");
},
[](const RoomCreateEvent &e) {
return e.isUpgrade() ? i18n("upgraded the room to version %1", e.version().isEmpty() ? "1" : e.version().toHtmlEscaped())
: i18n("created the room, version %1", e.version().isEmpty() ? "1" : e.version().toHtmlEscaped());
return e.isUpgrade() ? i18n("upgraded the room to version %1", e.version().isEmpty() ? "1"_ls : e.version().toHtmlEscaped())
: i18n("created the room, version %1", e.version().isEmpty() ? "1"_ls : e.version().toHtmlEscaped());
},
[](const RoomPowerLevelsEvent &) {
return i18nc("'power level' means permission level", "changed the power levels for this room");
@@ -652,13 +655,13 @@ QString NeoChatRoom::eventToString(const RoomEvent &evt, Qt::TextFormat format,
return i18n("changed the server access control lists for this room");
}
if (e.matrixType() == QLatin1String("im.vector.modular.widgets")) {
if (e.fullJson()["unsigned"]["prev_content"].toObject().isEmpty()) {
return i18nc("[User] added <name> widget", "added %1 widget", e.contentJson()["name"].toString());
if (e.fullJson()["unsigned"_ls]["prev_content"_ls].toObject().isEmpty()) {
return i18nc("[User] added <name> widget", "added %1 widget", e.contentJson()["name"_ls].toString());
}
if (e.contentJson().isEmpty()) {
return i18nc("[User] removed <name> widget", "removed %1 widget", e.fullJson()["unsigned"]["prev_content"]["name"].toString());
return i18nc("[User] removed <name> widget", "removed %1 widget", e.fullJson()["unsigned"_ls]["prev_content"_ls]["name"_ls].toString());
}
return i18nc("[User] configured <name> widget", "configured %1 widget", e.contentJson()["name"].toString());
return i18nc("[User] configured <name> widget", "configured %1 widget", e.contentJson()["name"_ls].toString());
}
if (e.matrixType() == "org.matrix.msc3672.beacon_info"_ls) {
return e.contentJson()["description"_ls].toString();
@@ -775,7 +778,7 @@ QString NeoChatRoom::eventToGenericString(const RoomEvent &evt) const
return i18n("changed the server access control lists for this room");
}
if (e.matrixType() == QLatin1String("im.vector.modular.widgets")) {
if (e.fullJson()["unsigned"]["prev_content"].toObject().isEmpty()) {
if (e.fullJson()["unsigned"_ls]["prev_content"_ls].toObject().isEmpty()) {
return i18n("added a widget");
}
if (e.contentJson().isEmpty()) {
@@ -797,7 +800,7 @@ void NeoChatRoom::changeAvatar(const QUrl &localFile)
const auto job = connection()->uploadFile(localFile.toLocalFile());
if (isJobPending(job)) {
connect(job, &BaseJob::success, this, [this, job] {
connection()->callApi<SetRoomStateWithKeyJob>(id(), "m.room.avatar", QString(), QJsonObject{{"url", job->contentUri().toString()}});
connection()->callApi<SetRoomStateWithKeyJob>(id(), "m.room.avatar"_ls, QString(), QJsonObject{{"url"_ls, job->contentUri().toString()}});
});
}
}
@@ -806,23 +809,23 @@ QString msgTypeToString(MessageEventType msgType)
{
switch (msgType) {
case MessageEventType::Text:
return "m.text";
return "m.text"_ls;
case MessageEventType::File:
return "m.file";
return "m.file"_ls;
case MessageEventType::Audio:
return "m.audio";
return "m.audio"_ls;
case MessageEventType::Emote:
return "m.emote";
return "m.emote"_ls;
case MessageEventType::Image:
return "m.image";
return "m.image"_ls;
case MessageEventType::Video:
return "m.video";
return "m.video"_ls;
case MessageEventType::Notice:
return "m.notice";
return "m.notice"_ls;
case MessageEventType::Location:
return "m.location";
return "m.location"_ls;
default:
return "m.text";
return "m.text"_ls;
}
}
@@ -842,15 +845,16 @@ void NeoChatRoom::postHtmlMessage(const QString &text, const QString &html, Mess
if (isEdit) {
QJsonObject json{
{"type", "m.room.message"},
{"msgtype", msgTypeToString(type)},
{"body", "* " + text},
{"format", "org.matrix.custom.html"},
{"formatted_body", html},
{"m.new_content", QJsonObject{{"body", text}, {"msgtype", msgTypeToString(type)}, {"format", "org.matrix.custom.html"}, {"formatted_body", html}}},
{"m.relates_to", QJsonObject{{"rel_type", "m.replace"}, {"event_id", relateToEventId}}}};
{"type"_ls, "m.room.message"_ls},
{"msgtype"_ls, msgTypeToString(type)},
{"body"_ls, "* %1"_ls.arg(text)},
{"format"_ls, "org.matrix.custom.html"_ls},
{"formatted_body"_ls, html},
{"m.new_content"_ls,
QJsonObject{{"body"_ls, text}, {"msgtype"_ls, msgTypeToString(type)}, {"format"_ls, "org.matrix.custom.html"_ls}, {"formatted_body"_ls, html}}},
{"m.relates_to"_ls, QJsonObject{{"rel_type"_ls, "m.replace"_ls}, {"event_id"_ls, relateToEventId}}}};
postJson("m.room.message", json);
postJson("m.room.message"_ls, json);
return;
}
@@ -859,31 +863,25 @@ void NeoChatRoom::postHtmlMessage(const QString &text, const QString &html, Mess
// clang-format off
QJsonObject json{
{"msgtype", msgTypeToString(type)},
{"body", "> <" + replyEvt.senderId() + "> " + eventToString(replyEvt) + "\n\n" + text},
{"format", "org.matrix.custom.html"},
{"m.relates_to",
{"msgtype"_ls, msgTypeToString(type)},
{"body"_ls, "> <%1> %2\n\n%3"_ls.arg(replyEvt.senderId(), eventToString(replyEvt), text)},
{"format"_ls, "org.matrix.custom.html"_ls},
{"m.relates_to"_ls,
QJsonObject {
{"m.in_reply_to",
{"m.in_reply_to"_ls,
QJsonObject {
{"event_id", replyEventId}
{"event_id"_ls, replyEventId}
}
}
}
},
{"formatted_body",
"<mx-reply><blockquote><a href=\"https://matrix.to/#/" +
id() + "/" +
replyEventId +
"\">In reply to</a> <a href=\"https://matrix.to/#/" +
replyEvt.senderId() + "\">" + replyEvt.senderId() +
"</a><br>" + eventToString(replyEvt, Qt::RichText) +
"</blockquote></mx-reply>" + html
{"formatted_body"_ls,
"<mx-reply><blockquote><a href=\"https://matrix.to/#/%1/%2\">In reply to</a> <a href=\"https://matrix.to/#/%3\">%4</a><br>%5</blockquote></mx-reply>%6"_ls.arg(id(), replyEventId, replyEvt.senderId(), replyEvt.senderId(), eventToString(replyEvt, Qt::RichText), html)
}
};
// clang-format on
postJson("m.room.message", json);
postJson("m.room.message"_ls, json);
return;
}
@@ -1001,37 +999,37 @@ QString NeoChatRoom::joinRule() const
void NeoChatRoom::setJoinRule(const QString &joinRule)
{
if (!canSendState("m.room.join_rules")) {
if (!canSendState("m.room.join_rules"_ls)) {
qWarning() << "Power level too low to set join rules";
return;
}
setState("m.room.join_rules", "", QJsonObject{{"join_rule", joinRule}});
setState("m.room.join_rules"_ls, {}, QJsonObject{{"join_rule"_ls, joinRule}});
// Not emitting joinRuleChanged() here, since that would override the change in the UI with the *current* value, which is not the *new* value.
}
QString NeoChatRoom::historyVisibility() const
{
return currentState().get("m.room.history_visibility")->contentJson()["history_visibility"_ls].toString();
return currentState().get("m.room.history_visibility"_ls)->contentJson()["history_visibility"_ls].toString();
}
void NeoChatRoom::setHistoryVisibility(const QString &historyVisibilityRule)
{
if (!canSendState("m.room.history_visibility")) {
if (!canSendState("m.room.history_visibility"_ls)) {
qWarning() << "Power level too low to set history visibility";
return;
}
setState("m.room.history_visibility", "", QJsonObject{{"history_visibility", historyVisibilityRule}});
setState("m.room.history_visibility"_ls, {}, QJsonObject{{"history_visibility"_ls, historyVisibilityRule}});
// Not emitting historyVisibilityChanged() here, since that would override the change in the UI with the *current* value, which is not the *new* value.
}
bool NeoChatRoom::defaultUrlPreviewState() const
{
auto urlPreviewsDisabled = currentState().get("org.matrix.room.preview_urls");
auto urlPreviewsDisabled = currentState().get("org.matrix.room.preview_urls"_ls);
// Some rooms will not have this state event set so check for a nullptr return.
if (urlPreviewsDisabled != nullptr) {
return !urlPreviewsDisabled->contentJson()["disable"].toBool();
return !urlPreviewsDisabled->contentJson()["disable"_ls].toBool();
} else {
return false;
}
@@ -1039,7 +1037,7 @@ bool NeoChatRoom::defaultUrlPreviewState() const
void NeoChatRoom::setDefaultUrlPreviewState(const bool &defaultUrlPreviewState)
{
if (!canSendState("org.matrix.room.preview_urls")) {
if (!canSendState("org.matrix.room.preview_urls"_ls)) {
qWarning() << "Power level too low to set the default URL preview state for the room";
return;
}
@@ -1073,13 +1071,13 @@ void NeoChatRoom::setDefaultUrlPreviewState(const bool &defaultUrlPreviewState)
*
* You just have to set disable to true to disable URL previews by default.
*/
setState("org.matrix.room.preview_urls", "", QJsonObject{{"disable", !defaultUrlPreviewState}});
setState("org.matrix.room.preview_urls"_ls, {}, QJsonObject{{"disable"_ls, !defaultUrlPreviewState}});
}
bool NeoChatRoom::urlPreviewEnabled() const
{
if (hasAccountData("org.matrix.room.preview_urls")) {
return !accountData("org.matrix.room.preview_urls")->contentJson()["disable"].toBool();
if (hasAccountData("org.matrix.room.preview_urls"_ls)) {
return !accountData("org.matrix.room.preview_urls"_ls)->contentJson()["disable"_ls].toBool();
} else {
return defaultUrlPreviewState();
}
@@ -1098,7 +1096,10 @@ void NeoChatRoom::setUrlPreviewEnabled(const bool &urlPreviewEnabled)
* "type": "org.matrix.room.preview_urls",
* }
*/
connection()->callApi<SetAccountDataPerRoomJob>(localUser()->id(), id(), "org.matrix.room.preview_urls", QJsonObject{{"disable", !urlPreviewEnabled}});
connection()->callApi<SetAccountDataPerRoomJob>(localUser()->id(),
id(),
"org.matrix.room.preview_urls"_ls,
QJsonObject{{"disable"_ls, !urlPreviewEnabled}});
}
void NeoChatRoom::setUserPowerLevel(const QString &userID, const int &powerLevel)
@@ -1107,7 +1108,7 @@ void NeoChatRoom::setUserPowerLevel(const QString &userID, const int &powerLevel
qWarning() << "Cannot modify the power level of the only user";
return;
}
if (!canSendState("m.room.power_levels")) {
if (!canSendState("m.room.power_levels"_ls)) {
qWarning() << "Power level too low to set user power levels";
return;
}
@@ -1117,14 +1118,14 @@ void NeoChatRoom::setUserPowerLevel(const QString &userID, const int &powerLevel
}
int clampPowerLevel = std::clamp(powerLevel, 0, 100);
auto powerLevelContent = currentState().get("m.room.power_levels")->contentJson();
auto powerLevelUserOverrides = powerLevelContent["users"].toObject();
auto powerLevelContent = currentState().get("m.room.power_levels"_ls)->contentJson();
auto powerLevelUserOverrides = powerLevelContent["users"_ls].toObject();
if (powerLevelUserOverrides[userID] != clampPowerLevel) {
powerLevelUserOverrides[userID] = clampPowerLevel;
powerLevelContent["users"] = powerLevelUserOverrides;
powerLevelContent["users"_ls] = powerLevelUserOverrides;
setState("m.room.power_levels", "", powerLevelContent);
setState("m.room.power_levels"_ls, {}, powerLevelContent);
}
}
@@ -1140,19 +1141,19 @@ int NeoChatRoom::getUserPowerLevel(const QString &userId) const
int NeoChatRoom::powerLevel(const QString &eventName, const bool &isStateEvent) const
{
const auto powerLevelEvent = currentState().get<RoomPowerLevelsEvent>();
if (eventName == "ban") {
if (eventName == "ban"_ls) {
return powerLevelEvent->ban();
} else if (eventName == "kick") {
} else if (eventName == "kick"_ls) {
return powerLevelEvent->kick();
} else if (eventName == "invite") {
} else if (eventName == "invite"_ls) {
return powerLevelEvent->invite();
} else if (eventName == "redact") {
} else if (eventName == "redact"_ls) {
return powerLevelEvent->redact();
} else if (eventName == "users_default") {
} else if (eventName == "users_default"_ls) {
return powerLevelEvent->usersDefault();
} else if (eventName == "state_default") {
} else if (eventName == "state_default"_ls) {
return powerLevelEvent->stateDefault();
} else if (eventName == "events_default") {
} else if (eventName == "events_default"_ls) {
return powerLevelEvent->eventsDefault();
} else if (isStateEvent) {
return powerLevelEvent->powerLevelForState(eventName);
@@ -1163,7 +1164,7 @@ int NeoChatRoom::powerLevel(const QString &eventName, const bool &isStateEvent)
void NeoChatRoom::setPowerLevel(const QString &eventName, const int &newPowerLevel, const bool &isStateEvent)
{
auto powerLevelContent = currentState().get("m.room.power_levels")->contentJson();
auto powerLevelContent = currentState().get("m.room.power_levels"_ls)->contentJson();
int clampPowerLevel = std::clamp(newPowerLevel, 0, 100);
int powerLevel = 0;
@@ -1174,215 +1175,215 @@ void NeoChatRoom::setPowerLevel(const QString &eventName, const int &newPowerLev
powerLevelContent[eventName] = clampPowerLevel;
}
} else {
auto eventPowerLevels = powerLevelContent["events"].toObject();
auto eventPowerLevels = powerLevelContent["events"_ls].toObject();
if (eventPowerLevels.contains(eventName)) {
powerLevel = eventPowerLevels[eventName].toInt();
} else {
if (isStateEvent) {
powerLevel = powerLevelContent["state_default"].toInt();
powerLevel = powerLevelContent["state_default"_ls].toInt();
} else {
powerLevel = powerLevelContent["events_default"].toInt();
powerLevel = powerLevelContent["events_default"_ls].toInt();
}
}
if (powerLevel != clampPowerLevel) {
eventPowerLevels[eventName] = clampPowerLevel;
powerLevelContent["events"] = eventPowerLevels;
powerLevelContent["events"_ls] = eventPowerLevels;
}
}
setState("m.room.power_levels", "", powerLevelContent);
setState("m.room.power_levels"_ls, {}, powerLevelContent);
}
int NeoChatRoom::defaultUserPowerLevel() const
{
return powerLevel("users_default");
return powerLevel("users_default"_ls);
}
void NeoChatRoom::setDefaultUserPowerLevel(const int &newPowerLevel)
{
setPowerLevel("users_default", newPowerLevel);
setPowerLevel("users_default"_ls, newPowerLevel);
}
int NeoChatRoom::invitePowerLevel() const
{
return powerLevel("invite");
return powerLevel("invite"_ls);
}
void NeoChatRoom::setInvitePowerLevel(const int &newPowerLevel)
{
setPowerLevel("invite", newPowerLevel);
setPowerLevel("invite"_ls, newPowerLevel);
}
int NeoChatRoom::kickPowerLevel() const
{
return powerLevel("kick");
return powerLevel("kick"_ls);
}
void NeoChatRoom::setKickPowerLevel(const int &newPowerLevel)
{
setPowerLevel("kick", newPowerLevel);
setPowerLevel("kick"_ls, newPowerLevel);
}
int NeoChatRoom::banPowerLevel() const
{
return powerLevel("ban");
return powerLevel("ban"_ls);
}
void NeoChatRoom::setBanPowerLevel(const int &newPowerLevel)
{
setPowerLevel("ban", newPowerLevel);
setPowerLevel("ban"_ls, newPowerLevel);
}
int NeoChatRoom::redactPowerLevel() const
{
return powerLevel("redact");
return powerLevel("redact"_ls);
}
void NeoChatRoom::setRedactPowerLevel(const int &newPowerLevel)
{
setPowerLevel("redact", newPowerLevel);
setPowerLevel("redact"_ls, newPowerLevel);
}
int NeoChatRoom::statePowerLevel() const
{
return powerLevel("state_default");
return powerLevel("state_default"_ls);
}
void NeoChatRoom::setStatePowerLevel(const int &newPowerLevel)
{
setPowerLevel("state_default", newPowerLevel);
setPowerLevel("state_default"_ls, newPowerLevel);
}
int NeoChatRoom::defaultEventPowerLevel() const
{
return powerLevel("events_default");
return powerLevel("events_default"_ls);
}
void NeoChatRoom::setDefaultEventPowerLevel(const int &newPowerLevel)
{
setPowerLevel("events_default", newPowerLevel);
setPowerLevel("events_default"_ls, newPowerLevel);
}
int NeoChatRoom::powerLevelPowerLevel() const
{
return powerLevel("m.room.power_levels", true);
return powerLevel("m.room.power_levels"_ls, true);
}
void NeoChatRoom::setPowerLevelPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.power_levels", newPowerLevel, true);
setPowerLevel("m.room.power_levels"_ls, newPowerLevel, true);
}
int NeoChatRoom::namePowerLevel() const
{
return powerLevel("m.room.name", true);
return powerLevel("m.room.name"_ls, true);
}
void NeoChatRoom::setNamePowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.name", newPowerLevel, true);
setPowerLevel("m.room.name"_ls, newPowerLevel, true);
}
int NeoChatRoom::avatarPowerLevel() const
{
return powerLevel("m.room.avatar", true);
return powerLevel("m.room.avatar"_ls, true);
}
void NeoChatRoom::setAvatarPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.avatar", newPowerLevel, true);
setPowerLevel("m.room.avatar"_ls, newPowerLevel, true);
}
int NeoChatRoom::canonicalAliasPowerLevel() const
{
return powerLevel("m.room.canonical_alias", true);
return powerLevel("m.room.canonical_alias"_ls, true);
}
void NeoChatRoom::setCanonicalAliasPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.canonical_alias", newPowerLevel, true);
setPowerLevel("m.room.canonical_alias"_ls, newPowerLevel, true);
}
int NeoChatRoom::topicPowerLevel() const
{
return powerLevel("m.room.topic", true);
return powerLevel("m.room.topic"_ls, true);
}
void NeoChatRoom::setTopicPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.topic", newPowerLevel, true);
setPowerLevel("m.room.topic"_ls, newPowerLevel, true);
}
int NeoChatRoom::encryptionPowerLevel() const
{
return powerLevel("m.room.encryption", true);
return powerLevel("m.room.encryption"_ls, true);
}
void NeoChatRoom::setEncryptionPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.encryption", newPowerLevel, true);
setPowerLevel("m.room.encryption"_ls, newPowerLevel, true);
}
int NeoChatRoom::historyVisibilityPowerLevel() const
{
return powerLevel("m.room.history_visibility", true);
return powerLevel("m.room.history_visibility"_ls, true);
}
void NeoChatRoom::setHistoryVisibilityPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.history_visibility", newPowerLevel, true);
setPowerLevel("m.room.history_visibility"_ls, newPowerLevel, true);
}
int NeoChatRoom::pinnedEventsPowerLevel() const
{
return powerLevel("m.room.pinned_events", true);
return powerLevel("m.room.pinned_events"_ls, true);
}
void NeoChatRoom::setPinnedEventsPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.pinned_events", newPowerLevel, true);
setPowerLevel("m.room.pinned_events"_ls, newPowerLevel, true);
}
int NeoChatRoom::tombstonePowerLevel() const
{
return powerLevel("m.room.tombstone", true);
return powerLevel("m.room.tombstone"_ls, true);
}
void NeoChatRoom::setTombstonePowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.tombstone", newPowerLevel, true);
setPowerLevel("m.room.tombstone"_ls, newPowerLevel, true);
}
int NeoChatRoom::serverAclPowerLevel() const
{
return powerLevel("m.room.server_acl", true);
return powerLevel("m.room.server_acl"_ls, true);
}
void NeoChatRoom::setServerAclPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.room.server_acl", newPowerLevel, true);
setPowerLevel("m.room.server_acl"_ls, newPowerLevel, true);
}
int NeoChatRoom::spaceChildPowerLevel() const
{
return powerLevel("m.space.child", true);
return powerLevel("m.space.child"_ls, true);
}
void NeoChatRoom::setSpaceChildPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.space.child", newPowerLevel, true);
setPowerLevel("m.space.child"_ls, newPowerLevel, true);
}
int NeoChatRoom::spaceParentPowerLevel() const
{
return powerLevel("m.space.parent", true);
return powerLevel("m.space.parent"_ls, true);
}
void NeoChatRoom::setSpaceParentPowerLevel(const int &newPowerLevel)
{
setPowerLevel("m.space.parent", newPowerLevel, true);
setPowerLevel("m.space.parent"_ls, newPowerLevel, true);
}
QCoro::Task<void> NeoChatRoom::doDeleteMessagesByUser(const QString &user, QString reason)
@@ -1394,7 +1395,7 @@ QCoro::Task<void> NeoChatRoom::doDeleteMessagesByUser(const QString &user, QStri
}
}
for (const auto &e : events) {
auto job = connection()->callApi<RedactEventJob>(id(), QUrl::toPercentEncoding(e), connection()->generateTxnId(), reason);
auto job = connection()->callApi<RedactEventJob>(id(), QString::fromLatin1(QUrl::toPercentEncoding(e)), connection()->generateTxnId(), reason);
co_await qCoro(job, &BaseJob::finished);
if (job->error() != BaseJob::Success) {
qWarning() << "Error: \"" << job->error() << "\" while deleting messages. Aborting";
@@ -1445,26 +1446,26 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* Note to prevent race conditions any rule that is going ot be overridden later is not removed.
* If the default push notification state is chosen any exisiting rule needs to be removed.
*/
QJsonObject accountData = connection()->accountDataJson("m.push_rules");
QJsonObject accountData = connection()->accountDataJson("m.push_rules"_ls);
// For default and mute check for a room rule and remove if found.
if (state == PushNotificationState::Default || state == PushNotificationState::Mute) {
QJsonArray roomRuleArray = accountData["global"].toObject()["room"].toArray();
QJsonArray roomRuleArray = accountData["global"_ls].toObject()["room"_ls].toArray();
for (const auto &i : roomRuleArray) {
QJsonObject roomRule = i.toObject();
if (roomRule["rule_id"] == id()) {
Controller::instance().activeConnection()->callApi<DeletePushRuleJob>("global", "room", id());
if (roomRule["rule_id"_ls] == id()) {
Controller::instance().activeConnection()->callApi<DeletePushRuleJob>("global"_ls, "room"_ls, id());
}
}
}
// For default, all and @mentions and keywords check for an override rule and remove if found.
if (state == PushNotificationState::Default || state == PushNotificationState::All || state == PushNotificationState::MentionKeyword) {
QJsonArray overrideRuleArray = accountData["global"].toObject()["override"].toArray();
QJsonArray overrideRuleArray = accountData["global"_ls].toObject()["override"_ls].toArray();
for (const auto &i : overrideRuleArray) {
QJsonObject overrideRule = i.toObject();
if (overrideRule["rule_id"] == id()) {
Controller::instance().activeConnection()->callApi<DeletePushRuleJob>("global", "override", id());
if (overrideRule["rule_id"_ls] == id()) {
Controller::instance().activeConnection()->callApi<DeletePushRuleJob>("global"_ls, "override"_ls, id());
}
}
}
@@ -1480,7 +1481,7 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* "don't_notify"
* ]
*/
const QVector<QVariant> actions = {"dont_notify"};
const QVector<QVariant> actions = {"dont_notify"_ls};
/**
* Setup the push condition to get all events for the current room
* see https://spec.matrix.org/v1.3/client-server-api/#conditions-1
@@ -1494,15 +1495,17 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* ]
*/
PushCondition pushCondition;
pushCondition.kind = "event_match";
pushCondition.key = "room_id";
pushCondition.kind = "event_match"_ls;
pushCondition.key = "room_id"_ls;
pushCondition.pattern = id();
const QVector<PushCondition> conditions = {pushCondition};
// Add new override rule and make sure it's enabled
auto job = Controller::instance().activeConnection()->callApi<SetPushRuleJob>("global", "override", id(), actions, "", "", conditions, "");
auto job = Controller::instance()
.activeConnection()
->callApi<SetPushRuleJob>("global"_ls, "override"_ls, id(), actions, QString(), QString(), conditions, QString());
connect(job, &BaseJob::success, this, [this]() {
auto enableJob = Controller::instance().activeConnection()->callApi<SetPushRuleEnabledJob>("global", "override", id(), true);
auto enableJob = Controller::instance().activeConnection()->callApi<SetPushRuleEnabledJob>("global"_ls, "override"_ls, id(), true);
connect(enableJob, &BaseJob::success, this, [this]() {
m_pushNotificationStateUpdating = false;
});
@@ -1522,13 +1525,15 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* "don't_notify"
* ]
*/
const QVector<QVariant> actions = {"dont_notify"};
const QVector<QVariant> actions = {"dont_notify"_ls};
// No conditions for a room rule
const QVector<PushCondition> conditions;
auto setJob = Controller::instance().activeConnection()->callApi<SetPushRuleJob>("global", "room", id(), actions, "", "", conditions, "");
auto setJob = Controller::instance()
.activeConnection()
->callApi<SetPushRuleJob>("global"_ls, "room"_ls, id(), actions, QString(), QString(), conditions, QString());
connect(setJob, &BaseJob::success, this, [this]() {
auto enableJob = Controller::instance().activeConnection()->callApi<SetPushRuleEnabledJob>("global", "room", id(), true);
auto enableJob = Controller::instance().activeConnection()->callApi<SetPushRuleEnabledJob>("global"_ls, "room"_ls, id(), true);
connect(enableJob, &BaseJob::success, this, [this]() {
m_pushNotificationStateUpdating = false;
});
@@ -1550,16 +1555,18 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
* ]
*/
QJsonObject tweaks;
tweaks.insert("set_tweak", "sound");
tweaks.insert("value", "default");
const QVector<QVariant> actions = {"notify", tweaks};
tweaks.insert("set_tweak"_ls, "sound"_ls);
tweaks.insert("value"_ls, "default"_ls);
const QVector<QVariant> actions = {"notify"_ls, tweaks};
// No conditions for a room rule
const QVector<PushCondition> conditions;
// Add new room rule and make sure enabled
auto setJob = Controller::instance().activeConnection()->callApi<SetPushRuleJob>("global", "room", id(), actions, "", "", conditions, "");
auto setJob = Controller::instance()
.activeConnection()
->callApi<SetPushRuleJob>("global"_ls, "room"_ls, id(), actions, QString(), QString(), conditions, QString());
connect(setJob, &BaseJob::success, this, [this]() {
auto enableJob = Controller::instance().activeConnection()->callApi<SetPushRuleEnabledJob>("global", "room", id(), true);
auto enableJob = Controller::instance().activeConnection()->callApi<SetPushRuleEnabledJob>("global"_ls, "room"_ls, id(), true);
connect(enableJob, &BaseJob::success, this, [this]() {
m_pushNotificationStateUpdating = false;
});
@@ -1573,23 +1580,23 @@ void NeoChatRoom::setPushNotificationState(PushNotificationState::State state)
void NeoChatRoom::updatePushNotificationState(QString type)
{
if (type != "m.push_rules" || m_pushNotificationStateUpdating) {
if (type != "m.push_rules"_ls || m_pushNotificationStateUpdating) {
return;
}
QJsonObject accountData = connection()->accountDataJson("m.push_rules");
QJsonObject accountData = connection()->accountDataJson("m.push_rules"_ls);
// First look for a room rule with the room id
QJsonArray roomRuleArray = accountData["global"].toObject()["room"].toArray();
QJsonArray roomRuleArray = accountData["global"_ls].toObject()["room"_ls].toArray();
for (const auto &i : roomRuleArray) {
QJsonObject roomRule = i.toObject();
if (roomRule["rule_id"] == id()) {
QString notifyAction = roomRule["actions"].toArray()[0].toString();
if (notifyAction == "notify") {
if (roomRule["rule_id"_ls] == id()) {
QString notifyAction = roomRule["actions"_ls].toArray()[0].toString();
if (notifyAction == "notify"_ls) {
m_currentPushNotificationState = PushNotificationState::All;
Q_EMIT pushNotificationStateChanged(m_currentPushNotificationState);
return;
} else if (notifyAction == "dont_notify") {
} else if (notifyAction == "dont_notify"_ls) {
m_currentPushNotificationState = PushNotificationState::MentionKeyword;
Q_EMIT pushNotificationStateChanged(m_currentPushNotificationState);
return;
@@ -1598,12 +1605,12 @@ void NeoChatRoom::updatePushNotificationState(QString type)
}
// Check for an override rule with the room id
QJsonArray overrideRuleArray = accountData["global"].toObject()["override"].toArray();
QJsonArray overrideRuleArray = accountData["global"_ls].toObject()["override"_ls].toArray();
for (const auto &i : overrideRuleArray) {
QJsonObject overrideRule = i.toObject();
if (overrideRule["rule_id"] == id()) {
QString notifyAction = overrideRule["actions"].toArray()[0].toString();
if (notifyAction == "dont_notify") {
if (overrideRule["rule_id"_ls] == id()) {
QString notifyAction = overrideRule["actions"_ls].toArray()[0].toString();
if (notifyAction == "dont_notify"_ls) {
m_currentPushNotificationState = PushNotificationState::Mute;
Q_EMIT pushNotificationStateChanged(m_currentPushNotificationState);
return;
@@ -1682,7 +1689,7 @@ QVariantMap NeoChatRoom::chatBoxReplyUser() const
if (m_chatBoxReplyId.isEmpty()) {
return emptyUser;
}
return getUser(static_cast<NeoChatUser *>(user((*findInTimeline(m_chatBoxReplyId))->senderId())));
return getUser(user((*findInTimeline(m_chatBoxReplyId))->senderId()));
}
QString NeoChatRoom::chatBoxReplyMessage() const
@@ -1698,7 +1705,7 @@ QVariantMap NeoChatRoom::chatBoxEditUser() const
if (m_chatBoxEditId.isEmpty()) {
return emptyUser;
}
return getUser(static_cast<NeoChatUser *>(user((*findInTimeline(m_chatBoxEditId))->senderId())));
return getUser(user((*findInTimeline(m_chatBoxEditId))->senderId()));
}
QString NeoChatRoom::chatBoxEditMessage() const
@@ -1759,9 +1766,9 @@ void NeoChatRoom::replyLastMessage()
if (e->msgtype() != MessageEventType::Unknown) {
QString eventId;
if (content.contains("m.new_content")) {
if (content.contains("m.new_content"_ls)) {
// 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();
eventId = content["m.relates_to"_ls].toObject()["event_id"_ls].toString();
} else {
// For any message that isn't an edit return the id of the current message
eventId = (*it)->id();
@@ -1793,9 +1800,9 @@ void NeoChatRoom::editLastMessage()
if (e->msgtype() != MessageEventType::Unknown) {
QString eventId;
if (content.contains("m.new_content")) {
if (content.contains("m.new_content"_ls)) {
// 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();
eventId = content["m.relates_to"_ls].toObject()["event_id"_ls].toString();
} else {
// For any message that isn't an edit return the id of the current message
eventId = (*it)->id();
@@ -1809,10 +1816,7 @@ void NeoChatRoom::editLastMessage()
bool NeoChatRoom::canEncryptRoom() const
{
#ifdef Quotient_E2EE_ENABLED
return !usesEncryption() && canSendState("m.room.encryption");
#endif
return false;
return !usesEncryption() && canSendState("m.room.encryption"_ls);
}
PollHandler *NeoChatRoom::poll(const QString &eventId)
@@ -1904,33 +1908,34 @@ int NeoChatRoom::maxRoomVersion() const
}
return maxVersion;
}
NeoChatUser *NeoChatRoom::directChatRemoteUser() const
Quotient::User *NeoChatRoom::directChatRemoteUser() const
{
return dynamic_cast<NeoChatUser *>(connection()->directChatUsers(this)[0]);
return connection()->directChatUsers(this)[0];
}
void NeoChatRoom::sendLocation(float lat, float lon, const QString &description)
{
QJsonObject locationContent{
{"uri", "geo:%1,%2"_ls.arg(QString::number(lat), QString::number(lon))},
{"uri"_ls, "geo:%1,%2"_ls.arg(QString::number(lat), QString::number(lon))},
};
if (!description.isEmpty()) {
locationContent["description"] = description;
locationContent["description"_ls] = description;
}
QJsonObject content{
{"body", i18nc("'Lat' and 'Lon' as in Latitude and Longitude", "Lat: %1, Lon: %2", lat, lon)},
{"msgtype", "m.location"},
{"geo_uri", "geo:%1,%2"_ls.arg(QString::number(lat), QString::number(lon))},
{"org.matrix.msc3488.location", locationContent},
{"org.matrix.msc3488.asset",
{"body"_ls, i18nc("'Lat' and 'Lon' as in Latitude and Longitude", "Lat: %1, Lon: %2", lat, lon)},
{"msgtype"_ls, "m.location"_ls},
{"geo_uri"_ls, "geo:%1,%2"_ls.arg(QString::number(lat), QString::number(lon))},
{"org.matrix.msc3488.location"_ls, locationContent},
{"org.matrix.msc3488.asset"_ls,
QJsonObject{
{"type", "m.pin"},
{"type"_ls, "m.pin"_ls},
}},
{"org.matrix.msc1767.text", i18nc("'Lat' and 'Lon' as in Latitude and Longitude", "Lat: %1, Lon: %2", lat, lon)},
{"org.matrix.msc1767.text"_ls, i18nc("'Lat' and 'Lon' as in Latitude and Longitude", "Lat: %1, Lon: %2", lat, lon)},
};
postJson("m.room.message", content);
postJson("m.room.message"_ls, content);
}
QByteArray NeoChatRoom::roomAcountDataJson(const QString &eventType)
@@ -1938,7 +1943,7 @@ QByteArray NeoChatRoom::roomAcountDataJson(const QString &eventType)
return QJsonDocument(accountData(eventType)->fullJson()).toJson();
}
QUrl NeoChatRoom::avatarForMember(NeoChatUser *user) const
QUrl NeoChatRoom::avatarForMember(Quotient::User *user) const
{
const auto &url = memberAvatarUrl(user->id());
if (url.isEmpty() || url.scheme() != "mxc"_ls) {
@@ -1954,7 +1959,7 @@ QUrl NeoChatRoom::avatarForMember(NeoChatUser *user) const
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();
const QString &replyEventId = event.contentJson()["m.relates_to"_ls].toObject()["m.in_reply_to"_ls].toObject()["event_id"_ls].toString();
if (replyEventId.isEmpty()) {
return {};
};

View File

@@ -10,10 +10,15 @@
#include <QTextCursor>
#include <QCoroTask>
#include <Quotient/user.h>
#include "neochatuser.h"
#include "pollhandler.h"
namespace Quotient
{
class User;
}
class PushNotificationState : public QObject
{
Q_OBJECT
@@ -64,7 +69,7 @@ class NeoChatRoom : public Quotient::Room
*
* The list does not include the local user.
*
* This is different to getting a list of NeoChatUser objects or Quotient::User objects
* This is different to getting a list of Quotient::User objects
* 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 puts the result as a list of QVariantMap objects.
@@ -76,7 +81,7 @@ class NeoChatRoom : public Quotient::Room
* - displayName - Display name in the context of this room.
* - display - Name in the context of this room.
*
* @sa Quotient::User, NeoChatUser
* @sa Quotient::User
*/
Q_PROPERTY(QVariantList usersTyping READ getUsersTyping NOTIFY typingChanged)
@@ -119,7 +124,7 @@ class NeoChatRoom : public Quotient::Room
/**
* @brief Get a user object for the other person in a direct chat.
*/
Q_PROPERTY(NeoChatUser *directChatRemoteUser READ directChatRemoteUser CONSTANT)
Q_PROPERTY(Quotient::User *directChatRemoteUser READ directChatRemoteUser CONSTANT)
/**
* @brief If the room is a space.
@@ -181,9 +186,6 @@ class NeoChatRoom : public Quotient::Room
/**
* @brief Whether the local user can encrypt the room.
*
* Requires libQuotient 0.7 compiled with the Quotient_E2EE_ENABLED parameter to
* be able to return true.
*
* A local user can encrypt a room if they have permission to send the m.room.encryption
* state event.
*
@@ -316,7 +318,7 @@ class NeoChatRoom : public Quotient::Room
/**
* @brief Get the user for the message being replied to.
*
* This is different to getting a NeoChatUser object or Quotient::User object
* This is different to getting a 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.
*
@@ -329,9 +331,9 @@ class NeoChatRoom : public Quotient::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.
* - object - The Quotient::User object for the user.
*
* @sa getUser, Quotient::User, NeoChatUser
* @sa getUser, Quotient::User
*/
Q_PROPERTY(QVariantMap chatBoxReplyUser READ chatBoxReplyUser NOTIFY chatBoxReplyIdChanged)
@@ -345,7 +347,7 @@ class NeoChatRoom : public Quotient::Room
/**
* @brief Get the user for the message being edited.
*
* This is different to getting a NeoChatUser object or Quotient::User object
* This is different to getting a 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.
*
@@ -358,9 +360,9 @@ class NeoChatRoom : public Quotient::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.
* - object - The Quotient::User object for the user.
*
* @sa getUser, Quotient::User, NeoChatUser
* @sa getUser, Quotient::User
*/
Q_PROPERTY(QVariantMap chatBoxEditUser READ chatBoxEditUser NOTIFY chatBoxEditIdChanged)
@@ -392,7 +394,7 @@ public:
/**
* @brief Get a list of users in the context of this room.
*
* This is different to getting a list of NeoChatUser objects or Quotient::User objects
* This is different to getting a list of Quotient::User objects
* 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 returns the result as a list of QVariantMap objects.
@@ -407,14 +409,14 @@ public:
* - avatarMediaId - Avatar id in the context of this room.
* - color - Color for the user.
*
* @sa Quotient::User, NeoChatUser
* @sa Quotient::User
*/
Q_INVOKABLE [[nodiscard]] QVariantList getUsers(const QString &keyword, int limit = -1) const;
/**
* @brief Get a user in the context of this room.
*
* This is different to getting a NeoChatUser object or Quotient::User object
* This is different to getting a 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.
@@ -431,16 +433,16 @@ public:
* - 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.
* - object - The Quotient::User object for the user.
*
* @sa Quotient::User, NeoChatUser
* @sa Quotient::User
*/
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
* This is different to getting a 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.
@@ -457,11 +459,11 @@ public:
* - 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.
* - object - The Quotient::User object for the user.
*
* @sa Quotient::User, NeoChatUser
* @sa Quotient::User
*/
Q_INVOKABLE [[nodiscard]] QVariantMap getUser(NeoChatUser *user) const;
Q_INVOKABLE [[nodiscard]] QVariantMap getUser(Quotient::User *user) const;
[[nodiscard]] QVariantList getUsersTyping() const;
@@ -602,7 +604,7 @@ public:
[[nodiscard]] QString avatarMediaId() const;
NeoChatUser *directChatRemoteUser() const;
Quotient::User *directChatRemoteUser() const;
[[nodiscard]] bool isSpace();
@@ -818,7 +820,7 @@ public:
*/
Q_INVOKABLE QByteArray roomAcountDataJson(const QString &eventType);
Q_INVOKABLE [[nodiscard]] QUrl avatarForMember(NeoChatUser *user) const;
Q_INVOKABLE [[nodiscard]] QUrl avatarForMember(Quotient::User *user) const;
/**
* @brief Returns the event that is being replied to. This includes events that were manually loaded using NeoChatRoom::loadReply.

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