Compare commits

..

110 Commits

Author SHA1 Message Date
John Preston
c8d1e01159 Beta version 2.9.8.
- And still debugging a video playback crash in 32 bit Windows version.
2021-08-23 18:30:14 +03:00
John Preston
7e6f24552a Add basic OpenGL info to crash annotations. 2021-08-23 18:29:20 +03:00
John Preston
27d58ba07b Try to do a non-failed double->crl::time cast.
A crash on some old CPUs show, that in video frame processing
sometimes a cast from double to crl::time fails, writing to
the resulting crl::time value INT64_MIN (0x8000000000000000).

This is shown in crash logs, with lines like:

...,rounded:104,casted:-9223372036854775808,...

where logs are written like:

...
).arg(std::round(adjust * _options.speed)
).arg(crl::time(std::round(adjust * _options.speed))
...

I don't know what to do and how to workaround this. Trying other casts.
2021-08-23 17:58:59 +03:00
23rd
3a92a181a1 Fixed editing on Up arrow in sections with non-empty input field. 2021-08-23 13:57:35 +03:00
23rd
ddd5617043 Fixed processing GIF images as non-album files.
Fixed #16844.
2021-08-23 13:57:31 +03:00
John Preston
70b3e414ce Fix crash in Update-requested-by-tg://-link. 2021-08-23 13:54:49 +03:00
John Preston
2b04653f24 Beta version 2.9.7.
- Still debugging a video playback crash in 32 bit Windows version.
2021-08-23 12:21:09 +03:00
John Preston
868015da25 Add extensive video playback crash logs. 2021-08-23 12:17:40 +03:00
John Preston
7aeffa242e Beta version 2.9.6.
- Debugging a video playback crash in 32 bit Windows version.
2021-08-21 09:34:26 +03:00
John Preston
3136c0586e Add some more assertions to debug a crash. 2021-08-21 09:33:20 +03:00
John Preston
fb0fcbca7f Remove redundant -static-libstdc++ for Updater. 2021-08-20 21:14:39 +03:00
John Preston
0d449c037b Beta version 2.9.5: Fix hide workaround for media viewer. 2021-08-20 19:56:40 +03:00
John Preston
4d98230694 Beta version 2.9.5.
- Tile chat background patterns horizontally.
- Fix a rare crash in spellchecker on Windows.
- Fix animated chat backgrounds in Saved Messages.
- Fix "Sorry, group is inaccessible" message in scheduled voice chats.
2021-08-20 18:42:13 +03:00
John Preston
3d36e501a1 Add some assertions to debug a crash in video playback. 2021-08-20 18:42:13 +03:00
John Preston
b4eb9a0827 Fix single-colored patterns. 2021-08-20 16:24:26 +03:00
John Preston
aaf0015be4 Improve pattern wallpaper preview in Settings. 2021-08-20 16:14:09 +03:00
John Preston
1e8e163bb1 Tile patterns horizontally. 2021-08-20 15:55:10 +03:00
John Preston
f3f741e1eb Hide 'Tile' option in generated backgrounds. 2021-08-20 15:14:28 +03:00
John Preston
44f52ca6cd Fix solid color background preview. 2021-08-20 14:54:11 +03:00
John Preston
2b6e04bca3 Apply initial bubble opacity in QImage bubble backgrounds. 2021-08-20 14:54:11 +03:00
John Preston
784d57a2bc Use QImage bubbles background for some Media parts. 2021-08-20 14:54:11 +03:00
John Preston
f4fdadd3b0 Allow arbitrary QImage as outgoing bubbles background. 2021-08-20 14:54:11 +03:00
John Preston
1cc9a52461 Fix my speaking status freeze in voice chats. 2021-08-18 17:52:23 +03:00
John Preston
cd52982752 Hopefully fix an assertion violation in voice chats. 2021-08-18 17:45:21 +03:00
John Preston
4dd58b79e9 Fix forward of a bot message with a game from a group. 2021-08-18 16:43:22 +03:00
John Preston
c5c94276c2 Allow editing caption of forwarded audio file.
Fixes https://bugs.telegram.org/c/3025
2021-08-18 16:29:05 +03:00
John Preston
8e0b9b685c Show 'X subscribers' in channel ConfirmInviteBox.
Fixes https://bugs.telegram.org/c/2059
2021-08-18 15:57:52 +03:00
John Preston
1792bed721 Remove additional padding in shared contacts. 2021-08-18 15:52:04 +03:00
John Preston
a502cbc06e Move message link up in registered shared contacts.
Fixes #16804.
2021-08-18 15:48:30 +03:00
John Preston
ddda7b8c52 Fix crash in application Dock menu on macOS. 2021-08-18 15:44:38 +03:00
John Preston
0f19ba3231 Fix spellcheck crash on Windows on certain strings. 2021-08-18 15:22:27 +03:00
John Preston
36486a3d73 Fix creating a theme from a default one.
Regression was introduced in 79cc797aff.
2021-08-18 14:52:57 +03:00
John Preston
02f48a7781 Don't allow selected items together with text. 2021-08-18 14:52:49 +03:00
John Preston
c77f4dd794 Fix build on Linux. 2021-08-18 13:06:47 +03:00
John Preston
ca31a08182 Fix 'Sorry, group is inac...' in scheduled voice chat. 2021-08-18 11:34:16 +03:00
John Preston
33936195a1 Animate the chat background in Saved Messages. 2021-08-18 11:33:37 +03:00
John Preston
67bafa02fe Remove attempt of a shadow Qt build. 2021-08-17 18:15:55 +03:00
John Preston
1ef0046002 Beta version 2.9.4.
- Choose one from dozens of new gorgeous animated backgrounds
in Chat Settings > Chat background.
2021-08-17 18:09:18 +03:00
John Preston
f2f19b14eb Fix reading one message if last one is outgoing. 2021-08-17 18:07:20 +03:00
John Preston
662966ba31 Support patterns with negative intensity. 2021-08-17 17:35:10 +03:00
John Preston
5383ae3d96 Fix log in after password change by email. 2021-08-17 15:51:36 +03:00
John Preston
d80b25944e Fix Snap build on GitHub Actions. 2021-08-17 15:17:58 +03:00
23rd
76813db3ad Completed ability to recover cloud password with email. 2021-08-17 15:08:57 +03:00
John Preston
c3595f2e31 Ask for a new password when recovering by email. 2021-08-17 15:07:58 +03:00
John Preston
5a882d1fdc Rotate background in ListWidget. 2021-08-17 14:55:40 +03:00
John Preston
ce6f9f580f Remove unused ColorizePattern function. 2021-08-17 13:06:28 +03:00
John Preston
52b9a1fceb Log all Qt messages as usual in debug builds. 2021-08-17 12:25:13 +03:00
John Preston
1209b2692a Generate correct next rotated gradient. 2021-08-16 17:15:02 +03:00
John Preston
2abcb51dda Filter out patterns without background colors. 2021-08-16 17:14:34 +03:00
John Preston
7a06eccaec Make complex gradients animate on outgoing messages. 2021-08-16 16:07:43 +03:00
John Preston
a1f81e4de8 Generate static complex gradients. 2021-08-16 13:24:15 +03:00
John Preston
689378ee04 Prefer 1280x720 resolution for camera video. 2021-08-16 10:26:08 +03:00
John Preston
b239506150 Fix pattern wallpaper preview on retina screens. 2021-08-16 10:26:08 +03:00
John Preston
3dadcd9352 Animated transition on pattern-on-gradient resize. 2021-08-16 10:26:08 +03:00
John Preston
b9a9520ef5 Don't blend SoftLight patterns in realtime. 2021-08-16 10:26:08 +03:00
John Preston
2b46f87d7b Cache background quickly if no buttons pressed. 2021-08-16 10:26:08 +03:00
John Preston
2667bb3568 Move background caching to Window::SessionController. 2021-08-16 10:26:08 +03:00
John Preston
1bc5277d51 Show color / gradient wallpapers in WebPage previews. 2021-08-16 10:26:08 +03:00
John Preston
436d7b9d82 Add support for linear gradients without patterns. 2021-08-16 10:26:08 +03:00
John Preston
ba7e976fe2 Fix background sample generation. 2021-08-16 10:26:08 +03:00
John Preston
c2b1187948 Start support of linear gradient wallpapers. 2021-08-16 10:26:08 +03:00
23rd
1fd28d5cfb Removed MTP* from public interface of Api::CloudPassword. 2021-08-15 13:44:43 +03:00
23rd
eec58137e9 Fixed build for Linux. 2021-08-15 13:26:43 +03:00
Ilya Fedin
e7d39e6046 Get rid of GtkIntegration::initializeSettings use 2021-08-13 15:21:19 +03:00
Ilya Fedin
63a92cb90a Log icon theme 2021-08-13 15:21:19 +03:00
John Preston
85cc3b30a0 Don't use MTP* for WallPaper flags. 2021-08-12 12:32:30 +03:00
John Preston
474a6a71d9 Move unread mentions menu to chat_helpers/send_context_menu. 2021-08-12 10:06:16 +03:00
John Preston
393173c1da Finish 'Mark mentions as read' context menu. 2021-08-12 09:46:02 +03:00
John Preston
badc27eda4 Fix build with a correct lib_ui revision. 2021-08-12 09:03:19 +03:00
test
920f3b245b Update lang.strings 2021-08-12 08:52:56 +03:00
test
f189ffc6ac Summary 2021-08-12 08:52:56 +03:00
Nicholas Guriev
840bb447ba Mention some missing includes in payments/ subdirectory 2021-08-12 08:51:45 +03:00
Ilya Fedin
414456d003 Revert "Use gtk clipboard when available to avoid https://bugreports.qt.io/browse/QTBUG-56595"
Fixed in Qt by https://codereview.qt-project.org/c/qt/qtbase/+/306771

This reverts commit 3a91003eea.
2021-08-12 08:51:10 +03:00
23rd
ea3191badf Fixed Github CI build. 2021-08-12 08:34:51 +03:00
John Preston
4452edcaad Update release asset uploading script. 2021-08-12 08:34:47 +03:00
23rd
76eb00cea9 Added drafts saving on account switching. 2021-08-12 02:36:41 +03:00
23rd
b3622b413e Added ability to set custom auto-lock timer. 2021-08-12 02:36:41 +03:00
23rd
b55383efe7 Moved time input widgets to lib_ui. 2021-08-12 02:36:41 +03:00
23rd
852e46f0c9 Added filepath removal for modified images in photo editor.
Fixed #16791.
2021-08-12 02:35:53 +03:00
John Preston
84fef1f045 Fix linking to QtSvg properly. 2021-08-11 20:22:45 +03:00
John Preston
6cadf54874 Add support for SVG patterns in wallpapers. 2021-08-11 19:56:12 +03:00
John Preston
e8fc874456 Build and link with QtSvg. 2021-08-11 19:55:47 +03:00
John Preston
c79cd0b692 Use Images::Read instead of App::readImage. 2021-08-11 18:55:08 +03:00
John Preston
b150ab8ef5 Add .tgv as a known mime type. 2021-08-11 18:23:14 +03:00
Ilya Fedin
8b7b0fa570 Remove -externalupdater flag
Having a path to executable in /etc/tdesktop/externalupdater is a way more convenient and is enough
2021-08-11 18:20:52 +03:00
Ilya Fedin
a3ee1e4ed5 Remove mentions of unused -testmode flag 2021-08-11 18:20:52 +03:00
Ilya Fedin
349446e6b0 Lock issues once a day rather than once a hour 2021-08-11 17:56:25 +03:00
Ilya Fedin
97262a99c7 Get rid of osx and linux32 special targets 2021-08-11 16:59:27 +03:00
Ilya Fedin
1d2e34f5e9 Write Qt messages only to log in debug mode 2021-08-11 15:49:31 +03:00
Ilya Fedin
bc2fc94e25 Don't check libtgvoip defines, too big queue 2021-08-11 15:46:38 +03:00
Ilya Fedin
6f0e94a04a WebKitGTK support doesn't depend on GTK integration anymore 2021-08-11 15:46:38 +03:00
John Preston
60e43cfa3f Version 2.9.3.
- Fix requesting screencast rights on macOS (again).
2021-08-11 11:35:48 +03:00
John Preston
46885b7f9f Fix mouse input in layers in call window. 2021-08-11 11:06:34 +03:00
23rd
fff42a664c Fixed Github CI Windows build. 2021-08-11 05:53:16 +03:00
John Preston
437d35d8c4 Version 2.9.2: Fix build on macOS. 2021-08-10 19:24:56 +03:00
John Preston
36a5dd8d8b Version 2.9.2: Buffer more audio data.
I hope this fixes #16733.
2021-08-10 16:44:59 +03:00
John Preston
d8e99b4860 Version 2.9.2.
- Fix crashes and bugs in scheduled messages.
- Fix file sending after a call or voice chat on Windows.
- Fix main window title glitches on Windows 7.
2021-08-10 16:10:59 +03:00
John Preston
3cddcaa039 Update submodules. 2021-08-10 16:05:08 +03:00
John Preston
49078e5679 Apply a window title workaround on Windows 7.
Fixes #16785, fixes #16758, fixes #16721.
2021-08-10 15:46:18 +03:00
John Preston
1dec054766 Check if native window frame fits for saved geometry. 2021-08-10 15:46:18 +03:00
John Preston
91ef6f13c8 Use good bitrate for screen capture in calls. 2021-08-10 15:46:18 +03:00
John Preston
73c8f16340 Fix maximized window on Linux, update tg_angle. 2021-08-10 15:46:18 +03:00
23rd
cbad2469db Moved MTP cloud password from ApiWrap to Api::CloudPassword. 2021-08-10 15:46:18 +03:00
23rd
0ae260c6e1 Moved MTP blocked peers from ApiWrap to Api::BlockedPeers. 2021-08-10 15:46:18 +03:00
23rd
221ded6d54 Fixed handle of last message on Up arrow in sections on macOS. 2021-08-10 15:46:18 +03:00
23rd
6f80811ecd Fixed applying server messages as scheduled.
Fixed #16726 and many other problems.
2021-08-10 15:46:18 +03:00
23rd
5bd73bab9b Moved user privacy from ApiWrap to Api::UserPrivacy. 2021-08-10 15:46:18 +03:00
Ilya Fedin
ac86f3e5bd Use Communications category for tray icon
Since tdesktop fits it
2021-08-10 15:42:21 +03:00
GitHub Action
bae6a29326 Update User-Agent for DNS to Chrome 92.0.4515.107. 2021-08-09 10:21:57 +03:00
John Preston
dcf86f55af Version 2.9.1.
- Fix requesting screencast rights on macOS.
2021-07-30 21:28:24 +03:00
263 changed files with 5020 additions and 3737 deletions

View File

@@ -63,8 +63,6 @@ jobs:
- "DESKTOP_APP_DISABLE_X11_INTEGRATION"
- "DESKTOP_APP_DISABLE_WAYLAND_INTEGRATION"
- "DESKTOP_APP_DISABLE_GTK_INTEGRATION"
- "LIBTGVOIP_DISABLE_ALSA"
- "LIBTGVOIP_DISABLE_PULSEAUDIO"
env:
UPLOAD_ARTIFACT: "false"
@@ -94,9 +92,6 @@ jobs:
if [ "${{ matrix.defines }}" == "DESKTOP_APP_DISABLE_DBUS_INTEGRATION" ]; then
DEFINE="$DEFINE -D DESKTOP_APP_DISABLE_GTK_INTEGRATION=ON -D DESKTOP_APP_DISABLE_WEBKITGTK=ON"
fi
if [ "${{ matrix.defines }}" == "DESKTOP_APP_DISABLE_GTK_INTEGRATION" ]; then
DEFINE="$DEFINE -D DESKTOP_APP_DISABLE_WEBKITGTK=ON"
fi
echo Define from matrix: $DEFINE
echo "ARTIFACT_NAME=Telegram_${{ matrix.defines }}" >> $GITHUB_ENV
else

View File

@@ -2,7 +2,7 @@ name: 'Lock Threads'
on:
schedule:
- cron: '0 * * * *'
- cron: '0 0 * * *'
jobs:
lock:

View File

@@ -449,10 +449,11 @@ jobs:
git clone git://code.qt.io/qt/qt5.git qt_$QT
cd qt_$QT
perl init-repository --module-subset=qtbase,qtimageformats
perl init-repository --module-subset=qtbase,qtimageformats,qtsvg
git checkout v5.15.2
git submodule update qtbase
git submodule update qtimageformats
git submodule update qtsvg
cd qtbase
find ../../patches/qtbase_$QT -type f -print0 | sort -z | xargs -0 git apply
cd ..

View File

@@ -52,28 +52,34 @@ jobs:
- ""
env:
SDK: "10.0.18362.0"
VC: "call vcvars32.bat && cd Libraries"
GIT: "https://github.com"
QT: "5_15_2"
QT_VER: "5.15.2"
OPENSSL_VER: "1_1_1"
UPLOAD_ARTIFACT: "false"
ONLY_CACHE: "false"
MANUAL_CACHING: "2"
MANUAL_CACHING: "0"
DOC_PATH: "docs/building-win.md"
AUTO_CACHING: "1"
defaults:
run:
shell: cmd
working-directory: Libraries
steps:
- name: Get repository name.
shell: bash
working-directory: ${{ github.workspace }}
run: echo "REPO_NAME=${GITHUB_REPOSITORY##*/}" >> $GITHUB_ENV
- uses: ilammy/msvc-dev-cmd@v1.9.0
name: x86 Native Tools Command Prompt.
with:
arch: win32
- name: Set up environment paths.
shell: bash
working-directory: ${{ github.workspace }}
run: |
echo "C:\\Strawberry\\perl\\bin\\" >> $GITHUB_PATH
echo "C:\\Program Files\\NASM\\" >> $GITHUB_PATH
@@ -84,6 +90,8 @@ jobs:
p=`pwd | sed 's#^/[d]#d:#g' |sed 's#/#\\\\#g'`
echo "LibrariesPath=$p" >> $GITHUB_ENV
echo "QT=${QT_VER//./_}" >> $GITHUB_ENV
- name: Save msbuild version.
run: |
call vcvars32.bat
@@ -97,6 +105,7 @@ jobs:
- name: Generate cache key.
shell: bash
working-directory: ${{ github.workspace }}
run: |
curl -o $LibrariesPath/tg_owt-version.json https://api.github.com/repos/desktop-app/tg_owt/git/refs/heads/master
curl -o $LibrariesPath/tg_angle-version.json https://api.github.com/repos/desktop-app/tg_angle/git/refs/heads/master
@@ -108,7 +117,10 @@ jobs:
echo "CACHE_KEY=`md5sum CACHE_KEY.txt | awk '{ print $1 }'`" >> $GITHUB_ENV
- name: Choco installs.
run: choco install --no-progress -y nasm yasm jom ninja
run: |
choco install --allow-empty-checksums --no-progress -y yasm
choco install --no-progress -y nasm jom ninja
python -m pip install pywin32
- name: NuGet sources.
run: |
@@ -117,6 +129,7 @@ jobs:
- name: Patches.
shell: bash
working-directory: ${{ github.workspace }}
run: |
echo "Find necessary commit from doc."
checkoutCommit=$(grep -A 1 "cd patches" $REPO_NAME/$DOC_PATH | sed -n 2p)
@@ -139,8 +152,6 @@ jobs:
- name: LZMA.
run: |
%VC%
git clone %GIT%/telegramdesktop/lzma.git
cd lzma
cd C\Util\LzmaLib
@@ -155,8 +166,6 @@ jobs:
- name: OpenSSL.
if: steps.cache-openssl.outputs.cache-hit != 'true'
run: |
%VC%
git clone %GIT%/openssl/openssl.git openssl_%OPENSSL_VER%
cd openssl_%OPENSSL_VER%
git checkout OpenSSL_%OPENSSL_VER%-stable
@@ -180,8 +189,6 @@ jobs:
- name: Zlib.
run: |
%VC%
git clone %GIT%/telegramdesktop/zlib.git
cd zlib
git checkout tdesktop
@@ -191,8 +198,6 @@ jobs:
- name: MozJPEG.
shell: cmd
run: |
%VC%
git clone -b v4.0.1-rc2 %GIT%/mozilla/mozjpeg.git
cd mozjpeg
cmake . ^
@@ -211,8 +216,6 @@ jobs:
- name: OpenAL Soft.
if: steps.cache-openal.outputs.cache-hit != 'true'
run: |
%VC%
git clone -b openal-soft-1.21.0 --depth=1 %GIT%/kcat/openal-soft.git
cd openal-soft\build
cmake .. ^
@@ -236,8 +239,6 @@ jobs:
GYP_MSVS_VERSION: 2019
if: steps.cache-breakpad.outputs.cache-hit != 'true'
run: |
cd %LibrariesPath%
git clone %GIT%/telegramdesktop/gyp.git
cd gyp
SET PATH=%PY2%;%cd%;%PATH%
@@ -271,8 +272,6 @@ jobs:
- name: Opus.
if: steps.cache-opus.outputs.cache-hit != 'true'
run: |
%VC%
git clone %GIT%/telegramdesktop/opus.git
cd opus
git checkout tdesktop
@@ -281,10 +280,7 @@ jobs:
msbuild -m opus.sln /property:Configuration=Release /property:Platform="Win32"
- name: Rnnoise.
shell: cmd
run: |
%VC%
git clone %GIT%/desktop-app/rnnoise.git
mkdir rnnoise\out
cd rnnoise\out
@@ -300,7 +296,6 @@ jobs:
- name: FFmpeg.
if: steps.cache-ffmpeg.outputs.cache-hit != 'true'
run: |
%VC%
choco install --no-progress -y msys2
git clone %GIT%/FFmpeg/FFmpeg.git ffmpeg
@@ -321,8 +316,6 @@ jobs:
- name: Angle.
if: steps.cache-angle.outputs.cache-hit != 'true'
run: |
%VC%
git clone --recursive %GIT%/desktop-app/tg_angle.git
mkdir tg_angle\out\Debug
cd tg_angle\out\Debug
@@ -348,14 +341,13 @@ jobs:
- name: Configure Qt 5.15.2.
if: steps.cache-qt.outputs.cache-hit != 'true'
run: |
%VC%
git clone git://code.qt.io/qt/qt5.git qt_%QT%
cd qt_%QT%
perl init-repository --module-subset=qtbase,qtimageformats
perl init-repository --module-subset=qtbase,qtimageformats,qtsvg
git checkout v%QT_VER%
git submodule update qtbase
git submodule update qtimageformats
git submodule update qtsvg
cd qtbase
for /r %%i in (..\..\patches\qtbase_%QT%\*) do git apply %%i
cd ..
@@ -401,7 +393,6 @@ jobs:
- name: Qt 5.15.2 build.
if: steps.cache-qt.outputs.cache-hit != 'true'
run: |
%VC%
cd qt_%QT%
jom -j%NUMBER_OF_PROCESSORS%
@@ -419,8 +410,6 @@ jobs:
- name: WebRTC.
if: steps.cache-webrtc.outputs.cache-hit != 'true'
run: |
%VC%
git clone --recursive %GIT%/desktop-app/tg_owt.git
mkdir tg_owt\out\Debug
cd tg_owt\out\Debug
@@ -457,10 +446,12 @@ jobs:
echo "TDESKTOP_BUILD_DEFINE=$DEFINE" >> $GITHUB_ENV
- name: Free up some disk space.
working-directory: ${{ github.workspace }}
run: del /S *.pdb
- name: Telegram Desktop build.
if: env.ONLY_CACHE == 'false'
working-directory: ${{ github.workspace }}
run: |
cd %REPO_NAME%\Telegram
@@ -478,6 +469,7 @@ jobs:
- name: Move artifact.
if: env.UPLOAD_ARTIFACT == 'true'
working-directory: ${{ github.workspace }}
run: |
cd %REPO_NAME%\out\Debug
mkdir artifact

View File

@@ -91,12 +91,16 @@ PRIVATE
api/api_attached_stickers.h
api/api_authorizations.cpp
api/api_authorizations.h
api/api_blocked_peers.cpp
api/api_blocked_peers.h
api/api_bot.cpp
api/api_bot.h
api/api_chat_filters.cpp
api/api_chat_filters.h
api/api_chat_invite.cpp
api/api_chat_invite.h
api/api_cloud_password.cpp
api/api_cloud_password.h
api/api_common.h
api/api_editing.cpp
api/api_editing.h
@@ -124,6 +128,8 @@ PRIVATE
api/api_toggling_media.h
api/api_updates.cpp
api/api_updates.h
api/api_user_privacy.cpp
api/api_user_privacy.h
boxes/filters/edit_filter_box.cpp
boxes/filters/edit_filter_box.h
boxes/filters/edit_filter_chats_list.cpp
@@ -1292,8 +1298,6 @@ else()
if (NOT DESKTOP_APP_DISABLE_X11_INTEGRATION)
target_link_libraries(Telegram PRIVATE X11)
endif()
target_link_libraries(Telegram PRIVATE rt)
endif()
endif()
@@ -1311,10 +1315,6 @@ if (build_macstore)
COMMAND mkdir -p $<TARGET_FILE_DIR:Telegram>/../Frameworks
COMMAND cp -a ${libs_loc}/breakpad/src/client/mac/build/Release/Breakpad.framework $<TARGET_FILE_DIR:Telegram>/../Frameworks/Breakpad.framework
)
elseif (build_osx)
set(bundle_identifier "com.tdesktop.Telegram$<$<CONFIG:Debug>:DebugOsx>")
set(bundle_entitlements "Telegram.entitlements")
set(output_name "Telegram")
else()
set(bundle_identifier "com.tdesktop.Telegram$<$<CONFIG:Debug>:Debug>")
set(bundle_entitlements "Telegram.entitlements")
@@ -1432,10 +1432,6 @@ if ((NOT DESKTOP_APP_DISABLE_AUTOUPDATE OR APPLE) AND NOT build_macstore AND NOT
endif()
endif()
if (LINUX)
target_link_options(Updater PRIVATE -static-libstdc++)
endif()
if (DESKTOP_APP_SPECIAL_TARGET)
add_executable(Packer)
init_target(Packer)

View File

@@ -577,6 +577,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_passcode_autolock_minutes#other" = "{count} minutes";
"lng_passcode_autolock_hours#one" = "{count} hour";
"lng_passcode_autolock_hours#other" = "{count} hours";
"lng_passcode_autolock_hours_minutes" = "{hours_count}h {minutes_count}m";
"lng_passcode_enter_old" = "Enter current passcode";
"lng_passcode_enter_first" = "Enter a passcode";
"lng_passcode_enter_new" = "Enter new passcode";
@@ -1640,6 +1641,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_context_mark_read_sure" = "Are you sure you want to mark all chats from this folder as read?";
"lng_context_mark_read_all" = "Mark all chats as read";
"lng_context_mark_read_all_sure" = "Are you sure you want to mark all chats as read?";
"lng_context_mark_read_mentions_all" = "Mark all mentions as read";
"lng_context_archive_expand" = "Expand";
"lng_context_archive_collapse" = "Collapse";
"lng_context_archive_to_menu" = "Move to main menu";

View File

@@ -9,7 +9,7 @@
<Identity Name="TelegramMessengerLLP.TelegramDesktop"
ProcessorArchitecture="ARCHITECTURE"
Publisher="CN=536BC709-8EE1-4478-AF22-F0F0F26FF64A"
Version="2.9.0.0" />
Version="2.9.8.0" />
<Properties>
<DisplayName>Telegram Desktop</DisplayName>
<PublisherDisplayName>Telegram Messenger LLP</PublisherDisplayName>

View File

@@ -44,8 +44,8 @@ IDI_ICON1 ICON "..\\art\\icon256.ico"
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 2,9,0,0
PRODUCTVERSION 2,9,0,0
FILEVERSION 2,9,8,0
PRODUCTVERSION 2,9,8,0
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
@@ -62,10 +62,10 @@ BEGIN
BEGIN
VALUE "CompanyName", "Telegram FZ-LLC"
VALUE "FileDescription", "Telegram Desktop"
VALUE "FileVersion", "2.9.0.0"
VALUE "FileVersion", "2.9.8.0"
VALUE "LegalCopyright", "Copyright (C) 2014-2021"
VALUE "ProductName", "Telegram Desktop"
VALUE "ProductVersion", "2.9.0.0"
VALUE "ProductVersion", "2.9.8.0"
END
END
BLOCK "VarFileInfo"

View File

@@ -35,8 +35,8 @@ LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 2,9,0,0
PRODUCTVERSION 2,9,0,0
FILEVERSION 2,9,8,0
PRODUCTVERSION 2,9,8,0
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
@@ -53,10 +53,10 @@ BEGIN
BEGIN
VALUE "CompanyName", "Telegram FZ-LLC"
VALUE "FileDescription", "Telegram Desktop Updater"
VALUE "FileVersion", "2.9.0.0"
VALUE "FileVersion", "2.9.8.0"
VALUE "LegalCopyright", "Copyright (C) 2014-2021"
VALUE "ProductName", "Telegram Desktop"
VALUE "ProductVersion", "2.9.0.0"
VALUE "ProductVersion", "2.9.8.0"
END
END
BLOCK "VarFileInfo"

View File

@@ -496,11 +496,7 @@ int main(int argc, char *argv[])
#elif defined Q_OS_MAC
QString outName(QString("tmacupd%1").arg(AlphaVersion ? AlphaVersion : version));
#elif defined Q_OS_UNIX
#ifndef _LP64
QString outName(QString("tlinux32upd%1").arg(AlphaVersion ? AlphaVersion : version));
#else
QString outName(QString("tlinuxupd%1").arg(AlphaVersion ? AlphaVersion : version));
#endif
#else
#error Unknown platform!
#endif

View File

@@ -384,8 +384,6 @@ int main(int argc, char *argv[]) {
bool writeprotected = false;
bool tosettings = false;
bool startintray = false;
bool testmode = false;
bool externalupdater = false;
bool customWorkingDir = false;
char *key = 0;
@@ -399,10 +397,6 @@ int main(int argc, char *argv[]) {
debug = _debug = true;
} else if (equal(argv[i], "-startintray")) {
startintray = true;
} else if (equal(argv[i], "-testmode")) {
testmode = true;
} else if (equal(argv[i], "-externalupdater")) {
externalupdater = true;
} else if (equal(argv[i], "-tosettings")) {
tosettings = true;
} else if (equal(argv[i], "-workdir_custom")) {
@@ -503,8 +497,6 @@ int main(int argc, char *argv[]) {
if (autostart) push("-autostart");
if (debug) push("-debug");
if (startintray) push("-startintray");
if (testmode) push("-testmode");
if (externalupdater) push("-externalupdater");
if (tosettings) push("-tosettings");
if (key) {
push("-key");

View File

@@ -90,7 +90,7 @@ int main(int argc, const char * argv[]) {
openLog();
pid_t procId = 0;
BOOL update = YES, toSettings = NO, autoStart = NO, startInTray = NO, testMode = NO, freeType = NO, externalUpdater = NO;
BOOL update = YES, toSettings = NO, autoStart = NO, startInTray = NO, freeType = NO;
BOOL customWorkingDir = NO;
NSString *key = nil;
for (int i = 0; i < argc; ++i) {
@@ -114,12 +114,8 @@ int main(int argc, const char * argv[]) {
_debug = YES;
} else if ([@"-startintray" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) {
startInTray = YES;
} else if ([@"-testmode" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) {
testMode = YES;
} else if ([@"-freetype" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) {
freeType = YES;
} else if ([@"-externalupdater" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) {
externalUpdater = YES;
} else if ([@"-workdir_custom" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) {
customWorkingDir = YES;
} else if ([@"-key" isEqualToString:[NSString stringWithUTF8String:argv[i]]]) {
@@ -256,9 +252,7 @@ int main(int argc, const char * argv[]) {
if (toSettings) [args addObject:@"-tosettings"];
if (_debug) [args addObject:@"-debug"];
if (startInTray) [args addObject:@"-startintray"];
if (testMode) [args addObject:@"-testmode"];
if (freeType) [args addObject:@"-freetype"];
if (externalUpdater) [args addObject:@"-externalupdater"];
if (autoStart) [args addObject:@"-autostart"];
if (key) {
[args addObject:@"-key"];

View File

@@ -343,7 +343,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdPara
LPWSTR *args;
int argsCount;
bool needupdate = false, autostart = false, debug = false, writeprotected = false, startintray = false, testmode = false, freetype = false, externalupdater = false;
bool needupdate = false, autostart = false, debug = false, writeprotected = false, startintray = false, freetype = false;
args = CommandLineToArgvW(GetCommandLine(), &argsCount);
if (args) {
for (int i = 1; i < argsCount; ++i) {
@@ -357,12 +357,8 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdPara
openLog();
} else if (equal(args[i], L"-startintray")) {
startintray = true;
} else if (equal(args[i], L"-testmode")) {
testmode = true;
} else if (equal(args[i], L"-freetype")) {
freetype = true;
} else if (equal(args[i], L"-externalupdater")) {
externalupdater = true;
} else if (equal(args[i], L"-writeprotected") && ++i < argsCount) {
writeLog(std::wstring(L"Argument: ") + args[i]);
writeprotected = true;
@@ -432,9 +428,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdPara
if (autostart) targs += L" -autostart";
if (debug) targs += L" -debug";
if (startintray) targs += L" -startintray";
if (testmode) targs += L" -testmode";
if (freetype) targs += L" -freetype";
if (externalupdater) targs += L" -externalupdater";
if (!customWorkingDir.empty()) {
targs += L" -workdir \"" + customWorkingDir + L"\"";
}

View File

@@ -0,0 +1,173 @@
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "api/api_blocked_peers.h"
#include "apiwrap.h"
#include "base/unixtime.h"
#include "data/data_changes.h"
#include "data/data_peer.h"
#include "data/data_peer_id.h"
#include "data/data_session.h"
#include "main/main_session.h"
namespace Api {
namespace {
constexpr auto kBlockedFirstSlice = 16;
constexpr auto kBlockedPerPage = 40;
BlockedPeers::Slice TLToSlice(
const MTPcontacts_Blocked &blocked,
Data::Session &owner) {
const auto create = [&](int count, const QVector<MTPPeerBlocked> &list) {
auto slice = BlockedPeers::Slice();
slice.total = std::max(count, list.size());
slice.list.reserve(list.size());
for (const auto &contact : list) {
contact.match([&](const MTPDpeerBlocked &data) {
slice.list.push_back({
.id = peerFromMTP(data.vpeer_id()),
.date = data.vdate().v,
});
});
}
return slice;
};
return blocked.match([&](const MTPDcontacts_blockedSlice &data) {
owner.processUsers(data.vusers());
owner.processChats(data.vchats());
return create(data.vcount().v, data.vblocked().v);
}, [&](const MTPDcontacts_blocked &data) {
owner.processUsers(data.vusers());
owner.processChats(data.vchats());
return create(0, data.vblocked().v);
});
}
} // namespace
BlockedPeers::BlockedPeers(not_null<ApiWrap*> api)
: _session(&api->session())
, _api(&api->instance()) {
}
bool BlockedPeers::Slice::Item::operator==(const Item &other) const {
return (id == other.id) && (date == other.date);
}
bool BlockedPeers::Slice::Item::operator!=(const Item &other) const {
return !(*this == other);
}
bool BlockedPeers::Slice::operator==(const BlockedPeers::Slice &other) const {
return (total == other.total) && (list == other.list);
}
bool BlockedPeers::Slice::operator!=(const BlockedPeers::Slice &other) const {
return !(*this == other);
}
void BlockedPeers::block(not_null<PeerData*> peer) {
if (peer->isBlocked()) {
_session->changes().peerUpdated(
peer,
Data::PeerUpdate::Flag::IsBlocked);
} else if (_blockRequests.find(peer) == end(_blockRequests)) {
const auto requestId = _api.request(MTPcontacts_Block(
peer->input
)).done([=](const MTPBool &result) {
_blockRequests.erase(peer);
peer->setIsBlocked(true);
if (_slice) {
_slice->list.insert(
_slice->list.begin(),
{ peer->id, base::unixtime::now() });
++_slice->total;
_changes.fire_copy(*_slice);
}
}).fail([=](const MTP::Error &error) {
_blockRequests.erase(peer);
}).send();
_blockRequests.emplace(peer, requestId);
}
}
void BlockedPeers::unblock(not_null<PeerData*> peer, Fn<void()> onDone) {
if (!peer->isBlocked()) {
_session->changes().peerUpdated(
peer,
Data::PeerUpdate::Flag::IsBlocked);
return;
} else if (_blockRequests.find(peer) != end(_blockRequests)) {
return;
}
const auto requestId = _api.request(MTPcontacts_Unblock(
peer->input
)).done([=](const MTPBool &result) {
_blockRequests.erase(peer);
peer->setIsBlocked(false);
if (_slice) {
auto &list = _slice->list;
for (auto i = list.begin(); i != list.end(); ++i) {
if (i->id == peer->id) {
list.erase(i);
break;
}
}
if (_slice->total > list.size()) {
--_slice->total;
}
_changes.fire_copy(*_slice);
}
if (onDone) {
onDone();
}
}).fail([=](const MTP::Error &error) {
_blockRequests.erase(peer);
}).send();
_blockRequests.emplace(peer, requestId);
}
void BlockedPeers::reload() {
if (_requestId) {
return;
}
request(0, [=](Slice &&slice) {
if (!_slice || *_slice != slice) {
_slice = slice;
_changes.fire(std::move(slice));
}
});
}
auto BlockedPeers::slice() -> rpl::producer<BlockedPeers::Slice> {
if (!_slice) {
reload();
}
return _slice
? _changes.events_starting_with_copy(*_slice)
: (_changes.events() | rpl::type_erased());
}
void BlockedPeers::request(int offset, Fn<void(BlockedPeers::Slice)> onDone) {
if (_requestId) {
return;
}
_requestId = _api.request(MTPcontacts_GetBlocked(
MTP_int(offset),
MTP_int(offset ? kBlockedPerPage : kBlockedFirstSlice)
)).done([=](const MTPcontacts_Blocked &result) {
_requestId = 0;
onDone(TLToSlice(result, _session->data()));
}).fail([=](const MTP::Error &error) {
_requestId = 0;
}).send();
}
} // namespace Api

View File

@@ -0,0 +1,60 @@
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once
#include "mtproto/sender.h"
class ApiWrap;
namespace Main {
class Session;
} // namespace Main
namespace Api {
class BlockedPeers final {
public:
struct Slice {
struct Item {
PeerId id;
TimeId date = 0;
bool operator==(const Item &other) const;
bool operator!=(const Item &other) const;
};
QVector<Item> list;
int total = 0;
bool operator==(const Slice &other) const;
bool operator!=(const Slice &other) const;
};
explicit BlockedPeers(not_null<ApiWrap*> api);
void reload();
rpl::producer<Slice> slice();
void request(int offset, Fn<void(Slice)> onDone);
void block(not_null<PeerData*> peer);
void unblock(not_null<PeerData*> peer, Fn<void()> onDone = nullptr);
private:
const not_null<Main::Session*> _session;
MTP::Sender _api;
base::flat_map<not_null<PeerData*>, mtpRequestId> _blockRequests;
mtpRequestId _requestId = 0;
std::optional<Slice> _slice;
rpl::event_stream<Slice> _changes;
};
} // namespace Api

View File

@@ -8,6 +8,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "api/api_bot.h"
#include "apiwrap.h"
#include "api/api_cloud_password.h"
#include "core/core_cloud_password.h"
#include "api/api_send_progress.h"
#include "boxes/confirm_box.h"
@@ -168,7 +169,7 @@ void SendBotCallbackDataWithPassword(
if (!button || button->requestId) {
return;
}
api->reloadPasswordState();
api->cloudPassword().reload();
SendBotCallbackData(item, row, column, MTP_inputCheckPasswordEmpty(), [=](const MTP::Error &error) {
auto box = PrePasswordErrorBox(
error,
@@ -181,7 +182,7 @@ void SendBotCallbackDataWithPassword(
} else {
auto lifetime = std::make_shared<rpl::lifetime>();
button->requestId = -1;
api->passwordState(
api->cloudPassword().state(
) | rpl::take(
1
) | rpl::start_with_next([=](const Core::CloudPasswordState &state) mutable {

View File

@@ -112,6 +112,11 @@ ConfirmInviteBox::ConfirmInviteBox(
? tr::lng_channel_invite_private(tr::now)
: (!_participants.empty() && _participants.size() < count)
? tr::lng_group_invite_members(tr::now, lt_count, count)
: (count > 0 && _isChannel)
? tr::lng_chat_status_subscribers(
tr::now,
lt_count_decimal,
count)
: (count > 0)
? tr::lng_chat_status_members(tr::now, lt_count_decimal, count)
: _isChannel

View File

@@ -0,0 +1,112 @@
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "api/api_cloud_password.h"
#include "base/openssl_help.h"
#include "core/core_cloud_password.h"
#include "apiwrap.h"
namespace Api {
// #TODO Add ability to set recovery email separately.
CloudPassword::CloudPassword(not_null<ApiWrap*> api)
: _api(&api->instance()) {
}
void CloudPassword::reload() {
if (_requestId) {
return;
}
_requestId = _api.request(MTPaccount_GetPassword(
)).done([=](const MTPaccount_Password &result) {
_requestId = 0;
result.match([&](const MTPDaccount_password &data) {
openssl::AddRandomSeed(bytes::make_span(data.vsecure_random().v));
if (_state) {
*_state = Core::ParseCloudPasswordState(data);
} else {
_state = std::make_unique<Core::CloudPasswordState>(
Core::ParseCloudPasswordState(data));
}
_stateChanges.fire_copy(*_state);
});
}).fail([=](const MTP::Error &error) {
_requestId = 0;
}).send();
}
void CloudPassword::clearUnconfirmedPassword() {
_requestId = _api.request(MTPaccount_CancelPasswordEmail(
)).done([=](const MTPBool &result) {
_requestId = 0;
reload();
}).fail([=](const MTP::Error &error) {
_requestId = 0;
reload();
}).send();
}
rpl::producer<Core::CloudPasswordState> CloudPassword::state() const {
return _state
? _stateChanges.events_starting_with_copy(*_state)
: (_stateChanges.events() | rpl::type_erased());
}
auto CloudPassword::stateCurrent() const
-> std::optional<Core::CloudPasswordState> {
return _state
? base::make_optional(*_state)
: std::nullopt;
}
auto CloudPassword::resetPassword()
-> rpl::producer<CloudPassword::ResetRetryDate, QString> {
return [=](auto consumer) {
_api.request(MTPaccount_ResetPassword(
)).done([=](const MTPaccount_ResetPasswordResult &result) {
result.match([&](const MTPDaccount_resetPasswordOk &data) {
reload();
}, [&](const MTPDaccount_resetPasswordRequestedWait &data) {
if (!_state) {
reload();
return;
}
const auto until = data.vuntil_date().v;
if (_state->pendingResetDate != until) {
_state->pendingResetDate = until;
_stateChanges.fire_copy(*_state);
}
}, [&](const MTPDaccount_resetPasswordFailedWait &data) {
consumer.put_next_copy(data.vretry_date().v);
});
consumer.put_done();
}).fail([=](const MTP::Error &error) {
consumer.put_error_copy(error.type());
}).send();
return rpl::lifetime();
};
}
auto CloudPassword::cancelResetPassword()
-> rpl::producer<rpl::no_value, QString> {
return [=](auto consumer) {
_api.request(MTPaccount_DeclinePasswordReset(
)).done([=] {
reload();
consumer.put_done();
}).fail([=](const MTP::Error &error) {
consumer.put_error_copy(error.type());
}).send();
return rpl::lifetime();
};
}
} // namespace Api

View File

@@ -0,0 +1,45 @@
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once
#include "mtproto/sender.h"
namespace Core {
struct CloudPasswordState;
} // namespace Core
class ApiWrap;
namespace Main {
class Session;
} // namespace Main
namespace Api {
class CloudPassword final {
public:
using ResetRetryDate = int;
explicit CloudPassword(not_null<ApiWrap*> api);
void reload();
void clearUnconfirmedPassword();
rpl::producer<Core::CloudPasswordState> state() const;
std::optional<Core::CloudPasswordState> stateCurrent() const;
rpl::producer<ResetRetryDate, QString> resetPassword();
rpl::producer<rpl::no_value, QString> cancelResetPassword();
private:
MTP::Sender _api;
mtpRequestId _requestId = 0;
std::unique_ptr<Core::CloudPasswordState> _state;
rpl::event_stream<Core::CloudPasswordState> _stateChanges;
};
} // namespace Api

View File

@@ -32,7 +32,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/file_upload.h"
#include "mainwidget.h"
#include "apiwrap.h"
#include "app.h"
namespace Api {
namespace {

View File

@@ -9,6 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "api/api_authorizations.h"
#include "api/api_text_entities.h"
#include "api/api_user_privacy.h"
#include "main/main_session.h"
#include "main/main_account.h"
#include "mtproto/mtp_instance.h"
@@ -1954,13 +1955,10 @@ void Updates::feedUpdate(const MTPUpdate &update) {
}
return true;
};
if (const auto key = ApiWrap::Privacy::KeyFromMTP(d.vkey().type())) {
if (allLoaded()) {
session().api().handlePrivacyChange(*key, d.vrules());
} else {
session().api().reloadPrivacy(*key);
}
}
session().api().userPrivacy().apply(
d.vkey().type(),
d.vrules(),
allLoaded());
} break;
case mtpc_updatePinnedDialogs: {

View File

@@ -0,0 +1,303 @@
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "api/api_user_privacy.h"
#include "apiwrap.h"
#include "data/data_chat.h"
#include "data/data_channel.h"
#include "data/data_peer.h"
#include "data/data_peer_id.h"
#include "data/data_session.h"
#include "data/data_user.h"
#include "main/main_session.h"
namespace Api {
namespace {
constexpr auto kMaxRules = 3; // Allow users, disallow users, Option.
using TLInputRules = MTPVector<MTPInputPrivacyRule>;
using TLRules = MTPVector<MTPPrivacyRule>;
TLInputRules RulesToTL(const UserPrivacy::Rule &rule) {
const auto collectInputUsers = [](const auto &peers) {
auto result = QVector<MTPInputUser>();
result.reserve(peers.size());
for (const auto peer : peers) {
if (const auto user = peer->asUser()) {
result.push_back(user->inputUser);
}
}
return result;
};
const auto collectInputChats = [](const auto &peers) {
auto result = QVector<MTPint>(); // #TODO ids
result.reserve(peers.size());
for (const auto peer : peers) {
if (!peer->isUser()) {
result.push_back(peerToBareMTPInt(peer->id));
}
}
return result;
};
auto result = QVector<MTPInputPrivacyRule>();
result.reserve(kMaxRules);
if (!rule.ignoreAlways) {
const auto users = collectInputUsers(rule.always);
const auto chats = collectInputChats(rule.always);
if (!users.empty()) {
result.push_back(
MTP_inputPrivacyValueAllowUsers(
MTP_vector<MTPInputUser>(users)));
}
if (!chats.empty()) {
result.push_back(
MTP_inputPrivacyValueAllowChatParticipants(
MTP_vector<MTPint>(chats)));
}
}
if (!rule.ignoreNever) {
const auto users = collectInputUsers(rule.never);
const auto chats = collectInputChats(rule.never);
if (!users.empty()) {
result.push_back(
MTP_inputPrivacyValueDisallowUsers(
MTP_vector<MTPInputUser>(users)));
}
if (!chats.empty()) {
result.push_back(
MTP_inputPrivacyValueDisallowChatParticipants(
MTP_vector<MTPint>(chats)));
}
}
result.push_back([&] {
using Option = UserPrivacy::Option;
switch (rule.option) {
case Option::Everyone: return MTP_inputPrivacyValueAllowAll();
case Option::Contacts: return MTP_inputPrivacyValueAllowContacts();
case Option::Nobody: return MTP_inputPrivacyValueDisallowAll();
}
Unexpected("Option value in Api::UserPrivacy::RulesToTL.");
}());
return MTP_vector<MTPInputPrivacyRule>(std::move(result));
}
UserPrivacy::Rule TLToRules(const TLRules &rules, Data::Session &owner) {
// This is simplified version of privacy rules interpretation.
// But it should be fine for all the apps
// that use the same subset of features.
using Option = UserPrivacy::Option;
auto result = UserPrivacy::Rule();
auto optionSet = false;
const auto setOption = [&](Option option) {
if (optionSet) return;
optionSet = true;
result.option = option;
};
auto &always = result.always;
auto &never = result.never;
const auto feed = [&](const MTPPrivacyRule &rule) {
rule.match([&](const MTPDprivacyValueAllowAll &) {
setOption(Option::Everyone);
}, [&](const MTPDprivacyValueAllowContacts &) {
setOption(Option::Contacts);
}, [&](const MTPDprivacyValueAllowUsers &data) {
const auto &users = data.vusers().v;
always.reserve(always.size() + users.size());
for (const auto userId : users) {
const auto user = owner.user(UserId(userId.v));
if (!base::contains(never, user)
&& !base::contains(always, user)) {
always.emplace_back(user);
}
}
}, [&](const MTPDprivacyValueAllowChatParticipants &data) {
const auto &chats = data.vchats().v;
always.reserve(always.size() + chats.size());
for (const auto &chatId : chats) {
const auto chat = owner.chatLoaded(chatId);
const auto peer = chat
? static_cast<PeerData*>(chat)
: owner.channelLoaded(chatId);
if (peer
&& !base::contains(never, peer)
&& !base::contains(always, peer)) {
always.emplace_back(peer);
}
}
}, [&](const MTPDprivacyValueDisallowContacts &) {
// Not supported
}, [&](const MTPDprivacyValueDisallowAll &) {
setOption(Option::Nobody);
}, [&](const MTPDprivacyValueDisallowUsers &data) {
const auto &users = data.vusers().v;
never.reserve(never.size() + users.size());
for (const auto userId : users) {
const auto user = owner.user(UserId(userId.v));
if (!base::contains(always, user)
&& !base::contains(never, user)) {
never.emplace_back(user);
}
}
}, [&](const MTPDprivacyValueDisallowChatParticipants &data) {
const auto &chats = data.vchats().v;
never.reserve(never.size() + chats.size());
for (const auto &chatId : chats) {
const auto chat = owner.chatLoaded(chatId);
const auto peer = chat
? static_cast<PeerData*>(chat)
: owner.channelLoaded(chatId);
if (peer
&& !base::contains(always, peer)
&& !base::contains(never, peer)) {
never.emplace_back(peer);
}
}
});
};
for (const auto &rule : rules.v) {
feed(rule);
}
feed(MTP_privacyValueDisallowAll()); // Disallow by default.
return result;
}
MTPInputPrivacyKey KeyToTL(UserPrivacy::Key key) {
using Key = UserPrivacy::Key;
switch (key) {
case Key::Calls: return MTP_inputPrivacyKeyPhoneCall();
case Key::Invites: return MTP_inputPrivacyKeyChatInvite();
case Key::PhoneNumber: return MTP_inputPrivacyKeyPhoneNumber();
case Key::AddedByPhone:
return MTP_inputPrivacyKeyAddedByPhone();
case Key::LastSeen:
return MTP_inputPrivacyKeyStatusTimestamp();
case Key::CallsPeer2Peer:
return MTP_inputPrivacyKeyPhoneP2P();
case Key::Forwards:
return MTP_inputPrivacyKeyForwards();
case Key::ProfilePhoto:
return MTP_inputPrivacyKeyProfilePhoto();
}
Unexpected("Key in Api::UserPrivacy::KetToTL.");
}
std::optional<UserPrivacy::Key> TLToKey(mtpTypeId type) {
using Key = UserPrivacy::Key;
switch (type) {
case mtpc_privacyKeyPhoneNumber:
case mtpc_inputPrivacyKeyPhoneNumber: return Key::PhoneNumber;
case mtpc_privacyKeyAddedByPhone:
case mtpc_inputPrivacyKeyAddedByPhone: return Key::AddedByPhone;
case mtpc_privacyKeyStatusTimestamp:
case mtpc_inputPrivacyKeyStatusTimestamp: return Key::LastSeen;
case mtpc_privacyKeyChatInvite:
case mtpc_inputPrivacyKeyChatInvite: return Key::Invites;
case mtpc_privacyKeyPhoneCall:
case mtpc_inputPrivacyKeyPhoneCall: return Key::Calls;
case mtpc_privacyKeyPhoneP2P:
case mtpc_inputPrivacyKeyPhoneP2P: return Key::CallsPeer2Peer;
case mtpc_privacyKeyForwards:
case mtpc_inputPrivacyKeyForwards: return Key::Forwards;
case mtpc_privacyKeyProfilePhoto:
case mtpc_inputPrivacyKeyProfilePhoto: return Key::ProfilePhoto;
}
return std::nullopt;
}
} // namespace
UserPrivacy::UserPrivacy(not_null<ApiWrap*> api)
: _session(&api->session())
, _api(&api->instance()) {
}
void UserPrivacy::save(
Key key,
const UserPrivacy::Rule &rule) {
const auto tlKey = KeyToTL(key);
const auto keyTypeId = tlKey.type();
const auto it = _privacySaveRequests.find(keyTypeId);
if (it != _privacySaveRequests.cend()) {
_api.request(it->second).cancel();
_privacySaveRequests.erase(it);
}
const auto requestId = _api.request(MTPaccount_SetPrivacy(
tlKey,
RulesToTL(rule)
)).done([=](const MTPaccount_PrivacyRules &result) {
result.match([&](const MTPDaccount_privacyRules &data) {
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
_privacySaveRequests.remove(keyTypeId);
apply(keyTypeId, data.vrules(), true);
});
}).fail([=](const MTP::Error &error) {
_privacySaveRequests.remove(keyTypeId);
}).send();
_privacySaveRequests.emplace(keyTypeId, requestId);
}
void UserPrivacy::apply(
mtpTypeId type,
const TLRules &rules,
bool allLoaded) {
if (const auto key = TLToKey(type)) {
if (!allLoaded) {
reload(*key);
return;
}
pushPrivacy(*key, rules);
if ((*key) == Key::LastSeen) {
_session->api().updatePrivacyLastSeens();
}
}
}
void UserPrivacy::reload(Key key) {
if (_privacyRequestIds.contains(key)) {
return;
}
const auto requestId = _api.request(MTPaccount_GetPrivacy(
KeyToTL(key)
)).done([=](const MTPaccount_PrivacyRules &result) {
_privacyRequestIds.erase(key);
result.match([&](const MTPDaccount_privacyRules &data) {
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
pushPrivacy(key, data.vrules());
});
}).fail([=](const MTP::Error &error) {
_privacyRequestIds.erase(key);
}).send();
_privacyRequestIds.emplace(key, requestId);
}
void UserPrivacy::pushPrivacy(Key key, const TLRules &rules) {
const auto &saved = (_privacyValues[key] =
TLToRules(rules, _session->data()));
const auto i = _privacyChanges.find(key);
if (i != end(_privacyChanges)) {
i->second.fire_copy(saved);
}
}
auto UserPrivacy::value(Key key) -> rpl::producer<UserPrivacy::Rule> {
if (const auto i = _privacyValues.find(key); i != end(_privacyValues)) {
return _privacyChanges[key].events_starting_with_copy(i->second);
} else {
return _privacyChanges[key].events();
}
}
} // namespace Api

View File

@@ -0,0 +1,73 @@
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once
#include "mtproto/sender.h"
class ApiWrap;
namespace Main {
class Session;
} // namespace Main
namespace Api {
class UserPrivacy final {
public:
enum class Key {
PhoneNumber,
AddedByPhone,
LastSeen,
Calls,
Invites,
CallsPeer2Peer,
Forwards,
ProfilePhoto,
};
enum class Option {
Everyone,
Contacts,
Nobody,
};
struct Rule {
Option option = Option::Everyone;
std::vector<not_null<PeerData*>> always;
std::vector<not_null<PeerData*>> never;
bool ignoreAlways = false;
bool ignoreNever = false;
};
explicit UserPrivacy(not_null<ApiWrap*> api);
void save(
Key key,
const UserPrivacy::Rule &rule);
void apply(
mtpTypeId type,
const MTPVector<MTPPrivacyRule> &rules,
bool allLoaded);
void reload(Key key);
rpl::producer<Rule> value(Key key);
private:
const not_null<Main::Session*> _session;
void pushPrivacy(Key key, const MTPVector<MTPPrivacyRule> &rules);
base::flat_map<mtpTypeId, mtpRequestId> _privacySaveRequests;
base::flat_map<Key, mtpRequestId> _privacyRequestIds;
base::flat_map<Key, Rule> _privacyValues;
std::map<Key, rpl::event_stream<Rule>> _privacyChanges;
MTP::Sender _api;
};
} // namespace Api

View File

@@ -9,6 +9,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "api/api_authorizations.h"
#include "api/api_attached_stickers.h"
#include "api/api_blocked_peers.h"
#include "api/api_cloud_password.h"
#include "api/api_hash.h"
#include "api/api_invite_links.h"
#include "api/api_media.h"
@@ -18,6 +20,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "api/api_sensitive_content.h"
#include "api/api_global_privacy.h"
#include "api/api_updates.h"
#include "api/api_user_privacy.h"
#include "data/stickers/data_stickers.h"
#include "data/data_drafts.h"
#include "data/data_changes.h"
@@ -42,7 +45,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "dialogs/dialogs_key.h"
#include "core/core_cloud_password.h"
#include "core/application.h"
#include "base/openssl_help.h"
#include "base/unixtime.h"
#include "base/qt_adapters.h"
#include "base/call_delayed.h"
@@ -78,7 +80,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/storage_media_prepare.h"
#include "storage/storage_account.h"
#include "facades.h"
#include "app.h"
#include "app.h" // App::quitting
namespace {
@@ -108,7 +110,6 @@ constexpr auto kStickersByEmojiInvalidateTimeout = crl::time(60 * 60 * 1000);
constexpr auto kNotifySettingSaveTimeout = crl::time(1000);
constexpr auto kDialogsFirstLoad = 20;
constexpr auto kDialogsPerPage = 500;
constexpr auto kBlockedFirstSlice = 16;
using PhotoFileLocationId = Data::PhotoFileLocationId;
using DocumentFileLocationId = Data::DocumentFileLocationId;
@@ -120,65 +121,6 @@ using UpdatedFileReferences = Data::UpdatedFileReferences;
} // namespace
MTPInputPrivacyKey ApiWrap::Privacy::Input(Key key) {
switch (key) {
case Privacy::Key::Calls: return MTP_inputPrivacyKeyPhoneCall();
case Privacy::Key::Invites: return MTP_inputPrivacyKeyChatInvite();
case Privacy::Key::PhoneNumber: return MTP_inputPrivacyKeyPhoneNumber();
case Privacy::Key::AddedByPhone:
return MTP_inputPrivacyKeyAddedByPhone();
case Privacy::Key::LastSeen:
return MTP_inputPrivacyKeyStatusTimestamp();
case Privacy::Key::CallsPeer2Peer:
return MTP_inputPrivacyKeyPhoneP2P();
case Privacy::Key::Forwards:
return MTP_inputPrivacyKeyForwards();
case Privacy::Key::ProfilePhoto:
return MTP_inputPrivacyKeyProfilePhoto();
}
Unexpected("Key in ApiWrap::Privacy::Input.");
}
std::optional<ApiWrap::Privacy::Key> ApiWrap::Privacy::KeyFromMTP(
mtpTypeId type) {
using Key = Privacy::Key;
switch (type) {
case mtpc_privacyKeyPhoneNumber:
case mtpc_inputPrivacyKeyPhoneNumber: return Key::PhoneNumber;
case mtpc_privacyKeyAddedByPhone:
case mtpc_inputPrivacyKeyAddedByPhone: return Key::AddedByPhone;
case mtpc_privacyKeyStatusTimestamp:
case mtpc_inputPrivacyKeyStatusTimestamp: return Key::LastSeen;
case mtpc_privacyKeyChatInvite:
case mtpc_inputPrivacyKeyChatInvite: return Key::Invites;
case mtpc_privacyKeyPhoneCall:
case mtpc_inputPrivacyKeyPhoneCall: return Key::Calls;
case mtpc_privacyKeyPhoneP2P:
case mtpc_inputPrivacyKeyPhoneP2P: return Key::CallsPeer2Peer;
case mtpc_privacyKeyForwards:
case mtpc_inputPrivacyKeyForwards: return Key::Forwards;
case mtpc_privacyKeyProfilePhoto:
case mtpc_inputPrivacyKeyProfilePhoto: return Key::ProfilePhoto;
}
return std::nullopt;
}
bool ApiWrap::BlockedPeersSlice::Item::operator==(const Item &other) const {
return (peer == other.peer) && (date == other.date);
}
bool ApiWrap::BlockedPeersSlice::Item::operator!=(const Item &other) const {
return !(*this == other);
}
bool ApiWrap::BlockedPeersSlice::operator==(const BlockedPeersSlice &other) const {
return (total == other.total) && (list == other.list);
}
bool ApiWrap::BlockedPeersSlice::operator!=(const BlockedPeersSlice &other) const {
return !(*this == other);
}
ApiWrap::ApiWrap(not_null<Main::Session*> session)
: MTP::Sender(&session->account().mtp())
, _session(session)
@@ -192,9 +134,12 @@ ApiWrap::ApiWrap(not_null<Main::Session*> session)
, _updateNotifySettingsTimer([=] { sendNotifySettingsUpdates(); })
, _authorizations(std::make_unique<Api::Authorizations>(this))
, _attachedStickers(std::make_unique<Api::AttachedStickers>(this))
, _blockedPeers(std::make_unique<Api::BlockedPeers>(this))
, _cloudPassword(std::make_unique<Api::CloudPassword>(this))
, _selfDestruct(std::make_unique<Api::SelfDestruct>(this))
, _sensitiveContent(std::make_unique<Api::SensitiveContent>(this))
, _globalPrivacy(std::make_unique<Api::GlobalPrivacy>(this))
, _userPrivacy(std::make_unique<Api::UserPrivacy>(this))
, _inviteLinks(std::make_unique<Api::InviteLinks>(this)) {
crl::on_main(session, [=] {
// You can't use _session->lifetime() in the constructor,
@@ -2175,68 +2120,6 @@ void ApiWrap::leaveChannel(not_null<ChannelData*> channel) {
}
}
void ApiWrap::blockPeer(not_null<PeerData*> peer) {
if (peer->isBlocked()) {
session().changes().peerUpdated(
peer,
Data::PeerUpdate::Flag::IsBlocked);
} else if (_blockRequests.find(peer) == end(_blockRequests)) {
const auto requestId = request(MTPcontacts_Block(
peer->input
)).done([=](const MTPBool &result) {
_blockRequests.erase(peer);
peer->setIsBlocked(true);
if (_blockedPeersSlice) {
_blockedPeersSlice->list.insert(
_blockedPeersSlice->list.begin(),
{ peer, base::unixtime::now() });
++_blockedPeersSlice->total;
_blockedPeersChanges.fire_copy(*_blockedPeersSlice);
}
}).fail([=](const MTP::Error &error) {
_blockRequests.erase(peer);
}).send();
_blockRequests.emplace(peer, requestId);
}
}
void ApiWrap::unblockPeer(not_null<PeerData*> peer, Fn<void()> onDone) {
if (!peer->isBlocked()) {
session().changes().peerUpdated(
peer,
Data::PeerUpdate::Flag::IsBlocked);
return;
} else if (_blockRequests.find(peer) != end(_blockRequests)) {
return;
}
const auto requestId = request(MTPcontacts_Unblock(
peer->input
)).done([=](const MTPBool &result) {
_blockRequests.erase(peer);
peer->setIsBlocked(false);
if (_blockedPeersSlice) {
auto &list = _blockedPeersSlice->list;
for (auto i = list.begin(); i != list.end(); ++i) {
if (i->peer == peer) {
list.erase(i);
break;
}
}
if (_blockedPeersSlice->total > list.size()) {
--_blockedPeersSlice->total;
}
_blockedPeersChanges.fire_copy(*_blockedPeersSlice);
}
if (onDone) {
onDone();
}
}).fail([=](const MTP::Error &error) {
_blockRequests.erase(peer);
}).send();
_blockRequests.emplace(peer, requestId);
}
void ApiWrap::requestNotifySettings(const MTPInputNotifyPeer &peer) {
const auto key = [&] {
switch (peer.type()) {
@@ -2309,45 +2192,7 @@ void ApiWrap::saveDraftToCloudDelayed(not_null<History*> history) {
}
}
void ApiWrap::savePrivacy(
const MTPInputPrivacyKey &key,
QVector<MTPInputPrivacyRule> &&rules) {
const auto keyTypeId = key.type();
const auto it = _privacySaveRequests.find(keyTypeId);
if (it != _privacySaveRequests.cend()) {
request(it->second).cancel();
_privacySaveRequests.erase(it);
}
const auto requestId = request(MTPaccount_SetPrivacy(
key,
MTP_vector<MTPInputPrivacyRule>(std::move(rules))
)).done([=](const MTPaccount_PrivacyRules &result) {
result.match([&](const MTPDaccount_privacyRules &data) {
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
_privacySaveRequests.remove(keyTypeId);
if (const auto key = Privacy::KeyFromMTP(keyTypeId)) {
handlePrivacyChange(*key, data.vrules());
}
});
}).fail([=](const MTP::Error &error) {
_privacySaveRequests.remove(keyTypeId);
}).send();
_privacySaveRequests.emplace(keyTypeId, requestId);
}
void ApiWrap::handlePrivacyChange(
Privacy::Key key,
const MTPVector<MTPPrivacyRule> &rules) {
pushPrivacy(key, rules.v);
if (key == Privacy::Key::LastSeen) {
updatePrivacyLastSeens(rules.v);
}
}
void ApiWrap::updatePrivacyLastSeens(const QVector<MTPPrivacyRule> &rules) {
void ApiWrap::updatePrivacyLastSeens() {
const auto now = base::unixtime::now();
_session->data().enumerateUsers([&](UserData *user) {
if (user->isSelf() || !user->isFullLoaded()) {
@@ -4742,69 +4587,6 @@ void ApiWrap::clearPeerPhoto(not_null<PhotoData*> photo) {
}
}
void ApiWrap::reloadPasswordState() {
if (_passwordRequestId) {
return;
}
_passwordRequestId = request(MTPaccount_GetPassword(
)).done([=](const MTPaccount_Password &result) {
_passwordRequestId = 0;
result.match([&](const MTPDaccount_password &data) {
openssl::AddRandomSeed(bytes::make_span(data.vsecure_random().v));
if (_passwordState) {
*_passwordState = Core::ParseCloudPasswordState(data);
} else {
_passwordState = std::make_unique<Core::CloudPasswordState>(
Core::ParseCloudPasswordState(data));
}
_passwordStateChanges.fire_copy(*_passwordState);
});
}).fail([=](const MTP::Error &error) {
_passwordRequestId = 0;
}).send();
}
void ApiWrap::applyPendingReset(const MTPaccount_ResetPasswordResult &data) {
if (!_passwordState) {
reloadPasswordState();
return;
}
data.match([&](const MTPDaccount_resetPasswordOk &data) {
reloadPasswordState();
}, [&](const MTPDaccount_resetPasswordRequestedWait &data) {
const auto until = data.vuntil_date().v;
if (_passwordState->pendingResetDate != until) {
_passwordState->pendingResetDate = until;
_passwordStateChanges.fire_copy(*_passwordState);
}
}, [&](const MTPDaccount_resetPasswordFailedWait &data) {
});
}
void ApiWrap::clearUnconfirmedPassword() {
_passwordRequestId = request(MTPaccount_CancelPasswordEmail(
)).done([=](const MTPBool &result) {
_passwordRequestId = 0;
reloadPasswordState();
}).fail([=](const MTP::Error &error) {
_passwordRequestId = 0;
reloadPasswordState();
}).send();
}
rpl::producer<Core::CloudPasswordState> ApiWrap::passwordState() const {
return _passwordState
? _passwordStateChanges.events_starting_with_copy(*_passwordState)
: (_passwordStateChanges.events() | rpl::type_erased());
}
auto ApiWrap::passwordStateCurrent() const
-> std::optional<Core::CloudPasswordState> {
return _passwordState
? base::make_optional(*_passwordState)
: std::nullopt;
}
void ApiWrap::reloadContactSignupSilent() {
if (_contactSignupSilentRequestId) {
return;
@@ -4878,176 +4660,6 @@ void ApiWrap::saveSelfBio(const QString &text, FnMut<void()> done) {
}).send();
}
void ApiWrap::reloadPrivacy(Privacy::Key key) {
if (_privacyRequestIds.contains(key)) {
return;
}
const auto requestId = request(MTPaccount_GetPrivacy(
Privacy::Input(key)
)).done([=](const MTPaccount_PrivacyRules &result) {
_privacyRequestIds.erase(key);
result.match([&](const MTPDaccount_privacyRules &data) {
_session->data().processUsers(data.vusers());
_session->data().processChats(data.vchats());
pushPrivacy(key, data.vrules().v);
});
}).fail([=](const MTP::Error &error) {
_privacyRequestIds.erase(key);
}).send();
_privacyRequestIds.emplace(key, requestId);
}
auto ApiWrap::parsePrivacy(const QVector<MTPPrivacyRule> &rules)
-> Privacy {
using Option = Privacy::Option;
// This is simplified version of privacy rules interpretation.
// But it should be fine for all the apps
// that use the same subset of features.
auto result = Privacy();
auto optionSet = false;
const auto SetOption = [&](Option option) {
if (optionSet) return;
optionSet = true;
result.option = option;
};
auto &always = result.always;
auto &never = result.never;
const auto Feed = [&](const MTPPrivacyRule &rule) {
rule.match([&](const MTPDprivacyValueAllowAll &) {
SetOption(Option::Everyone);
}, [&](const MTPDprivacyValueAllowContacts &) {
SetOption(Option::Contacts);
}, [&](const MTPDprivacyValueAllowUsers &data) {
const auto &users = data.vusers().v;
always.reserve(always.size() + users.size());
for (const auto userId : users) {
const auto user = _session->data().user(UserId(userId.v));
if (!base::contains(never, user)
&& !base::contains(always, user)) {
always.emplace_back(user);
}
}
}, [&](const MTPDprivacyValueAllowChatParticipants &data) {
const auto &chats = data.vchats().v;
always.reserve(always.size() + chats.size());
for (const auto &chatId : chats) {
const auto chat = _session->data().chatLoaded(chatId);
const auto peer = chat
? static_cast<PeerData*>(chat)
: _session->data().channelLoaded(chatId);
if (peer
&& !base::contains(never, peer)
&& !base::contains(always, peer)) {
always.emplace_back(peer);
}
}
}, [&](const MTPDprivacyValueDisallowContacts &) {
// not supported
}, [&](const MTPDprivacyValueDisallowAll &) {
SetOption(Option::Nobody);
}, [&](const MTPDprivacyValueDisallowUsers &data) {
const auto &users = data.vusers().v;
never.reserve(never.size() + users.size());
for (const auto userId : users) {
const auto user = _session->data().user(UserId(userId.v));
if (!base::contains(always, user)
&& !base::contains(never, user)) {
never.emplace_back(user);
}
}
}, [&](const MTPDprivacyValueDisallowChatParticipants &data) {
const auto &chats = data.vchats().v;
never.reserve(never.size() + chats.size());
for (const auto &chatId : chats) {
const auto chat = _session->data().chatLoaded(chatId);
const auto peer = chat
? static_cast<PeerData*>(chat)
: _session->data().channelLoaded(chatId);
if (peer
&& !base::contains(always, peer)
&& !base::contains(never, peer)) {
never.emplace_back(peer);
}
}
});
};
for (const auto &rule : rules) {
Feed(rule);
}
Feed(MTP_privacyValueDisallowAll()); // disallow by default.
return result;
}
void ApiWrap::pushPrivacy(
Privacy::Key key,
const QVector<MTPPrivacyRule> &rules) {
const auto &saved = (_privacyValues[key] = parsePrivacy(rules));
const auto i = _privacyChanges.find(key);
if (i != end(_privacyChanges)) {
i->second.fire_copy(saved);
}
}
auto ApiWrap::privacyValue(Privacy::Key key) -> rpl::producer<Privacy> {
if (const auto i = _privacyValues.find(key); i != end(_privacyValues)) {
return _privacyChanges[key].events_starting_with_copy(i->second);
} else {
return _privacyChanges[key].events();
}
}
void ApiWrap::reloadBlockedPeers() {
if (_blockedPeersRequestId) {
return;
}
_blockedPeersRequestId = request(MTPcontacts_GetBlocked(
MTP_int(0),
MTP_int(kBlockedFirstSlice)
)).done([=](const MTPcontacts_Blocked &result) {
_blockedPeersRequestId = 0;
const auto push = [&](
int count,
const QVector<MTPPeerBlocked> &list) {
auto slice = BlockedPeersSlice();
slice.total = std::max(count, list.size());
slice.list.reserve(list.size());
for (const auto &contact : list) {
contact.match([&](const MTPDpeerBlocked &data) {
const auto peer = _session->data().peerLoaded(
peerFromMTP(data.vpeer_id()));
if (peer) {
peer->setIsBlocked(true);
slice.list.push_back({ peer, data.vdate().v });
}
});
}
if (!_blockedPeersSlice || *_blockedPeersSlice != slice) {
_blockedPeersSlice = slice;
_blockedPeersChanges.fire(std::move(slice));
}
};
result.match([&](const MTPDcontacts_blockedSlice &data) {
_session->data().processUsers(data.vusers());
push(data.vcount().v, data.vblocked().v);
}, [&](const MTPDcontacts_blocked &data) {
_session->data().processUsers(data.vusers());
push(0, data.vblocked().v);
});
}).fail([=](const MTP::Error &error) {
_blockedPeersRequestId = 0;
}).send();
}
auto ApiWrap::blockedPeersSlice() -> rpl::producer<BlockedPeersSlice> {
if (!_blockedPeersSlice) {
reloadBlockedPeers();
}
return _blockedPeersSlice
? _blockedPeersChanges.events_starting_with_copy(*_blockedPeersSlice)
: (_blockedPeersChanges.events() | rpl::type_erased());
}
Api::Authorizations &ApiWrap::authorizations() {
return *_authorizations;
}
@@ -5056,6 +4668,14 @@ Api::AttachedStickers &ApiWrap::attachedStickers() {
return *_attachedStickers;
}
Api::BlockedPeers &ApiWrap::blockedPeers() {
return *_blockedPeers;
}
Api::CloudPassword &ApiWrap::cloudPassword() {
return *_cloudPassword;
}
Api::SelfDestruct &ApiWrap::selfDestruct() {
return *_selfDestruct;
}
@@ -5068,6 +4688,10 @@ Api::GlobalPrivacy &ApiWrap::globalPrivacy() {
return *_globalPrivacy;
}
Api::UserPrivacy &ApiWrap::userPrivacy() {
return *_userPrivacy;
}
Api::InviteLinks &ApiWrap::inviteLinks() {
return *_inviteLinks;
}

View File

@@ -45,10 +45,6 @@ namespace Dialogs {
class Key;
} // namespace Dialogs
namespace Core {
struct CloudPasswordState;
} // namespace Core
namespace Ui {
struct PreparedList;
} // namespace Ui
@@ -58,9 +54,12 @@ namespace Api {
class Updates;
class Authorizations;
class AttachedStickers;
class BlockedPeers;
class CloudPassword;
class SelfDestruct;
class SensitiveContent;
class GlobalPrivacy;
class UserPrivacy;
class InviteLinks;
namespace details {
@@ -113,46 +112,6 @@ public:
using SendAction = Api::SendAction;
using MessageToSend = Api::MessageToSend;
struct Privacy {
enum class Key {
PhoneNumber,
AddedByPhone,
LastSeen,
Calls,
Invites,
CallsPeer2Peer,
Forwards,
ProfilePhoto,
};
enum class Option {
Everyone,
Contacts,
Nobody,
};
Option option = Option::Everyone;
std::vector<not_null<PeerData*>> always;
std::vector<not_null<PeerData*>> never;
static MTPInputPrivacyKey Input(Key key);
static std::optional<Key> KeyFromMTP(mtpTypeId type);
};
struct BlockedPeersSlice {
struct Item {
PeerData *peer = nullptr;
TimeId date = 0;
bool operator==(const Item &other) const;
bool operator!=(const Item &other) const;
};
QVector<Item> list;
int total = 0;
bool operator==(const BlockedPeersSlice &other) const;
bool operator!=(const BlockedPeersSlice &other) const;
};
explicit ApiWrap(not_null<Main::Session*> session);
~ApiWrap();
@@ -295,19 +254,10 @@ public:
void joinChannel(not_null<ChannelData*> channel);
void leaveChannel(not_null<ChannelData*> channel);
void blockPeer(not_null<PeerData*> peer);
void unblockPeer(not_null<PeerData*> peer, Fn<void()> onDone = nullptr);
void requestNotifySettings(const MTPInputNotifyPeer &peer);
void updateNotifySettingsDelayed(not_null<const PeerData*> peer);
void saveDraftToCloudDelayed(not_null<History*> history);
void savePrivacy(
const MTPInputPrivacyKey &key,
QVector<MTPInputPrivacyRule> &&rules);
void handlePrivacyChange(
Privacy::Key key,
const MTPVector<MTPPrivacyRule> &rules);
static int OnlineTillFromStatus(
const MTPUserStatus &status,
int currentOnlineTill);
@@ -433,12 +383,6 @@ public:
void uploadPeerPhoto(not_null<PeerData*> peer, QImage &&image);
void clearPeerPhoto(not_null<PhotoData*> photo);
void reloadPasswordState();
void applyPendingReset(const MTPaccount_ResetPasswordResult &data);
void clearUnconfirmedPassword();
rpl::producer<Core::CloudPasswordState> passwordState() const;
std::optional<Core::CloudPasswordState> passwordStateCurrent() const;
void reloadContactSignupSilent();
rpl::producer<bool> contactSignupSilent() const;
std::optional<bool> contactSignupSilentCurrent() const;
@@ -446,17 +390,14 @@ public:
void saveSelfBio(const QString &text, FnMut<void()> done);
void reloadPrivacy(Privacy::Key key);
rpl::producer<Privacy> privacyValue(Privacy::Key key);
void reloadBlockedPeers();
rpl::producer<BlockedPeersSlice> blockedPeersSlice();
[[nodiscard]] Api::Authorizations &authorizations();
[[nodiscard]] Api::AttachedStickers &attachedStickers();
[[nodiscard]] Api::BlockedPeers &blockedPeers();
[[nodiscard]] Api::CloudPassword &cloudPassword();
[[nodiscard]] Api::SelfDestruct &selfDestruct();
[[nodiscard]] Api::SensitiveContent &sensitiveContent();
[[nodiscard]] Api::GlobalPrivacy &globalPrivacy();
[[nodiscard]] Api::UserPrivacy &userPrivacy();
[[nodiscard]] Api::InviteLinks &inviteLinks();
void createPoll(
@@ -470,6 +411,8 @@ public:
void closePoll(not_null<HistoryItem*> item);
void reloadPollResults(not_null<HistoryItem*> item);
void updatePrivacyLastSeens();
private:
struct MessageDataRequest {
using Callbacks = QList<RequestMessageDataCallback>;
@@ -626,12 +569,6 @@ private:
void photoUploadReady(const FullMsgId &msgId, const MTPInputFile &file);
Privacy parsePrivacy(const QVector<MTPPrivacyRule> &rules);
void pushPrivacy(
Privacy::Key key,
const QVector<MTPPrivacyRule> &rules);
void updatePrivacyLastSeens(const QVector<MTPPrivacyRule> &rules);
void migrateDone(
not_null<PeerData*> peer,
not_null<ChannelData*> channel);
@@ -676,7 +613,6 @@ private:
QMap<uint64, QPair<uint64, mtpRequestId> > _stickerSetRequests;
QMap<ChannelData*, mtpRequestId> _channelAmInRequests;
base::flat_map<not_null<PeerData*>, mtpRequestId> _blockRequests;
base::flat_map<PeerId, mtpRequestId> _notifySettingRequests;
base::flat_map<not_null<History*>, mtpRequestId> _draftsSaveRequestIds;
base::Timer _draftsSaveTimer;
@@ -701,8 +637,6 @@ private:
base::flat_map<not_null<EmojiPtr>, StickersByEmoji> _stickersByEmoji;
base::flat_map<mtpTypeId, mtpRequestId> _privacySaveRequests;
mtpRequestId _contactsRequestId = 0;
mtpRequestId _contactsStatusesRequestId = 0;
@@ -765,27 +699,18 @@ private:
base::flat_map<FullMsgId, not_null<PeerData*>> _peerPhotoUploads;
mtpRequestId _passwordRequestId = 0;
std::unique_ptr<Core::CloudPasswordState> _passwordState;
rpl::event_stream<Core::CloudPasswordState> _passwordStateChanges;
mtpRequestId _saveBioRequestId = 0;
FnMut<void()> _saveBioDone;
QString _saveBioText;
base::flat_map<Privacy::Key, mtpRequestId> _privacyRequestIds;
base::flat_map<Privacy::Key, Privacy> _privacyValues;
std::map<Privacy::Key, rpl::event_stream<Privacy>> _privacyChanges;
mtpRequestId _blockedPeersRequestId = 0;
std::optional<BlockedPeersSlice> _blockedPeersSlice;
rpl::event_stream<BlockedPeersSlice> _blockedPeersChanges;
const std::unique_ptr<Api::Authorizations> _authorizations;
const std::unique_ptr<Api::AttachedStickers> _attachedStickers;
const std::unique_ptr<Api::BlockedPeers> _blockedPeers;
const std::unique_ptr<Api::CloudPassword> _cloudPassword;
const std::unique_ptr<Api::SelfDestruct> _selfDestruct;
const std::unique_ptr<Api::SensitiveContent> _sensitiveContent;
const std::unique_ptr<Api::GlobalPrivacy> _globalPrivacy;
const std::unique_ptr<Api::UserPrivacy> _userPrivacy;
const std::unique_ptr<Api::InviteLinks> _inviteLinks;
base::flat_map<FullMsgId, mtpRequestId> _pollVotesRequestIds;

View File

@@ -7,52 +7,15 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "app.h"
#include "lang/lang_keys.h"
#include "boxes/confirm_box.h"
#include "data/data_channel.h"
#include "data/data_chat.h"
#include "data/data_user.h"
#include "data/data_abstract_structure.h"
#include "data/data_media_types.h"
#include "data/data_session.h"
#include "data/data_document.h"
#include "history/history.h"
#include "history/history_location_manager.h"
#include "history/history_item_components.h"
#include "history/view/history_view_element.h"
#include "media/audio/media_audio.h"
#include "ui/image/image.h"
#include "ui/cached_round_corners.h"
#include "inline_bots/inline_bot_layout_item.h"
#include "core/crash_reports.h"
#include "core/update_checker.h"
#include "core/sandbox.h"
#include "core/application.h"
#include "window/notifications_manager.h"
#include "window/window_controller.h"
#include "platform/platform_notifications_manager.h"
#include "storage/file_upload.h"
#include "storage/localstorage.h"
#include "storage/storage_facade.h"
#include "storage/storage_shared_media.h"
#include "mainwindow.h"
#include "mainwidget.h"
#include "apiwrap.h"
#include "main/main_session.h"
#include "styles/style_boxes.h"
#include "styles/style_overview.h"
#include "styles/style_media_view.h"
#include "styles/style_chat_helpers.h"
#include "styles/style_chat.h"
#include "styles/style_layers.h"
#include <QtCore/QBuffer>
#include <QtGui/QFontDatabase>
#ifdef OS_MAC_OLD
#include <libexif/exif-data.h>
#endif // OS_MAC_OLD
namespace {
constexpr auto kImageAreaLimit = 12'032 * 9'024;
@@ -69,15 +32,6 @@ HistoryView::Element *hoveredItem = nullptr,
namespace App {
void initMedia() {
Ui::StartCachedCorners();
}
void deinitMedia() {
Ui::FinishCachedCorners();
Data::clearGlobalStructures();
}
void hoveredItem(HistoryView::Element *item) {
::hoveredItem = item;
}
@@ -168,80 +122,4 @@ namespace App {
App::quit();
}
QImage readImage(QByteArray data, QByteArray *format, bool opaque, bool *animated) {
if (data.isEmpty()) {
return QImage();
}
QByteArray tmpFormat;
QImage result;
QBuffer buffer(&data);
if (!format) {
format = &tmpFormat;
}
{
QImageReader reader(&buffer, *format);
#ifndef OS_MAC_OLD
reader.setAutoTransform(true);
#endif // OS_MAC_OLD
if (animated) *animated = reader.supportsAnimation() && reader.imageCount() > 1;
if (!reader.canRead()) {
return QImage();
}
const auto imageSize = reader.size();
if (imageSize.width() * imageSize.height() > kImageAreaLimit) {
return QImage();
}
QByteArray fmt = reader.format();
if (!fmt.isEmpty()) *format = fmt;
if (!reader.read(&result)) {
return QImage();
}
fmt = reader.format();
if (!fmt.isEmpty()) *format = fmt;
}
buffer.seek(0);
auto fmt = QString::fromUtf8(*format).toLower();
if (fmt == "jpg" || fmt == "jpeg") {
#ifdef OS_MAC_OLD
if (auto exifData = exif_data_new_from_data((const uchar*)(data.constData()), data.size())) {
auto byteOrder = exif_data_get_byte_order(exifData);
if (auto exifEntry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION)) {
auto orientationFix = [exifEntry, byteOrder] {
auto orientation = exif_get_short(exifEntry->data, byteOrder);
switch (orientation) {
case 2: return QTransform(-1, 0, 0, 1, 0, 0);
case 3: return QTransform(-1, 0, 0, -1, 0, 0);
case 4: return QTransform(1, 0, 0, -1, 0, 0);
case 5: return QTransform(0, -1, -1, 0, 0, 0);
case 6: return QTransform(0, 1, -1, 0, 0, 0);
case 7: return QTransform(0, 1, 1, 0, 0, 0);
case 8: return QTransform(0, -1, 1, 0, 0, 0);
}
return QTransform();
};
result = result.transformed(orientationFix());
}
exif_data_free(exifData);
}
#endif // OS_MAC_OLD
} else if (opaque) {
result = Images::prepareOpaque(std::move(result));
}
return result;
}
QImage readImage(const QString &file, QByteArray *format, bool opaque, bool *animated, QByteArray *content) {
QFile f(file);
if (f.size() > kImageSizeLimit || !f.open(QIODevice::ReadOnly)) {
if (animated) *animated = false;
return QImage();
}
auto imageBytes = f.readAll();
auto result = readImage(imageBytes, format, opaque, animated);
if (content && !result.isNull()) {
*content = imageBytes;
}
return result;
}
}

View File

@@ -7,8 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once
#include "data/data_types.h"
namespace HistoryView {
class Element;
} // namespace HistoryView
@@ -26,9 +24,6 @@ namespace App {
HistoryView::Element *mousedItem();
void clearMousedItems();
void initMedia();
void deinitMedia();
enum LaunchState {
Launched = 0,
QuitRequested = 1,
@@ -40,8 +35,4 @@ namespace App {
void setLaunchState(LaunchState state);
void restart();
constexpr auto kImageSizeLimit = 64 * 1024 * 1024; // Open images up to 64mb jpg/png/gif
QImage readImage(QByteArray data, QByteArray *format = nullptr, bool opaque = true, bool *animated = nullptr);
QImage readImage(const QString &file, QByteArray *format = nullptr, bool opaque = true, bool *animated = nullptr, QByteArray *content = 0);
};

View File

@@ -95,9 +95,7 @@ void AboutBox::showVersionHistory() {
url += qsl("win64/%1.zip");
} else if (Platform::IsMac()) {
url += qsl("mac/%1.zip");
} else if (Platform::IsLinux32Bit()) {
url += qsl("linux32/%1.tar.xz");
} else if (Platform::IsLinux64Bit()) {
} else if (Platform::IsLinux()) {
url += qsl("linux/%1.tar.xz");
} else {
Unexpected("Platform value.");

View File

@@ -9,7 +9,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwidget.h"
#include "mainwindow.h"
#include "app.h"
namespace Ui {
namespace internal {

View File

@@ -7,41 +7,139 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "boxes/auto_lock_box.h"
#include "lang/lang_keys.h"
#include "storage/localstorage.h"
#include "core/application.h"
#include "mainwindow.h"
#include "lang/lang_keys.h"
#include "ui/widgets/checkbox.h"
#include "ui/widgets/time_input.h"
#include "ui/ui_utility.h"
#include "styles/style_layers.h"
#include "styles/style_boxes.h"
AutoLockBox::AutoLockBox(QWidget*, not_null<Main::Session*> session)
: _session(session) {
namespace {
constexpr auto kCustom = std::numeric_limits<int>::max();
constexpr auto kOptions = { 60, 300, 3600, 18000, kCustom };
constexpr auto kDefaultCustom = "10:00"_cs;
auto TimeString(int seconds) {
const auto hours = seconds / 3600;
const auto minutes = (seconds - hours * 3600) / 60;
return QString("%1:%2").arg(hours).arg(minutes, 2, 10, QLatin1Char('0'));
}
} // namespace
AutoLockBox::AutoLockBox(QWidget*) {
}
void AutoLockBox::prepare() {
setTitle(tr::lng_passcode_autolock());
addButton(tr::lng_box_ok(), [this] { closeBox(); });
addButton(tr::lng_box_ok(), [=] { closeBox(); });
auto options = { 60, 300, 3600, 18000 };
const auto currentTime = Core::App().settings().autoLock();
auto group = std::make_shared<Ui::RadiobuttonGroup>(
Core::App().settings().autoLock());
const auto group = std::make_shared<Ui::RadiobuttonGroup>(
ranges::contains(kOptions, currentTime) ? currentTime : kCustom);
const auto x = st::boxPadding.left() + st::boxOptionListPadding.left();
auto y = st::boxOptionListPadding.top() + st::autolockButton.margin.top();
auto count = int(options.size());
const auto count = int(kOptions.size());
_options.reserve(count);
for (auto seconds : options) {
_options.emplace_back(this, group, seconds, (seconds % 3600) ? tr::lng_passcode_autolock_minutes(tr::now, lt_count, seconds / 60) : tr::lng_passcode_autolock_hours(tr::now, lt_count, seconds / 3600), st::autolockButton);
_options.back()->moveToLeft(st::boxPadding.left() + st::boxOptionListPadding.left(), y);
for (const auto seconds : kOptions) {
const auto text = [&] {
if (seconds == kCustom) {
return QString();
}
const auto minutes = (seconds % 3600);
return (minutes
? tr::lng_passcode_autolock_minutes
: tr::lng_passcode_autolock_hours)(
tr::now,
lt_count,
minutes ? (seconds / 60) : (seconds / 3600));
}();
_options.emplace_back(
this,
group,
seconds,
text,
st::autolockButton);
_options.back()->moveToLeft(x, y);
y += _options.back()->heightNoMargins() + st::boxOptionListSkip;
}
group->setChangedCallback([this](int value) { durationChanged(value); });
setDimensions(st::autolockWidth, st::boxOptionListPadding.top() + count * _options.back()->heightNoMargins() + (count - 1) * st::boxOptionListSkip + st::boxOptionListPadding.bottom() + st::boxPadding.bottom());
const auto timeInput = [&] {
const auto &last = _options.back();
const auto &st = st::autolockButton;
const auto textLeft = st.checkPosition.x()
+ last->checkRect().width()
+ st.textPosition.x();
const auto textTop = st.margin.top() + st.textPosition.y();
const auto timeInput = Ui::CreateChild<Ui::TimeInput>(
this,
(group->value() == kCustom)
? TimeString(currentTime)
: kDefaultCustom.utf8(),
st::autolockTimeField,
st::autolockDateField,
st::scheduleTimeSeparator,
st::scheduleTimeSeparatorPadding);
timeInput->resizeToWidth(st::autolockTimeWidth);
timeInput->moveToLeft(last->x() + textLeft, last->y() + textTop);
return timeInput;
}();
const auto collect = [=] {
const auto timeValue = timeInput->valueCurrent().split(':');
if (timeValue.size() != 2) {
return 0;
}
return timeValue[0].toInt() * 3600 + timeValue[1].toInt() * 60;
};
timeInput->focuses(
) | rpl::start_with_next([=] {
group->setValue(kCustom);
}, lifetime());
group->setChangedCallback([=](int value) {
if (value != kCustom) {
durationChanged(value);
} else {
timeInput->setFocusFast();
}
});
rpl::merge(
boxClosing() | rpl::filter([=] { return group->value() == kCustom; }),
timeInput->submitRequests()
) | rpl::start_with_next([=] {
if (const auto result = collect()) {
durationChanged(result);
} else {
timeInput->showError();
}
}, lifetime());
const auto timeInputBottom = timeInput->y() + timeInput->height();
setDimensions(
st::autolockWidth,
st::boxOptionListPadding.top()
+ (timeInputBottom - _options.back()->bottomNoMargins())
+ count * _options.back()->heightNoMargins()
+ (count - 1) * st::boxOptionListSkip
+ st::boxOptionListPadding.bottom()
+ st::boxPadding.bottom());
}
void AutoLockBox::durationChanged(int seconds) {
if (Core::App().settings().autoLock() == seconds) {
closeBox();
return;
}
Core::App().settings().setAutoLock(seconds);
Core::App().saveSettingsDelayed();

View File

@@ -9,17 +9,13 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/abstract_box.h"
namespace Main {
class Session;
} // namespace Main
namespace Ui {
class Radiobutton;
} // namespace Ui
class AutoLockBox : public Ui::BoxContent {
public:
AutoLockBox(QWidget*, not_null<Main::Session*> session);
AutoLockBox(QWidget*);
protected:
void prepare() override;
@@ -27,8 +23,6 @@ protected:
private:
void durationChanged(int seconds);
const not_null<Main::Session*> _session;
std::vector<object_ptr<Ui::Radiobutton>> _options;
};

View File

@@ -255,7 +255,7 @@ void BackgroundBox::Inner::updatePapers() {
_papers = _session->data().wallpapers(
) | ranges::views::filter([](const Data::WallPaper &paper) {
return !paper.isPattern() || paper.backgroundColor().has_value();
return !paper.isPattern() || !paper.backgroundColors().empty();
}) | ranges::views::transform([](const Data::WallPaper &paper) {
return Paper{ paper };
}) | ranges::to_vector;
@@ -326,8 +326,18 @@ void BackgroundBox::Inner::validatePaperThumbnail(
paper.dataMedia = document->createMediaView();
paper.dataMedia->thumbnailWanted(paper.data.fileOrigin());
}
}
if (!paper.dataMedia || !paper.dataMedia->thumbnail()) {
if (!paper.dataMedia->thumbnail()) {
return;
}
} else if (!paper.data.backgroundColors().empty()) {
paper.thumbnail = Ui::PixmapFromImage(
Data::GenerateWallPaper(
st::backgroundSize * cIntRetinaFactor(),
paper.data.backgroundColors(),
paper.data.gradientRotation()));
paper.thumbnail.setDevicePixelRatio(cRetinaFactor());
return;
} else {
return;
}
}
@@ -336,12 +346,11 @@ void BackgroundBox::Inner::validatePaperThumbnail(
: paper.dataMedia->thumbnail();
auto original = thumbnail->original();
if (paper.data.isPattern()) {
const auto color = *paper.data.backgroundColor();
original = Data::PreparePatternImage(
std::move(original),
color,
Data::PatternColor(color),
paper.data.patternIntensity());
paper.data.backgroundColors(),
paper.data.gradientRotation(),
paper.data.patternOpacity());
}
paper.thumbnail = Ui::PixmapFromImage(TakeMiddleSample(
original,

View File

@@ -279,7 +279,7 @@ bool ServiceCheck::checkRippleStartPosition(QPoint position) const {
});
}
AdminLog::OwnedItem GenerateTextItem(
[[nodiscard]] AdminLog::OwnedItem GenerateTextItem(
not_null<HistoryView::ElementDelegate*> delegate,
not_null<History*> history,
const QString &text,
@@ -308,7 +308,7 @@ AdminLog::OwnedItem GenerateTextItem(
return AdminLog::OwnedItem(delegate, item);
}
QImage PrepareScaledNonPattern(
[[nodiscard]] QImage PrepareScaledNonPattern(
const QImage &image,
Images::Option blur) {
const auto size = st::boxWideWidth;
@@ -331,66 +331,31 @@ QImage PrepareScaledNonPattern(
size);
}
QImage ColorizePattern(QImage image, QColor color) {
if (image.format() != QImage::Format_ARGB32_Premultiplied) {
image = std::move(image).convertToFormat(
QImage::Format_ARGB32_Premultiplied);
}
// Similar to style::colorizeImage.
// But style::colorizeImage takes pattern with all pixels having the
// same components value, from (0, 0, 0, 0) to (255, 255, 255, 255).
//
// While in patterns we have different value ranges, usually they are
// from (0, 0, 0, 0) to (0, 0, 0, 255), so we should use only 'alpha'.
const auto width = image.width();
const auto height = image.height();
const auto pattern = anim::shifted(color);
constexpr auto resultIntsPerPixel = 1;
const auto resultIntsPerLine = (image.bytesPerLine() >> 2);
const auto resultIntsAdded = resultIntsPerLine - width * resultIntsPerPixel;
auto resultInts = reinterpret_cast<uint32*>(image.bits());
Assert(resultIntsAdded >= 0);
Assert(image.depth() == static_cast<int>((resultIntsPerPixel * sizeof(uint32)) << 3));
Assert(image.bytesPerLine() == (resultIntsPerLine << 2));
const auto maskBytesPerPixel = (image.depth() >> 3);
const auto maskBytesPerLine = image.bytesPerLine();
const auto maskBytesAdded = maskBytesPerLine - width * maskBytesPerPixel;
// We want to read the last byte of four available.
// This is the difference with style::colorizeImage.
auto maskBytes = image.constBits() + (maskBytesPerPixel - 1);
Assert(maskBytesAdded >= 0);
Assert(image.depth() == (maskBytesPerPixel << 3));
for (auto y = 0; y != height; ++y) {
for (auto x = 0; x != width; ++x) {
auto maskOpacity = static_cast<anim::ShiftedMultiplier>(*maskBytes) + 1;
*resultInts = anim::unshifted(pattern * maskOpacity);
maskBytes += maskBytesPerPixel;
resultInts += resultIntsPerPixel;
}
maskBytes += maskBytesAdded;
resultInts += resultIntsAdded;
}
return image;
}
QImage PrepareScaledFromFull(
[[nodiscard]] QImage PrepareScaledFromFull(
const QImage &image,
std::optional<QColor> patternBackground,
bool isPattern,
const std::vector<QColor> &background,
int gradientRotation,
float64 patternOpacity,
Images::Option blur = Images::Option(0)) {
auto result = PrepareScaledNonPattern(image, blur);
if (patternBackground) {
result = ColorizePattern(
if (isPattern) {
result = Data::PreparePatternImage(
std::move(result),
Data::PatternColor(*patternBackground));
background,
gradientRotation,
patternOpacity);
}
return std::move(result).convertToFormat(
QImage::Format_ARGB32_Premultiplied);
}
[[nodiscard]] QImage BlackImage(QSize size) {
auto result = QImage(size, QImage::Format_ARGB32_Premultiplied);
result.fill(Qt::black);
return result;
}
} // namespace
BackgroundPreviewBox::BackgroundPreviewBox(
@@ -415,12 +380,28 @@ BackgroundPreviewBox::BackgroundPreviewBox(
if (_media) {
_media->thumbnailWanted(_paper.fileOrigin());
}
generateBackground();
_controller->session().downloaderTaskFinished(
) | rpl::start_with_next([=] {
update();
}, lifetime());
}
void BackgroundPreviewBox::generateBackground() {
if (_paper.backgroundColors().empty()) {
return;
}
const auto size = QSize(st::boxWideWidth, st::boxWideWidth)
* cIntRetinaFactor();
_generated = Ui::PixmapFromImage((_paper.patternOpacity() >= 0.)
? Data::GenerateWallPaper(
size,
_paper.backgroundColors(),
_paper.gradientRotation())
: BlackImage(size));
_generated.setDevicePixelRatio(cRetinaFactor());
}
not_null<HistoryView::ElementDelegate*> BackgroundPreviewBox::delegate() {
return static_cast<HistoryView::ElementDelegate*>(this);
}
@@ -433,7 +414,7 @@ void BackgroundPreviewBox::prepare() {
if (_paper.hasShareUrl()) {
addLeftButton(tr::lng_background_share(), [=] { share(); });
}
updateServiceBg(_paper.backgroundColor());
updateServiceBg(_paper.backgroundColors());
_paper.loadDocument();
const auto document = _paper.document();
@@ -521,21 +502,23 @@ void BackgroundPreviewBox::paintEvent(QPaintEvent *e) {
Painter p(this);
const auto ms = crl::now();
const auto color = _paper.backgroundColor();
if (color) {
p.fillRect(e->rect(), *color);
if (_scaled.isNull()) {
setScaledFromThumb();
}
if (!color || _paper.isPattern()) {
if (!_scaled.isNull() || setScaledFromThumb()) {
paintImage(p);
paintRadial(p);
} else if (!color) {
p.fillRect(e->rect(), st::boxBg);
return;
} else {
// Progress of pattern loading.
paintRadial(p);
}
if (!_generated.isNull()
&& (_scaled.isNull()
|| (_fadeOutThumbnail.isNull() && _fadeIn.animating()))) {
p.drawPixmap(0, 0, _generated);
}
if (!_scaled.isNull()) {
paintImage(p);
paintRadial(p);
} else if (_generated.isNull()) {
p.fillRect(e->rect(), st::boxBg);
return;
} else {
// Progress of pattern loading.
paintRadial(p);
}
paintTexts(p, ms);
}
@@ -543,10 +526,6 @@ void BackgroundPreviewBox::paintEvent(QPaintEvent *e) {
void BackgroundPreviewBox::paintImage(Painter &p) {
Expects(!_scaled.isNull());
const auto master = _paper.isPattern()
? std::clamp(_paper.patternIntensity() / 100., 0., 1.)
: 1.;
const auto factor = cIntRetinaFactor();
const auto size = st::boxWideWidth;
const auto from = QRect(
@@ -563,7 +542,7 @@ void BackgroundPreviewBox::paintImage(Painter &p) {
const auto &pixmap = (!_blurred.isNull() && _paper.isBlurred())
? _blurred
: _scaled;
p.setOpacity(master * fade);
p.setOpacity(fade);
p.drawPixmap(rect(), pixmap, from);
checkBlurAnimationStart();
}
@@ -610,11 +589,18 @@ QRect BackgroundPreviewBox::radialRect() const {
void BackgroundPreviewBox::paintTexts(Painter &p, crl::time ms) {
const auto height1 = _text1->height();
const auto height2 = _text2->height();
const auto context = HistoryView::PaintContext{
.bubblesPattern = nullptr, // #TODO bubbles
.viewport = rect(),
.clip = rect(),
.selection = TextSelection(),
.now = ms,
};
p.translate(0, textsTop());
paintDate(p);
_text1->draw(p, rect(), TextSelection(), ms);
_text1->draw(p, context);
p.translate(0, height1);
_text2->draw(p, rect(), TextSelection(), ms);
_text2->draw(p, context);
p.translate(0, height2);
}
@@ -655,7 +641,10 @@ void BackgroundPreviewBox::radialAnimationCallback(crl::time now) {
checkLoadedDocument();
}
bool BackgroundPreviewBox::setScaledFromThumb() {
void BackgroundPreviewBox::setScaledFromThumb() {
if (!_scaled.isNull()) {
return;
}
const auto localThumbnail = _paper.localThumbnail();
const auto thumbnail = localThumbnail
? localThumbnail
@@ -663,13 +652,16 @@ bool BackgroundPreviewBox::setScaledFromThumb() {
? _media->thumbnail()
: nullptr;
if (!thumbnail) {
return false;
return;
} else if (_paper.isPattern() && _paper.document() != nullptr) {
return false;
return;
}
auto scaled = PrepareScaledFromFull(
thumbnail->original(),
patternBackgroundColor(),
_paper.isPattern(),
_paper.backgroundColors(),
_paper.gradientRotation(),
_paper.patternOpacity(),
_paper.document() ? Images::Option::Blurred : Images::Option(0));
auto blurred = (_paper.document() || _paper.isPattern())
? QImage()
@@ -677,13 +669,12 @@ bool BackgroundPreviewBox::setScaledFromThumb() {
Data::PrepareBlurredBackground(thumbnail->original()),
Images::Option(0));
setScaledFromImage(std::move(scaled), std::move(blurred));
return true;
}
void BackgroundPreviewBox::setScaledFromImage(
QImage &&image,
QImage &&blurred) {
updateServiceBg(Window::Theme::CountAverageColor(image));
updateServiceBg({ Window::Theme::CountAverageColor(image) });
if (!_full.isNull()) {
startFadeInFrom(std::move(_scaled));
}
@@ -710,16 +701,20 @@ void BackgroundPreviewBox::checkBlurAnimationStart() {
startFadeInFrom(_paper.isBlurred() ? _scaled : _blurred);
}
void BackgroundPreviewBox::updateServiceBg(std::optional<QColor> background) {
if (background) {
_serviceBg = Window::Theme::AdjustedColor(
st::msgServiceBg->c,
*background);
void BackgroundPreviewBox::updateServiceBg(const std::vector<QColor> &bg) {
const auto count = int(bg.size());
if (!count) {
return;
}
}
std::optional<QColor> BackgroundPreviewBox::patternBackgroundColor() const {
return _paper.isPattern() ? _paper.backgroundColor() : std::nullopt;
auto red = 0, green = 0, blue = 0;
for (const auto &color : bg) {
red += color.red();
green += color.green();
blue += color.blue();
}
_serviceBg = Window::Theme::AdjustedColor(
st::msgServiceBg->c,
QColor(red / count, green / count, blue / count));
}
void BackgroundPreviewBox::checkLoadedDocument() {
@@ -737,15 +732,23 @@ void BackgroundPreviewBox::checkLoadedDocument() {
crl::async([
this,
image = std::move(image),
patternBackground = patternBackgroundColor(),
isPattern = _paper.isPattern(),
background = _paper.backgroundColors(),
gradientRotation = _paper.gradientRotation(),
patternOpacity = _paper.patternOpacity(),
guard = _generating.make_guard()
]() mutable {
auto scaled = PrepareScaledFromFull(image, patternBackground);
auto blurred = patternBackground
? QImage()
: PrepareScaledNonPattern(
auto scaled = PrepareScaledFromFull(
image,
isPattern,
background,
gradientRotation,
patternOpacity);
auto blurred = !isPattern
? PrepareScaledNonPattern(
Data::PrepareBlurredBackground(image),
Images::Option(0));
Images::Option(0))
: QImage();
crl::on_main(std::move(guard), [
this,
image = std::move(image),
@@ -768,7 +771,7 @@ bool BackgroundPreviewBox::Start(
not_null<Window::SessionController*> controller,
const QString &slug,
const QMap<QString, QString> &params) {
if (const auto paper = Data::WallPaper::FromColorSlug(slug)) {
if (const auto paper = Data::WallPaper::FromColorsSlug(slug)) {
controller->show(Box<BackgroundPreviewBox>(
controller,
paper->withUrlParams(params)));

View File

@@ -56,11 +56,11 @@ private:
void radialAnimationCallback(crl::time now);
QRect radialRect() const;
void generateBackground();
void checkLoadedDocument();
bool setScaledFromThumb();
void setScaledFromThumb();
void setScaledFromImage(QImage &&image, QImage &&blurred);
void updateServiceBg(std::optional<QColor> background);
std::optional<QColor> patternBackgroundColor() const;
void updateServiceBg(const std::vector<QColor> &bg);
void paintImage(Painter &p);
void paintRadial(Painter &p);
void paintTexts(Painter &p, crl::time ms);
@@ -76,7 +76,7 @@ private:
Data::WallPaper _paper;
std::shared_ptr<Data::DocumentMedia> _media;
QImage _full;
QPixmap _scaled, _blurred, _fadeOutThumbnail;
QPixmap _generated, _scaled, _blurred, _fadeOutThumbnail;
Ui::Animations::Simple _fadeIn;
Ui::RadialAnimation _radial;
base::binary_guard _generating;

View File

@@ -324,7 +324,7 @@ passcodePadding: margins(0px, 0px, 0px, 5px);
passcodeTextLine: 28px;
passcodeLittleSkip: 5px;
passcodeAboutSkip: 7px;
passcodeSkip: 20px;
passcodeSkip: 23px;
newGroupAboutFg: windowSubTextFg;
newGroupPadding: margins(4px, 6px, 4px, 3px);
@@ -965,3 +965,11 @@ scheduleTimeSeparatorPadding: margins(2px, 0px, 2px, 0px);
boxAttentionDividerLabel: FlatLabel(boxDividerLabel) {
textFg: boxTextFgError;
}
autolockDateField: InputField(scheduleDateField) {
heightMin: 22px;
}
autolockTimeField: InputField(scheduleTimeField) {
heightMin: 20px;
}
autolockTimeWidth: 52px;

View File

@@ -41,7 +41,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "main/main_session.h"
#include "mtproto/mtproto_config.h"
#include "facades.h" // Ui::showChatsList
#include "app.h"
#include "styles/style_layers.h"
#include "styles/style_boxes.h"
@@ -282,7 +281,8 @@ void ConfirmBox::confirmed() {
}
} else if (const auto callbackPtr = std::get_if<2>(confirmed)) {
if (auto callback = base::take(*callbackPtr)) {
callback([=] { closeBox(); });
const auto weak = Ui::MakeWeak(this);
callback(crl::guard(weak, [=] { closeBox(); }));
}
}
}

View File

@@ -67,10 +67,7 @@ auto ListFromMimeData(not_null<const QMimeData*> data) {
if (result.error == Error::None) {
return result;
} else if (data->hasImage()) {
auto image = Platform::GetImageFromClipboard();
if (image.isNull()) {
image = qvariant_cast<QImage>(data->imageData());
}
auto image = qvariant_cast<QImage>(data->imageData());
if (!image.isNull()) {
return Storage::PrepareMediaFromImage(
std::move(image),

View File

@@ -170,63 +170,6 @@ void EditPrivacyBox::editExceptions(
Ui::LayerOption::KeepOther);
}
QVector<MTPInputPrivacyRule> EditPrivacyBox::collectResult() {
const auto collectInputUsers = [](const auto &peers) {
auto result = QVector<MTPInputUser>();
result.reserve(peers.size());
for (const auto peer : peers) {
if (const auto user = peer->asUser()) {
result.push_back(user->inputUser);
}
}
return result;
};
const auto collectInputChats = [](const auto &peers) {
auto result = QVector<MTPint>(); // #TODO ids
result.reserve(peers.size());
for (const auto peer : peers) {
if (!peer->isUser()) {
result.push_back(peerToBareMTPInt(peer->id));
}
}
return result;
};
constexpr auto kMaxRules = 3; // allow users, disallow users, option
auto result = QVector<MTPInputPrivacyRule>();
result.reserve(kMaxRules);
if (showExceptionLink(Exception::Always)) {
const auto users = collectInputUsers(_value.always);
const auto chats = collectInputChats(_value.always);
if (!users.empty()) {
result.push_back(MTP_inputPrivacyValueAllowUsers(MTP_vector<MTPInputUser>(users)));
}
if (!chats.empty()) {
result.push_back(MTP_inputPrivacyValueAllowChatParticipants(MTP_vector<MTPint>(chats)));
}
}
if (showExceptionLink(Exception::Never)) {
const auto users = collectInputUsers(_value.never);
const auto chats = collectInputChats(_value.never);
if (!users.empty()) {
result.push_back(MTP_inputPrivacyValueDisallowUsers(MTP_vector<MTPInputUser>(users)));
}
if (!chats.empty()) {
result.push_back(MTP_inputPrivacyValueDisallowChatParticipants(MTP_vector<MTPint>(chats)));
}
}
result.push_back([&] {
switch (_value.option) {
case Option::Everyone: return MTP_inputPrivacyValueAllowAll();
case Option::Contacts: return MTP_inputPrivacyValueAllowContacts();
case Option::Nobody: return MTP_inputPrivacyValueDisallowAll();
}
Unexpected("Option value in EditPrivacyBox::collectResult.");
}());
return result;
}
std::vector<not_null<PeerData*>> &EditPrivacyBox::exceptions(Exception exception) {
switch (exception) {
case Exception::Always: return _value.always;
@@ -379,10 +322,13 @@ void EditPrivacyBox::setupContent() {
const auto someAreDisallowed = (_value.option != Option::Everyone)
|| !_value.never.empty();
_controller->confirmSave(someAreDisallowed, crl::guard(this, [=] {
_value.ignoreAlways = !showExceptionLink(Exception::Always);
_value.ignoreNever = !showExceptionLink(Exception::Never);
_controller->saveAdditional();
_window->session().api().savePrivacy(
_controller->apiKey(),
collectResult());
_window->session().api().userPrivacy().save(
_controller->key(),
_value);
closeBox();
}));
});

View File

@@ -9,7 +9,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/abstract_box.h"
#include "mtproto/sender.h"
#include "apiwrap.h"
#include "api/api_user_privacy.h"
namespace Ui {
class VerticalLayout;
@@ -31,15 +31,14 @@ class EditPrivacyBox;
class EditPrivacyController {
public:
using Key = ApiWrap::Privacy::Key;
using Option = ApiWrap::Privacy::Option;
using Key = Api::UserPrivacy::Key;
using Option = Api::UserPrivacy::Option;
enum class Exception {
Always,
Never,
};
[[nodiscard]] virtual Key key() = 0;
[[nodiscard]] virtual MTPInputPrivacyKey apiKey() = 0;
[[nodiscard]] virtual rpl::producer<QString> title() = 0;
[[nodiscard]] virtual bool hasOption(Option option) {
@@ -102,8 +101,8 @@ private:
class EditPrivacyBox : public Ui::BoxContent {
public:
using Value = ApiWrap::Privacy;
using Option = Value::Option;
using Value = Api::UserPrivacy::Rule;
using Option = Api::UserPrivacy::Option;
using Exception = EditPrivacyController::Exception;
EditPrivacyBox(
@@ -124,7 +123,6 @@ protected:
private:
bool showExceptionLink(Exception exception) const;
void setupContent();
QVector<MTPInputPrivacyRule> collectResult();
Ui::FlatLabel *addLabel(
not_null<Ui::VerticalLayout*> container,

View File

@@ -14,7 +14,6 @@ Copyright (C) 2017, Nicholas Guriev <guriev-ns@ya.ru>
#include "ui/special_buttons.h"
#include "ui/widgets/checkbox.h"
#include "ui/widgets/labels.h"
#include "app.h"
#include "styles/style_layers.h"
#include "styles/style_boxes.h"

View File

@@ -14,6 +14,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/unixtime.h"
#include "mainwindow.h"
#include "apiwrap.h"
#include "api/api_cloud_password.h"
#include "main/main_session.h"
#include "main/main_domain.h"
#include "core/application.h"
@@ -43,7 +44,7 @@ enum class PasswordErrorType {
void SetCloudPassword(
not_null<Ui::GenericBox*> box,
not_null<Main::Session*> session) {
session->api().passwordState(
session->api().cloudPassword().state(
) | rpl::start_with_next([=] {
using namespace Settings;
const auto weak = Ui::MakeWeak(box);
@@ -101,49 +102,53 @@ void StartPendingReset(
not_null<Ui::BoxContent*> context,
Fn<void()> close) {
const auto weak = Ui::MakeWeak(context.get());
session->api().request(MTPaccount_ResetPassword(
)).done([=](const MTPaccount_ResetPasswordResult &result) {
session->api().applyPendingReset(result);
result.match([&](const MTPDaccount_resetPasswordOk &data) {
}, [&](const MTPDaccount_resetPasswordRequestedWait &data) {
}, [&](const MTPDaccount_resetPasswordFailedWait &data) {
constexpr auto kMinute = 60;
constexpr auto kHour = 3600;
constexpr auto kDay = 86400;
const auto left = std::max(
data.vretry_date().v - base::unixtime::now(),
kMinute);
const auto days = (left / kDay);
const auto hours = (left / kHour);
const auto minutes = (left / kMinute);
const auto duration = days
? tr::lng_group_call_duration_days(tr::now, lt_count, days)
: hours
? tr::lng_group_call_duration_hours(tr::now, lt_count, hours)
: tr::lng_group_call_duration_minutes(
tr::now,
lt_count,
minutes);
if (const auto strong = weak.data()) {
strong->getDelegate()->show(Box<InformBox>(
tr::lng_cloud_password_reset_later(
tr::now,
lt_duration,
duration)));
auto lifetime = std::make_shared<rpl::lifetime>();
auto finish = [=](const QString &message) mutable {
if (const auto strong = weak.data()) {
if (!message.isEmpty()) {
strong->getDelegate()->show(Box<InformBox>(message));
}
});
if (const auto strong = weak.data()) {
strong->closeBox();
}
close();
}).fail([=](const MTP::Error &error) {
if (const auto strong = weak.data()) {
strong->getDelegate()->show(
Box<InformBox>("Error: " + error.type()));
strong->closeBox();
if (lifetime) {
base::take(lifetime)->destroy();
}
close();
}).send();
};
session->api().cloudPassword().resetPassword(
) | rpl::start_with_next_error_done([=](
Api::CloudPassword::ResetRetryDate retryDate) {
constexpr auto kMinute = 60;
constexpr auto kHour = 3600;
constexpr auto kDay = 86400;
const auto left = std::max(
retryDate - base::unixtime::now(),
kMinute);
const auto days = (left / kDay);
const auto hours = (left / kHour);
const auto minutes = (left / kMinute);
const auto duration = days
? tr::lng_group_call_duration_days(tr::now, lt_count, days)
: hours
? tr::lng_group_call_duration_hours(tr::now, lt_count, hours)
: tr::lng_group_call_duration_minutes(
tr::now,
lt_count,
minutes);
if (const auto strong = weak.data()) {
strong->getDelegate()->show(Box<InformBox>(
tr::lng_cloud_password_reset_later(
tr::now,
lt_duration,
duration)));
}
}, [=](const QString &error) mutable {
finish("Error: " + error);
}, [=]() mutable {
finish({});
}, *lifetime);
}
} // namespace
@@ -184,21 +189,33 @@ PasscodeBox::PasscodeBox(
PasscodeBox::PasscodeBox(
QWidget*,
not_null<Main::Session*> session,
not_null<MTP::Instance*> mtp,
Main::Session *session,
const CloudFields &fields)
: _session(session)
, _api(&_session->mtp())
, _api(mtp)
, _turningOff(fields.turningOff)
, _cloudPwd(true)
, _cloudFields(fields)
, _about(st::boxWidth - st::boxPadding.left() * 1.5)
, _oldPasscode(this, st::defaultInputField, tr::lng_cloud_password_enter_old())
, _newPasscode(this, st::defaultInputField, fields.curRequest ? tr::lng_cloud_password_enter_new() : tr::lng_cloud_password_enter_first())
, _newPasscode(
this,
st::defaultInputField,
(fields.curRequest
? tr::lng_cloud_password_enter_new()
: tr::lng_cloud_password_enter_first()))
, _reenterPasscode(this, st::defaultInputField, tr::lng_cloud_password_confirm_new())
, _passwordHint(this, st::defaultInputField, fields.curRequest ? tr::lng_cloud_password_change_hint() : tr::lng_cloud_password_hint())
, _passwordHint(
this,
st::defaultInputField,
(fields.curRequest
? tr::lng_cloud_password_change_hint()
: tr::lng_cloud_password_hint()))
, _recoverEmail(this, st::defaultInputField, tr::lng_cloud_password_email())
, _recover(this, tr::lng_signin_recover(tr::now))
, _showRecoverLink(_cloudFields.hasRecovery || !_cloudFields.pendingResetDate) {
Expects(session != nullptr || !fields.fromRecoveryCode.isEmpty());
Expects(!_turningOff || _cloudFields.curRequest);
if (!_cloudFields.hint.isEmpty()) {
@@ -208,6 +225,13 @@ PasscodeBox::PasscodeBox(
}
}
PasscodeBox::PasscodeBox(
QWidget*,
not_null<Main::Session*> session,
const CloudFields &fields)
: PasscodeBox(nullptr, &session->mtp(), session, fields) {
}
rpl::producer<QByteArray> PasscodeBox::newPasswordSet() const {
return _newPasswordSet.events();
}
@@ -220,6 +244,10 @@ rpl::producer<> PasscodeBox::clearUnconfirmedPassword() const {
return _clearUnconfirmedPassword.events();
}
rpl::producer<MTPauth_Authorization> PasscodeBox::newAuthorization() const {
return _newAuthorization.events();
}
bool PasscodeBox::currentlyHave() const {
return _cloudPwd
? (!!_cloudFields.curRequest)
@@ -267,9 +295,11 @@ void PasscodeBox::prepare() {
} else {
_oldPasscode->hide();
setTitle(_cloudPwd
? tr::lng_cloud_password_create()
? (_cloudFields.fromRecoveryCode.isEmpty()
? tr::lng_cloud_password_create()
: tr::lng_cloud_password_change())
: tr::lng_passcode_create());
setDimensions(st::boxWidth, st::passcodePadding.top() + _newPasscode->height() + st::passcodeLittleSkip + _reenterPasscode->height() + st::passcodeSkip + (_cloudPwd ? _passwordHint->height() + st::passcodeLittleSkip : 0) + st::passcodeAboutSkip + _aboutHeight + (_cloudPwd ? (st::passcodeLittleSkip + _recoverEmail->height() + st::passcodeSkip) : st::passcodePadding.bottom()));
setDimensions(st::boxWidth, st::passcodePadding.top() + _newPasscode->height() + st::passcodeLittleSkip + _reenterPasscode->height() + st::passcodeSkip + (_cloudPwd ? _passwordHint->height() + st::passcodeLittleSkip : 0) + st::passcodeAboutSkip + _aboutHeight + ((_cloudPwd && _cloudFields.fromRecoveryCode.isEmpty()) ? (st::passcodeLittleSkip + _recoverEmail->height() + st::passcodeSkip) : st::passcodePadding.bottom()));
}
}
@@ -296,7 +326,10 @@ void PasscodeBox::prepare() {
_newPasscode->setVisible(!onlyCheck);
_reenterPasscode->setVisible(!onlyCheck);
_passwordHint->setVisible(!onlyCheck && _cloudPwd);
_recoverEmail->setVisible(!onlyCheck && _cloudPwd && !has);
_recoverEmail->setVisible(!onlyCheck
&& _cloudPwd
&& !has
&& _cloudFields.fromRecoveryCode.isEmpty());
}
void PasscodeBox::submit() {
@@ -395,21 +428,44 @@ void PasscodeBox::setInnerFocus() {
}
}
void PasscodeBox::recoverPasswordDone(
const QByteArray &newPasswordBytes,
const MTPauth_Authorization &result) {
if (_replacedBy) {
_replacedBy->closeBox();
}
_setRequest = 0;
const auto weak = Ui::MakeWeak(this);
_newAuthorization.fire_copy(result);
if (weak) {
_newPasswordSet.fire_copy(newPasswordBytes);
if (weak) {
getDelegate()->show(Box<InformBox>(
tr::lng_cloud_password_updated(tr::now)));
if (weak) {
closeBox();
}
}
}
}
void PasscodeBox::setPasswordDone(const QByteArray &newPasswordBytes) {
if (_replacedBy) {
_replacedBy->closeBox();
}
_setRequest = 0;
_newPasswordSet.fire_copy(newPasswordBytes);
const auto weak = Ui::MakeWeak(this);
const auto text = _reenterPasscode->isHidden()
? tr::lng_cloud_password_removed(tr::now)
: _oldPasscode->isHidden()
? tr::lng_cloud_password_was_set(tr::now)
: tr::lng_cloud_password_updated(tr::now);
getDelegate()->show(Box<InformBox>(text));
_newPasswordSet.fire_copy(newPasswordBytes);
if (weak) {
closeBox();
const auto text = _reenterPasscode->isHidden()
? tr::lng_cloud_password_removed(tr::now)
: _oldPasscode->isHidden()
? tr::lng_cloud_password_was_set(tr::now)
: tr::lng_cloud_password_updated(tr::now);
getDelegate()->show(Box<InformBox>(text));
if (weak) {
closeBox();
}
}
}
@@ -794,25 +850,44 @@ void PasscodeBox::setNewCloudPassword(const QString &newPassword) {
}
const auto hint = _passwordHint->getLastText();
const auto email = _recoverEmail->getLastText().trimmed();
const auto flags = MTPDaccount_passwordInputSettings::Flag::f_new_algo
| MTPDaccount_passwordInputSettings::Flag::f_new_password_hash
| MTPDaccount_passwordInputSettings::Flag::f_hint
| MTPDaccount_passwordInputSettings::Flag::f_email;
using Flag = MTPDaccount_passwordInputSettings::Flag;
const auto flags = Flag::f_new_algo
| Flag::f_new_password_hash
| Flag::f_hint
| (_cloudFields.fromRecoveryCode.isEmpty() ? Flag::f_email : Flag(0));
_checkPasswordCallback = nullptr;
_setRequest = _api.request(MTPaccount_UpdatePasswordSettings(
MTP_inputCheckPasswordEmpty(),
MTP_account_passwordInputSettings(
MTP_flags(flags),
Core::PrepareCloudPasswordAlgo(_cloudFields.newAlgo),
MTP_bytes(newPasswordHash.modpow),
MTP_string(hint),
MTP_string(email),
MTPSecureSecretSettings())
)).done([=](const MTPBool &result) {
setPasswordDone(newPasswordBytes);
}).fail([=](const MTP::Error &error) {
setPasswordFail(newPasswordBytes, email, error);
}).handleFloodErrors().send();
const auto settings = MTP_account_passwordInputSettings(
MTP_flags(flags),
Core::PrepareCloudPasswordAlgo(_cloudFields.newAlgo),
MTP_bytes(newPasswordHash.modpow),
MTP_string(hint),
MTP_string(email),
MTPSecureSecretSettings());
if (_cloudFields.fromRecoveryCode.isEmpty()) {
_setRequest = _api.request(MTPaccount_UpdatePasswordSettings(
MTP_inputCheckPasswordEmpty(),
settings
)).done([=](const MTPBool &result) {
setPasswordDone(newPasswordBytes);
}).fail([=](const MTP::Error &error) {
setPasswordFail(newPasswordBytes, email, error);
}).handleFloodErrors().send();
} else {
_setRequest = _api.request(MTPauth_RecoverPassword(
MTP_flags(MTPauth_RecoverPassword::Flag::f_new_settings),
MTP_string(_cloudFields.fromRecoveryCode),
settings
)).done([=](const MTPauth_Authorization &result) {
recoverPasswordDone(newPasswordBytes, result);
}).fail([=](const MTP::Error &error) {
if (MTP::IsFloodError(error)) {
_newError = tr::lng_flood_error(tr::now);
update();
}
setPasswordFail(newPasswordBytes, email, error);
}).handleFloodErrors().send();
}
}
void PasscodeBox::changeCloudPassword(
@@ -1000,6 +1075,7 @@ void PasscodeBox::emailChanged() {
void PasscodeBox::recoverByEmail() {
if (!_cloudFields.hasRecovery) {
Assert(_session != nullptr);
const auto session = _session;
const auto confirmBox = std::make_shared<QPointer<BoxContent>>();
const auto reset = crl::guard(this, [=] {
@@ -1031,19 +1107,19 @@ void PasscodeBox::recoverExpired() {
}
void PasscodeBox::recover() {
if (_pattern == "-") return;
if (_pattern == "-" || !_session) {
return;
}
const auto weak = Ui::MakeWeak(this);
const auto box = getDelegate()->show(Box<RecoverBox>(
&_api.instance(),
_session,
_pattern,
_cloudFields.notEmptyPassport,
_cloudFields.pendingResetDate != 0,
_cloudFields,
[weak] { if (weak) { weak->closeBox(); } }));
box->passwordCleared(
) | rpl::map_to(
QByteArray()
box->newPasswordSet(
) | rpl::start_to_stream(_newPasswordSet, lifetime());
box->recoveryExpired(
@@ -1066,18 +1142,19 @@ void PasscodeBox::recoverStartFail(const MTP::Error &error) {
RecoverBox::RecoverBox(
QWidget*,
not_null<Main::Session*> session,
not_null<MTP::Instance*> mtp,
Main::Session *session,
const QString &pattern,
bool notEmptyPassport,
bool hasPendingReset,
const PasscodeBox::CloudFields &fields,
Fn<void()> closeParent)
: _api(&session->mtp())
: _session(session)
, _api(mtp)
, _pattern(st::normalFont->elided(tr::lng_signin_recover_hint(tr::now, lt_recover_email, pattern), st::boxWidth - st::boxPadding.left() * 1.5))
, _notEmptyPassport(notEmptyPassport)
, _cloudFields(fields)
, _recoverCode(this, st::defaultInputField, tr::lng_signin_code())
, _noEmailAccess(this, tr::lng_signin_try_password(tr::now))
, _closeParent(std::move(closeParent)) {
if (hasPendingReset) {
if (_cloudFields.pendingResetDate != 0 || !session) {
_noEmailAccess.destroy();
} else {
_noEmailAccess->setClickedCallback([=] {
@@ -1101,8 +1178,8 @@ RecoverBox::RecoverBox(
}
}
rpl::producer<> RecoverBox::passwordCleared() const {
return _passwordCleared.events();
rpl::producer<QByteArray> RecoverBox::newPasswordSet() const {
return _newPasswordSet.events();
}
rpl::producer<> RecoverBox::recoveryExpired() const {
@@ -1168,17 +1245,29 @@ void RecoverBox::submit() {
}
const auto send = crl::guard(this, [=] {
_submitRequest = _api.request(MTPauth_RecoverPassword(
MTP_flags(0),
MTP_string(code),
MTPaccount_PasswordInputSettings()
)).done([=](const MTPauth_Authorization &result) {
codeSubmitDone(result);
}).fail([=](const MTP::Error &error) {
codeSubmitFail(error);
}).handleFloodErrors().send();
if (_cloudFields.turningOff) {
// From "Disable cloud password".
_submitRequest = _api.request(MTPauth_RecoverPassword(
MTP_flags(0),
MTP_string(code),
MTPaccount_PasswordInputSettings()
)).done([=](const MTPauth_Authorization &result) {
proceedToClear();
}).fail([=](const MTP::Error &error) {
checkSubmitFail(error);
}).handleFloodErrors().send();
} else {
// From "Change cloud password".
_submitRequest = _api.request(MTPauth_CheckRecoveryPassword(
MTP_string(code)
)).done([=](const MTPBool &result) {
proceedToChange(code);
}).fail([=](const MTP::Error &error) {
checkSubmitFail(error);
}).handleFloodErrors().send();
}
});
if (_notEmptyPassport) {
if (_cloudFields.notEmptyPassport) {
const auto confirmed = [=](Fn<void()> &&close) {
send();
close();
@@ -1204,16 +1293,46 @@ void RecoverBox::codeChanged() {
setError(QString());
}
void RecoverBox::codeSubmitDone(const MTPauth_Authorization &result) {
void RecoverBox::proceedToClear() {
_submitRequest = 0;
_passwordCleared.fire({});
_newPasswordSet.fire({});
getDelegate()->show(
Box<InformBox>(tr::lng_cloud_password_removed(tr::now)),
Ui::LayerOption::CloseOther);
}
void RecoverBox::codeSubmitFail(const MTP::Error &error) {
void RecoverBox::proceedToChange(const QString &code) {
Expects(!_cloudFields.turningOff);
_submitRequest = 0;
auto fields = _cloudFields;
fields.fromRecoveryCode = code;
fields.hasRecovery = false;
// we could've been turning off, no need to force new password then
// like if (_cloudFields.turningOff) { just RecoverPassword else Check }
fields.curRequest = {};
auto box = Box<PasscodeBox>(_session, fields);
box->boxClosing(
) | rpl::start_with_next([=] {
const auto weak = Ui::MakeWeak(this);
if (const auto onstack = _closeParent) {
onstack();
}
if (weak) {
weak->closeBox();
}
}, lifetime());
box->newPasswordSet(
) | rpl::start_with_next([=](QByteArray &&password) {
_newPasswordSet.fire(std::move(password));
}, lifetime());
getDelegate()->show(std::move(box));
}
void RecoverBox::checkSubmitFail(const MTP::Error &error) {
if (MTP::IsFloodError(error)) {
_submitRequest = 0;
setError(tr::lng_flood_error(tr::now));
@@ -1224,7 +1343,7 @@ void RecoverBox::codeSubmitFail(const MTP::Error &error) {
const QString &err = error.type();
if (err == qstr("PASSWORD_EMPTY")) {
_passwordCleared.fire({});
_newPasswordSet.fire(QByteArray());
getDelegate()->show(
Box<InformBox>(tr::lng_cloud_password_removed(tr::now)),
Ui::LayerOption::CloseOther);

View File

@@ -11,6 +11,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mtproto/sender.h"
#include "core/core_cloud_password.h"
namespace MTP {
class Instance;
} // namespace MTP
namespace Main {
class Session;
} // namespace Main
@@ -35,6 +39,7 @@ public:
Core::CloudPasswordCheckRequest curRequest;
Core::CloudPasswordAlgo newAlgo;
bool hasRecovery = false;
QString fromRecoveryCode;
bool notEmptyPassport = false;
QString hint;
Core::SecureSecretAlgo newSecureSecretAlgo;
@@ -47,6 +52,11 @@ public:
std::optional<QString> customDescription;
rpl::producer<QString> customSubmitButton;
};
PasscodeBox(
QWidget*,
not_null<MTP::Instance*> mtp,
Main::Session *session,
const CloudFields &fields);
PasscodeBox(
QWidget*,
not_null<Main::Session*> session,
@@ -56,6 +66,8 @@ public:
rpl::producer<> passwordReloadNeeded() const;
rpl::producer<> clearUnconfirmedPassword() const;
rpl::producer<MTPauth_Authorization> newAuthorization() const;
bool handleCustomCheckError(const MTP::Error &error);
bool handleCustomCheckError(const QString &type);
@@ -83,6 +95,9 @@ private:
bool onlyCheckCurrent() const;
void setPasswordDone(const QByteArray &newPasswordBytes);
void recoverPasswordDone(
const QByteArray &newPasswordBytes,
const MTPauth_Authorization &result);
void setPasswordFail(const MTP::Error &error);
void setPasswordFail(const QString &type);
void setPasswordFail(
@@ -132,7 +147,7 @@ private:
void passwordChecked();
void serverError();
const not_null<Main::Session*> _session;
Main::Session *_session = nullptr;
MTP::Sender _api;
QString _pattern;
@@ -163,6 +178,7 @@ private:
QString _oldError, _newError, _emailError;
rpl::event_stream<QByteArray> _newPasswordSet;
rpl::event_stream<MTPauth_Authorization> _newAuthorization;
rpl::event_stream<> _passwordReloadNeeded;
rpl::event_stream<> _clearUnconfirmedPassword;
@@ -172,14 +188,14 @@ class RecoverBox final : public Ui::BoxContent {
public:
RecoverBox(
QWidget*,
not_null<Main::Session*> session,
not_null<MTP::Instance*> mtp,
Main::Session *session,
const QString &pattern,
bool notEmptyPassport,
bool hasPendingReset,
const PasscodeBox::CloudFields &fields,
Fn<void()> closeParent = nullptr);
rpl::producer<> passwordCleared() const;
rpl::producer<> recoveryExpired() const;
[[nodiscard]] rpl::producer<QByteArray> newPasswordSet() const;
[[nodiscard]] rpl::producer<> recoveryExpired() const;
//void reloadPassword();
//void recoveryExpired();
@@ -194,15 +210,18 @@ protected:
private:
void submit();
void codeChanged();
void codeSubmitDone(const MTPauth_Authorization &result);
void codeSubmitFail(const MTP::Error &error);
void proceedToClear();
void proceedToChange(const QString &code);
void checkSubmitFail(const MTP::Error &error);
void setError(const QString &error);
Main::Session *_session = nullptr;
MTP::Sender _api;
mtpRequestId _submitRequest = 0;
QString _pattern;
bool _notEmptyPassport = false;
PasscodeBox::CloudFields _cloudFields;
object_ptr<Ui::InputField> _recoverCode;
object_ptr<Ui::LinkButton> _noEmailAccess;
@@ -210,7 +229,7 @@ private:
QString _error;
rpl::event_stream<> _passwordCleared;
rpl::event_stream<QByteArray> _newPasswordSet;
rpl::event_stream<> _recoveryExpired;
};

View File

@@ -30,7 +30,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "info/profile/info_profile_icon.h"
#include "apiwrap.h"
#include "facades.h" // Ui::showPeerHistory
#include "app.h"
#include "styles/style_boxes.h"
namespace {

View File

@@ -36,6 +36,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/unixtime.h"
#include "base/qt_adapters.h"
#include "apiwrap.h"
#include "api/api_cloud_password.h"
#include "main/main_session.h"
#include "styles/style_layers.h"
#include "styles/style_boxes.h"
@@ -444,7 +445,7 @@ void EditAdminBox::transferOwnership() {
? peer()->asChannel()->inputChannel
: MTP_inputChannelEmpty();
const auto api = &peer()->session().api();
api->reloadPasswordState();
api->cloudPassword().reload();
_checkTransferRequestId = api->request(MTPchannels_EditCreator(
channel,
MTP_inputUserEmpty(),
@@ -495,7 +496,7 @@ void EditAdminBox::transferOwnershipChecked() {
}
void EditAdminBox::requestTransferPassword(not_null<ChannelData*> channel) {
peer()->session().api().passwordState(
peer()->session().api().cloudPassword().state(
) | rpl::take(
1
) | rpl::start_with_next([=](const Core::CloudPasswordState &state) {

View File

@@ -47,7 +47,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/wrap/vertical_layout.h"
#include "window/window_session_controller.h"
#include "info/profile/info_profile_icon.h"
#include "app.h"
#include "apiwrap.h"
#include "api/api_invite_links.h"
#include "facades.h"

View File

@@ -27,7 +27,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "main/main_session.h"
#include "mainwindow.h"
#include "apiwrap.h"
#include "app.h"
#include "styles/style_layers.h"
#include "styles/style_boxes.h"
#include "styles/style_info.h"

View File

@@ -7,7 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "boxes/send_files_box.h"
#include "platform/platform_specific.h"
#include "lang/lang_keys.h"
#include "storage/localstorage.h"
#include "storage/storage_media_prepare.h"
@@ -52,7 +51,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/application.h"
#include "core/core_settings.h"
#include "facades.h" // App::LambdaDelayed.
#include "app.h"
#include "styles/style_chat.h"
#include "styles/style_layers.h"
#include "styles/style_boxes.h"
@@ -800,10 +798,7 @@ bool SendFilesBox::addFiles(not_null<const QMimeData*> data) {
if (result.error == Ui::PreparedList::Error::None) {
return result;
} else if (data->hasImage()) {
auto image = Platform::GetImageFromClipboard();
if (image.isNull()) {
image = qvariant_cast<QImage>(data->imageData());
}
auto image = qvariant_cast<QImage>(data->imageData());
if (!image.isNull()) {
return Storage::PrepareMediaFromImage(
std::move(image),

View File

@@ -19,7 +19,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_keys.h"
#include "main/main_session.h"
#include "apiwrap.h"
#include "app.h"
#include "styles/style_layers.h"
#include "styles/style_boxes.h"

View File

@@ -26,7 +26,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "boxes/confirm_box.h"
#include "base/unixtime.h"
#include "api/api_updates.h"
#include "app.h"
#include "apiwrap.h"
#include "styles/style_layers.h" // st::boxLabel.
#include "styles/style_calls.h"

View File

@@ -378,7 +378,8 @@ void Call::setupOutgoingVideo() {
Assert(state == Webrtc::VideoState::Active);
if (!_videoCapture) {
_videoCapture = _delegate->callGetVideoCapture(
_videoCaptureDeviceId);
_videoCaptureDeviceId,
_videoCaptureIsScreencast);
_videoCapture->setOutput(_videoOutgoing->sink());
}
if (_instance) {
@@ -735,7 +736,7 @@ void Call::createAndStartController(const MTPDphoneCall &call) {
.receiveTimeout = serverConfig.callPacketTimeoutMs / 1000.,
.dataSaving = tgcalls::DataSaving::Never,
.enableP2P = call.is_p2p_allowed(),
.enableAEC = !Platform::IsMac10_7OrGreater(),
.enableAEC = false,
.enableNS = true,
.enableAGC = true,
.enableVolumeControl = true,
@@ -985,7 +986,10 @@ void Call::setCurrentCameraDevice(const QString &deviceId) {
if (!_videoCaptureIsScreencast) {
_videoCaptureDeviceId = deviceId;
if (_videoCapture) {
_videoCapture->switchToDevice(deviceId.toStdString());
_videoCapture->switchToDevice(deviceId.toStdString(), false);
if (_instance) {
_instance->sendVideoDeviceUpdated();
}
}
}
}
@@ -1042,7 +1046,10 @@ void Call::toggleCameraSharing(bool enabled) {
const auto deviceId = Core::App().settings().callVideoInputDeviceId();
_videoCaptureDeviceId = deviceId;
if (_videoCapture) {
_videoCapture->switchToDevice(deviceId.toStdString());
_videoCapture->switchToDevice(deviceId.toStdString(), false);
if (_instance) {
_instance->sendVideoDeviceUpdated();
}
}
_videoOutgoing->setState(Webrtc::VideoState::Active);
}), true);
@@ -1066,7 +1073,10 @@ void Call::toggleScreenSharing(std::optional<QString> uniqueId) {
_videoCaptureIsScreencast = true;
_videoCaptureDeviceId = *uniqueId;
if (_videoCapture) {
_videoCapture->switchToDevice(uniqueId->toStdString());
_videoCapture->switchToDevice(uniqueId->toStdString(), true);
if (_instance) {
_instance->sendVideoDeviceUpdated();
}
}
_videoOutgoing->setState(Webrtc::VideoState::Active);
}

View File

@@ -77,8 +77,10 @@ public:
Fn<void()> onSuccess,
bool video) = 0;
virtual auto callGetVideoCapture(const QString &deviceId)
-> std::shared_ptr<tgcalls::VideoCaptureInterface> = 0;
virtual auto callGetVideoCapture(
const QString &deviceId,
bool isScreenCapture)
-> std::shared_ptr<tgcalls::VideoCaptureInterface> = 0;
virtual ~Delegate() = default;

View File

@@ -34,7 +34,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwidget.h"
#include "mtproto/mtproto_config.h"
#include "boxes/rate_call_box.h"
#include "app.h"
#include "app.h" // App::quitting
#include <tgcalls/VideoCaptureInterface.h>
#include <tgcalls/StaticThreads.h>
@@ -64,8 +64,10 @@ public:
Fn<void()> onSuccess,
bool video) override;
void callPlaySound(CallSound sound) override;
auto callGetVideoCapture(const QString &deviceId)
-> std::shared_ptr<tgcalls::VideoCaptureInterface> override;
auto callGetVideoCapture(
const QString &deviceId,
bool isScreenCapture)
-> std::shared_ptr<tgcalls::VideoCaptureInterface> override;
void groupCallFinished(not_null<GroupCall*> call) override;
void groupCallFailed(not_null<GroupCall*> call) override;
@@ -123,9 +125,11 @@ void Instance::Delegate::callPlaySound(CallSound sound) {
}());
}
auto Instance::Delegate::callGetVideoCapture(const QString &deviceId)
auto Instance::Delegate::callGetVideoCapture(
const QString &deviceId,
bool isScreenCapture)
-> std::shared_ptr<tgcalls::VideoCaptureInterface> {
return _instance->getVideoCapture(deviceId);
return _instance->getVideoCapture(deviceId, isScreenCapture);
}
void Instance::Delegate::groupCallFinished(not_null<GroupCall*> call) {
@@ -159,7 +163,7 @@ void Instance::Delegate::groupCallPlaySound(GroupCallSound sound) {
auto Instance::Delegate::groupCallGetVideoCapture(const QString &deviceId)
-> std::shared_ptr<tgcalls::VideoCaptureInterface> {
return _instance->getVideoCapture(deviceId);
return _instance->getVideoCapture(deviceId, false);
}
FnMut<void()> Instance::Delegate::groupCallAddAsyncWaiter() {
@@ -699,12 +703,15 @@ void Instance::requestPermissionOrFail(Platform::PermissionType type, Fn<void()>
}
std::shared_ptr<tgcalls::VideoCaptureInterface> Instance::getVideoCapture(
std::optional<QString> deviceId) {
std::optional<QString> deviceId,
bool isScreenCapture) {
if (auto result = _videoCapture.lock()) {
if (deviceId) {
result->switchToDevice((deviceId->isEmpty()
? Core::App().settings().callVideoInputDeviceId()
: *deviceId).toStdString());
result->switchToDevice(
(deviceId->isEmpty()
? Core::App().settings().callVideoInputDeviceId()
: *deviceId).toStdString(),
isScreenCapture);
}
return result;
}

View File

@@ -76,7 +76,8 @@ public:
bool minimizeCurrentActiveCall();
bool closeCurrentActiveCall();
[[nodiscard]] auto getVideoCapture(
std::optional<QString> deviceId = std::nullopt)
std::optional<QString> deviceId = std::nullopt,
bool isScreenCapture = false)
-> std::shared_ptr<tgcalls::VideoCaptureInterface>;
void requestPermissionsOrFail(Fn<void()> onSuccess, bool video = true);

View File

@@ -45,7 +45,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "platform/platform_specific.h"
#include "base/platform/base_platform_info.h"
#include "window/main_window.h"
#include "app.h"
#include "webrtc/webrtc_video_track.h"
#include "webrtc/webrtc_media_devices.h"
#include "styles/style_calls.h"
@@ -77,6 +76,9 @@ Panel::Panel(not_null<Call*> call)
, _mute(widget(), st::callMicrophoneMute, &st::callMicrophoneUnmute)
, _name(widget(), st::callName)
, _status(widget(), st::callStatus) {
_layerBg->setStyleOverrides(&st::groupCallBox, &st::groupCallLayerBox);
_layerBg->setHideByBackgroundClick(true);
_decline->setDuration(st::callPanelDuration);
_decline->entity()->setText(tr::lng_call_decline());
_cancel->setDuration(st::callPanelDuration);
@@ -158,9 +160,13 @@ void Panel::initWindow() {
_answerHangupRedial->height()).contains(widgetPoint)
|| (!_outgoingPreviewInBody
&& _outgoingVideoBubble->geometry().contains(widgetPoint));
return inControls
? Flag::None
: (Flag::Move | Flag::FullScreen);
if (inControls) {
return Flag::None | Flag(0);
}
const auto shown = _layerBg->topShownLayer();
return (!shown || !shown->geometry().contains(widgetPoint))
? (Flag::Move | Flag::FullScreen)
: Flag::None;
});
// Don't do that, it looks awful :(

View File

@@ -32,7 +32,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "main/main_session.h"
#include "boxes/abstract_box.h"
#include "base/timer.h"
#include "app.h"
#include "styles/style_calls.h"
#include "styles/style_chat.h" // style::GroupCallUserpics
#include "styles/style_layers.h"

View File

@@ -654,7 +654,7 @@ void GroupCall::toggleScreenSharing(
_screenWithAudio = withAudio;
_screenState = Webrtc::VideoState::Active;
if (changed && wasSharing && isSharingScreen()) {
_screenCapture->switchToDevice(uniqueId->toStdString());
_screenCapture->switchToDevice(uniqueId->toStdString(), true);
}
if (_screenInstance) {
_screenInstance->setIsMuted(!withAudio);
@@ -1715,13 +1715,13 @@ void GroupCall::handlePossibleCreateOrJoinResponse(
void GroupCall::handlePossibleCreateOrJoinResponse(
const MTPDgroupCall &data) {
setScheduledDate(data.vschedule_date().value_or_empty());
if (_acceptFields) {
if (!_instance && !_id) {
const auto input = MTP_inputGroupCall(
data.vid(),
data.vaccess_hash());
const auto scheduleDate = data.vschedule_date().value_or_empty();
setScheduledDate(scheduleDate);
if (const auto chat = _peer->asChat()) {
chat->setGroupCall(input, scheduleDate);
} else if (const auto group = _peer->asChannel()) {
@@ -1735,6 +1735,7 @@ void GroupCall::handlePossibleCreateOrJoinResponse(
} else if (_id != data.vid().v || !_instance) {
return;
}
setScheduledDate(data.vschedule_date().value_or_empty());
if (const auto streamDcId = data.vstream_dc_id()) {
_broadcastDcId = MTP::BareDcId(streamDcId->v);
}
@@ -1951,7 +1952,7 @@ void GroupCall::setupMediaDevices() {
) | rpl::start_with_next([=](QString id) {
_cameraInputId = id;
if (_cameraCapture) {
_cameraCapture->switchToDevice(id.toStdString());
_cameraCapture->switchToDevice(id.toStdString(), false);
}
}, _lifetime);
}
@@ -2064,7 +2065,9 @@ void GroupCall::setupOutgoingVideo() {
});
});
} else {
_cameraCapture->switchToDevice(_cameraInputId.toStdString());
_cameraCapture->switchToDevice(
_cameraInputId.toStdString(),
false);
}
if (_instance) {
_instance->setVideoCapture(_cameraCapture);
@@ -2131,7 +2134,8 @@ void GroupCall::setupOutgoingVideo() {
});
} else {
_screenCapture->switchToDevice(
_screenDeviceId.toStdString());
_screenDeviceId.toStdString(),
true);
}
if (_screenInstance) {
_screenInstance->setVideoCapture(_screenCapture);
@@ -2779,6 +2783,8 @@ void GroupCall::checkLastSpoke() {
|| muted() == MuteState::Active
|| muted() == MuteState::PushToTalk) {
real->applyLastSpoke(ssrc, when, now);
} else {
real->applyLastSpoke(ssrc, { crl::time(), crl::time() }, now);
}
}
_lastSpoke = std::move(list);

View File

@@ -246,7 +246,20 @@ private:
not_null<Row*> row,
const std::optional<Data::GroupCallParticipant> &was,
const Data::GroupCallParticipant *participant);
void updateRowInSoundingMap(
not_null<Row*> row,
bool wasSounding,
uint32 wasSsrc,
uint32 wasAdditionalSsrc,
const Data::GroupCallParticipant *participant);
void updateRowInSoundingMap(
not_null<Row*> row,
bool wasSounding,
uint32 wasSsrc,
bool nowSounding,
uint32 nowSsrc);
void removeRow(not_null<Row*> row);
void removeRowFromSoundingMap(not_null<Row*> row);
void updateRowLevel(not_null<Row*> row, float level);
void checkRowPosition(not_null<Row*> row);
[[nodiscard]] bool needToReorder(not_null<Row*> row) const;
@@ -804,14 +817,50 @@ void Members::Controller::updateRow(
: 0;
row->setSkipLevelUpdate(_skipRowLevelUpdate);
row->updateState(participant);
const auto wasNoSounding = _soundingRowBySsrc.empty();
updateRowInSoundingMap(
row,
wasSounding,
wasSsrc,
wasAdditionalSsrc,
participant);
const auto nowNoSounding = _soundingRowBySsrc.empty();
if (wasNoSounding && !nowNoSounding) {
_soundingAnimation.start();
} else if (nowNoSounding && !wasNoSounding) {
_soundingAnimation.stop();
}
delegate()->peerListUpdateRow(row);
}
void Members::Controller::updateRowInSoundingMap(
not_null<Row*> row,
bool wasSounding,
uint32 wasSsrc,
uint32 wasAdditionalSsrc,
const Data::GroupCallParticipant *participant) {
const auto nowSounding = row->sounding();
const auto nowSsrc = participant ? participant->ssrc : 0;
const auto nowAdditionalSsrc = participant
? GetAdditionalAudioSsrc(participant->videoParams)
: 0;
updateRowInSoundingMap(row, wasSounding, wasSsrc, nowSounding, nowSsrc);
updateRowInSoundingMap(
row,
wasSounding,
wasAdditionalSsrc,
nowSounding,
nowAdditionalSsrc);
}
const auto wasNoSounding = _soundingRowBySsrc.empty();
void Members::Controller::updateRowInSoundingMap(
not_null<Row*> row,
bool wasSounding,
uint32 wasSsrc,
bool nowSounding,
uint32 nowSsrc) {
if (wasSsrc == nowSsrc) {
if (nowSsrc && nowSounding != wasSounding) {
if (nowSounding) {
@@ -826,32 +875,14 @@ void Members::Controller::updateRow(
_soundingRowBySsrc.emplace(nowSsrc, row);
}
}
if (wasAdditionalSsrc == nowAdditionalSsrc) {
if (nowAdditionalSsrc && nowSounding != wasSounding) {
if (nowSounding) {
_soundingRowBySsrc.emplace(nowAdditionalSsrc, row);
} else {
_soundingRowBySsrc.remove(nowAdditionalSsrc);
}
}
} else {
_soundingRowBySsrc.remove(wasAdditionalSsrc);
if (nowSounding && nowAdditionalSsrc) {
_soundingRowBySsrc.emplace(nowAdditionalSsrc, row);
}
}
const auto nowNoSounding = _soundingRowBySsrc.empty();
if (wasNoSounding && !nowNoSounding) {
_soundingAnimation.start();
} else if (nowNoSounding && !wasNoSounding) {
_soundingAnimation.stop();
}
delegate()->peerListUpdateRow(row);
}
void Members::Controller::removeRow(not_null<Row*> row) {
removeRowFromSoundingMap(row);
delegate()->peerListRemoveRow(row);
}
void Members::Controller::removeRowFromSoundingMap(not_null<Row*> row) {
// There may be 0, 1 or 2 entries for a row.
for (auto i = begin(_soundingRowBySsrc); i != end(_soundingRowBySsrc);) {
if (i->second == row) {
@@ -860,7 +891,6 @@ void Members::Controller::removeRow(not_null<Row*> row) {
++i;
}
}
delegate()->peerListRemoveRow(row);
}
void Members::Controller::updateRowLevel(
@@ -944,18 +974,22 @@ void Members::Controller::prepareRows(not_null<Data::GroupCall*> real) {
auto changed = false;
auto count = delegate()->peerListFullRowsCount();
for (auto i = 0; i != count;) {
auto row = delegate()->peerListRowAt(i);
auto participantPeer = row->peer();
if (isMe(participantPeer)) {
const auto row = static_cast<Row*>(
delegate()->peerListRowAt(i).get());
removeRowFromSoundingMap(row);
const auto participantPeer = row->peer();
const auto me = isMe(participantPeer);
if (me) {
foundMe = true;
++i;
continue;
}
if (real->participantByPeer(participantPeer)) {
if (const auto found = real->participantByPeer(participantPeer)) {
updateRowInSoundingMap(row, false, 0, 0, found);
++i;
} else if (me) {
++i;
} else {
changed = true;
removeRow(static_cast<Row*>(row.get()));
removeRow(row);
--count;
}
}

View File

@@ -48,7 +48,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/unixtime.h"
#include "base/qt_signal_producer.h"
#include "base/timer_rpl.h"
#include "app.h"
#include "apiwrap.h" // api().kickParticipant.
#include "webrtc/webrtc_video_track.h"
#include "webrtc/webrtc_media_devices.h" // UniqueDesktopCaptureSource.
@@ -268,11 +267,16 @@ void Panel::initWindow() {
0,
widget()->width(),
st::groupCallMembersTop);
return (titleRect.contains(widgetPoint)
const auto moveable = (titleRect.contains(widgetPoint)
&& (!_menuToggle || !_menuToggle->geometry().contains(widgetPoint))
&& (!_menu || !_menu->geometry().contains(widgetPoint))
&& (!_recordingMark || !_recordingMark->geometry().contains(widgetPoint))
&& (!_joinAsToggle || !_joinAsToggle->geometry().contains(widgetPoint)))
&& (!_joinAsToggle || !_joinAsToggle->geometry().contains(widgetPoint)));
if (!moveable) {
return (Flag::None | Flag(0));
}
const auto shown = _layerBg->topShownLayer();
return (!shown || !shown->geometry().contains(widgetPoint))
? (Flag::Move | Flag::Maximize)
: Flag::None;
});

View File

@@ -33,7 +33,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "main/main_session.h"
#include "window/window_session_controller.h"
#include "history/view/history_view_cursor_state.h"
#include "app.h"
#include "storage/storage_account.h" // Account::writeSavedGifs
#include "styles/style_chat_helpers.h"

View File

@@ -11,7 +11,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "base/timer.h"
#include "inline_bots/inline_bot_layout_item.h"
#include "layout/layout_mosaic.h"
#include "app.h"
#include <QtCore/QTimer>

View File

@@ -14,6 +14,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "history/view/history_view_schedule_box.h"
#include "lang/lang_keys.h"
#include "ui/widgets/popup_menu.h"
#include "data/data_peer.h"
#include "main/main_session.h"
#include "apiwrap.h"
#include <QtWidgets/QApplication>
@@ -133,4 +136,45 @@ void SetupMenuAndShortcuts(
}, button->lifetime());
}
void SetupUnreadMentionsMenu(
not_null<Ui::RpWidget*> button,
Fn<PeerData*()> currentPeer) {
struct State {
base::unique_qptr<Ui::PopupMenu> menu;
base::flat_set<not_null<PeerData*>> sentForPeers;
};
const auto state = std::make_shared<State>();
const auto showMenu = [=] {
const auto peer = currentPeer();
if (!peer) {
return;
}
state->menu = base::make_unique_q<Ui::PopupMenu>(button);
const auto text = tr::lng_context_mark_read_mentions_all(tr::now);
state->menu->addAction(text, [=] {
if (!state->sentForPeers.emplace(peer).second) {
return;
}
peer->session().api().request(MTPmessages_ReadMentions(
peer->input
)).done([=](const MTPmessages_AffectedHistory &result) {
state->sentForPeers.remove(peer);
peer->session().api().applyAffectedHistory(peer, result);
}).fail([=](const MTP::Error &error) {
state->sentForPeers.remove(peer);
}).send();
});
state->menu->popup(QCursor::pos());
};
base::install_event_filter(button, [=](not_null<QEvent*> e) {
if (e->type() == QEvent::ContextMenu) {
showMenu();
return base::EventFilterResult::Cancel;
}
return base::EventFilterResult::Continue;
});
}
} // namespace SendMenu

View File

@@ -50,4 +50,8 @@ void SetupMenuAndShortcuts(
Fn<void()> silent,
Fn<void()> schedule);
void SetupUnreadMentionsMenu(
not_null<Ui::RpWidget*> button,
Fn<PeerData*()> currentPeer);
} // namespace SendMenu

View File

@@ -21,7 +21,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/application.h"
#include "base/call_delayed.h"
#include "apiwrap.h"
#include "app.h"
#include "styles/style_chat.h"
#include <QtCore/QBuffer>

View File

@@ -14,7 +14,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "window/window_session_controller.h"
#include "mainwindow.h"
#include "core/application.h"
#include "app.h"
#include "styles/style_chat_helpers.h"
namespace ChatHelpers {

View File

@@ -26,7 +26,7 @@ object_ptr<Window::SectionWidget> TabbedMemento::createWidget(
TabbedSection::TabbedSection(
QWidget *parent,
not_null<Window::SessionController*> controller)
: Window::SectionWidget(parent, controller)
: Window::SectionWidget(parent, controller, PaintedBackground::Custom)
, _selector(controller->tabbedSelector()) {
_selector->setParent(this);
_selector->setRoundRadius(0);

View File

@@ -7,6 +7,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "core/application.h"
#include "data/data_abstract_structure.h"
#include "data/data_photo.h"
#include "data/data_document.h"
#include "data/data_session.h"
@@ -41,6 +42,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "lang/lang_instance.h"
#include "mainwidget.h"
#include "core/file_utilities.h"
#include "core/crash_reports.h"
#include "main/main_account.h"
#include "main/main_domain.h"
#include "main/main_session.h"
@@ -64,6 +66,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "ui/text/text_options.h"
#include "ui/emoji_config.h"
#include "ui/effects/animations.h"
#include "ui/cached_round_corners.h"
#include "storage/serialize_common.h"
#include "storage/storage_domain.h"
#include "storage/storage_databases.h"
@@ -92,6 +95,27 @@ constexpr auto kQuitPreventTimeoutMs = crl::time(1500);
constexpr auto kAutoLockTimeoutLateMs = crl::time(3000);
constexpr auto kClearEmojiImageSourceTimeout = 10 * crl::time(1000);
void SetCrashAnnotationsGL() {
#ifdef Q_OS_WIN
CrashReports::SetAnnotation("OpenGL ANGLE", [] {
if (Core::App().settings().disableOpenGL()) {
return "Disabled";
} else switch (Ui::GL::CurrentANGLE()) {
case Ui::GL::ANGLE::Auto: return "Auto";
case Ui::GL::ANGLE::D3D11: return "Direct3D 11";
case Ui::GL::ANGLE::D3D9: return "Direct3D 9";
case Ui::GL::ANGLE::D3D11on12: return "D3D11on12";
case Ui::GL::ANGLE::OpenGL: return "OpenGL";
}
Unexpected("Ui::GL::CurrentANGLE value in SetupANGLE.");
}());
#else // Q_OS_WIN
CrashReports::SetAnnotation(
"OpenGL",
Core::App().settings().disableOpenGL() ? "Disabled" : "Enabled");
#endif // Q_OS_WIN
}
} // namespace
Application *Application::Instance = nullptr;
@@ -172,7 +196,8 @@ Application::~Application() {
Ui::Emoji::Clear();
Media::Clip::Finish();
App::deinitMedia();
Ui::FinishCachedCorners();
Data::clearGlobalStructures();
Window::Theme::Uninitialize();
@@ -217,6 +242,7 @@ void Application::run() {
style::startManager(cScale());
Ui::InitTextOptions();
Ui::StartCachedCorners();
Ui::Emoji::Init();
startEmojiImageLoader();
startSystemDarkModeViewer();
@@ -262,7 +288,6 @@ void Application::run() {
// Depend on activeWindow() for now :(
startShortcuts();
App::initMedia();
startDomain();
_window->widget()->show();
@@ -284,6 +309,7 @@ void Application::run() {
LOG(("Shortcuts Error: %1").arg(error));
}
SetCrashAnnotationsGL();
if (!Platform::IsMac() && Ui::GL::LastCrashCheckFailed()) {
showOpenGLCrashNotification();
}

View File

@@ -88,6 +88,21 @@ std::map<int, const char*> BetaLogs() {
"- Fix Direct3D acceleration on basic Windows 7 setup.\n"
},
{
2009004,
"- Choose one from dozens of new gorgeous animated backgrounds"
" in Chat Settings > Chat background.\n"
},
{
2009005,
"- Tile chat background patterns horizontally.\n"
"- Fix a rare crash in spellchecker on Windows.\n"
"- Fix animated chat backgrounds in Saved Messages.\n"
"- Fix \"Sorry, group is inaccessible\" message in scheduled voice chats.\n",
},
};
};

View File

@@ -23,7 +23,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_session.h"
#include "window/window_session_controller.h"
#include "facades.h"
#include "app.h"
#include <QtGui/QGuiApplication>

View File

@@ -299,10 +299,8 @@ QString PlatformString() {
return qsl("MacAppStore");
} else if (Platform::IsMac()) {
return qsl("MacOS");
} else if (Platform::IsLinux32Bit()) {
return qsl("Linux32Bit");
} else if (Platform::IsLinux64Bit()) {
return qsl("Linux64bit");
} else if (Platform::IsLinux()) {
return qsl("Linux");
}
Unexpected("Platform in CrashReports::PlatformString.");
}

View File

@@ -286,10 +286,7 @@ void Launcher::init() {
initQtMessageLogging();
QApplication::setApplicationName(qsl("TelegramDesktop"));
#ifndef OS_MAC_OLD
QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true);
#endif // OS_MAC_OLD
// fallback session management is useless for tdesktop since it doesn't have
// any "are you sure you want to close this window?" dialogs
@@ -427,9 +424,17 @@ void Launcher::initQtMessageLogging() {
QtMsgType type,
const QMessageLogContext &context,
const QString &msg) {
if (OriginalMessageHandler) {
OriginalMessageHandler(type, context, msg);
}
const auto InvokeOriginal = [&] {
#ifndef _DEBUG
if (Logs::DebugEnabled()) {
return;
}
#endif // _DEBUG
if (OriginalMessageHandler) {
OriginalMessageHandler(type, context, msg);
}
};
InvokeOriginal();
if (Logs::DebugEnabled() || !Logs::started()) {
if (!Logs::WritingEntry()) {
// Sometimes Qt logs something inside our own logging.
@@ -450,7 +455,6 @@ void Launcher::processArguments() {
AllLeftValues,
};
auto parseMap = std::map<QByteArray, KeyFormat> {
{ "-testmode" , KeyFormat::NoValues },
{ "-debug" , KeyFormat::NoValues },
{ "-freetype" , KeyFormat::NoValues },
{ "-many" , KeyFormat::NoValues },
@@ -459,7 +463,6 @@ void Launcher::processArguments() {
{ "-fixprevious" , KeyFormat::NoValues },
{ "-cleanup" , KeyFormat::NoValues },
{ "-noupdate" , KeyFormat::NoValues },
{ "-externalupdater", KeyFormat::NoValues },
{ "-tosettings" , KeyFormat::NoValues },
{ "-startintray" , KeyFormat::NoValues },
{ "-sendpath" , KeyFormat::AllLeftValues },
@@ -490,9 +493,6 @@ void Launcher::processArguments() {
}
}
if (parseResult.contains("-externalupdater")) {
SetUpdaterDisabledAtStartup();
}
gUseFreeType = parseResult.contains("-freetype");
gDebugMode = parseResult.contains("-debug");
gManyInstance = parseResult.contains("-many");

View File

@@ -40,7 +40,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "main/main_session.h"
#include "main/main_session_settings.h"
#include "apiwrap.h"
#include "app.h"
#include <QtGui/QGuiApplication>
@@ -232,15 +231,16 @@ bool ShowWallPaper(
const auto params = url_parse_params(
match->captured(1),
qthelp::UrlParamNameTransform::ToLower);
if (!params.value("gradient").isEmpty()) {
Ui::show(Box<InformBox>(
tr::lng_background_gradient_unsupported(tr::now)));
return false;
}
const auto bg = params.value("bg_color");
const auto color = params.value("color");
const auto gradient = params.value("gradient");
return BackgroundPreviewBox::Start(
controller,
(color.isEmpty() ? params.value(qsl("slug")) : color),
(!color.isEmpty()
? color
: !gradient.isEmpty()
? gradient
: params.value(qsl("slug"))),
params);
}

View File

@@ -21,6 +21,7 @@ QStringList MimeType::globPatterns() const {
switch (_type) {
case Known::WebP: return QStringList(u"*.webp"_q);
case Known::Tgs: return QStringList(u"*.tgs"_q);
case Known::Tgv: return QStringList(u"*.tgv"_q);
case Known::TDesktopTheme: return QStringList(u"*.tdesktop-theme"_q);
case Known::TDesktopPalette: return QStringList(u"*.tdesktop-palette"_q);
default: break;
@@ -32,6 +33,7 @@ QString MimeType::filterString() const {
switch (_type) {
case Known::WebP: return u"WebP image (*.webp)"_q;
case Known::Tgs: return u"Telegram sticker (*.tgs)"_q;
case Known::Tgv: return u"Wallpaper pattern (*.tgv)"_q;
case Known::TDesktopTheme: return u"Theme files (*.tdesktop-theme)"_q;
case Known::TDesktopPalette: return u"Palette files (*.tdesktop-palette)"_q;
default: break;
@@ -43,6 +45,7 @@ QString MimeType::name() const {
switch (_type) {
case Known::WebP: return u"image/webp"_q;
case Known::Tgs: return u"application/x-tgsticker"_q;
case Known::Tgv: return u"application/x-tgwallpattern"_q;
case Known::TDesktopTheme: return u"application/x-tdesktop-theme"_q;
case Known::TDesktopPalette: return u"application/x-tdesktop-palette"_q;
default: break;
@@ -55,6 +58,8 @@ MimeType MimeTypeForName(const QString &mime) {
return MimeType(MimeType::Known::WebP);
} else if (mime == qstr("application/x-tgsticker")) {
return MimeType(MimeType::Known::Tgs);
} else if (mime == qstr("application/x-tgwallpattern")) {
return MimeType(MimeType::Known::Tgv);
} else if (mime == qstr("application/x-tdesktop-theme")
|| mime == qstr("application/x-tgtheme-tdesktop")) {
return MimeType(MimeType::Known::TDesktopTheme);
@@ -72,6 +77,8 @@ MimeType MimeTypeForFile(const QFileInfo &file) {
return MimeType(MimeType::Known::WebP);
} else if (path.endsWith(qstr(".tgs"), Qt::CaseInsensitive)) {
return MimeType(MimeType::Known::Tgs);
} else if (path.endsWith(qstr(".tgv"))) {
return MimeType(MimeType::Known::Tgv);
} else if (path.endsWith(qstr(".tdesktop-theme"), Qt::CaseInsensitive)) {
return MimeType(MimeType::Known::TDesktopTheme);
} else if (path.endsWith(qstr(".tdesktop-palette"), Qt::CaseInsensitive)) {

View File

@@ -22,6 +22,7 @@ public:
TDesktopPalette,
WebP,
Tgs,
Tgv,
};
explicit MimeType(const QMimeType &type);

View File

@@ -242,9 +242,7 @@ QString FindUpdateFile() {
"tupdate|"
"tx64upd|"
"tmacupd|"
"tosxupd|"
"tlinuxupd|"
"tlinux32upd"
")\\d+(_[a-z\\d]+)?$",
QRegularExpression::CaseInsensitiveOption
).match(info.fileName()).hasMatch()) {

View File

@@ -22,7 +22,7 @@ constexpr auto AppId = "{53F49750-6209-4FBF-9CA8-7A333C87D1ED}"_cs;
constexpr auto AppNameOld = "Telegram Win (Unofficial)"_cs;
constexpr auto AppName = "Telegram Desktop"_cs;
constexpr auto AppFile = "Telegram"_cs;
constexpr auto AppVersion = 2009000;
constexpr auto AppVersionStr = "2.9";
constexpr auto AppBetaVersion = false;
constexpr auto AppVersion = 2009008;
constexpr auto AppVersionStr = "2.9.8";
constexpr auto AppBetaVersion = true;
constexpr auto AppAlphaVersion = TDESKTOP_ALPHA_VERSION;

View File

@@ -45,7 +45,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "mainwindow.h"
#include "core/application.h"
#include "lottie/lottie_animation.h"
#include "app.h"
#include <QtCore/QBuffer>
#include <QtCore/QMimeType>
@@ -412,7 +411,7 @@ void DocumentData::setattributes(
void DocumentData::validateLottieSticker() {
if (type == FileDocument
&& _mimeString == qstr("application/x-tgsticker")) {
&& hasMimeType(qstr("application/x-tgsticker"))) {
type = StickerDocument;
_additional = std::make_unique<StickerData>();
sticker()->animated = true;
@@ -443,9 +442,8 @@ bool DocumentData::checkWallPaperProperties() {
|| !dimensions.height()
|| dimensions.width() > Storage::kMaxWallPaperDimension
|| dimensions.height() > Storage::kMaxWallPaperDimension
|| size > Storage::kMaxWallPaperInMemory
|| mimeString() == qstr("application/x-tgwallpattern")) {
return false; // #TODO themes support svg patterns
|| size > Storage::kMaxWallPaperInMemory) {
return false;
}
type = WallPaperDocument;
return true;
@@ -488,9 +486,18 @@ bool DocumentData::isWallPaper() const {
}
bool DocumentData::isPatternWallPaper() const {
return isWallPaper()
&& (isPatternWallPaperPNG() || isPatternWallPaperSVG());
}
bool DocumentData::isPatternWallPaperPNG() const {
return isWallPaper() && hasMimeType(qstr("image/png"));
}
bool DocumentData::isPatternWallPaperSVG() const {
return isWallPaper() && hasMimeType(qstr("application/x-tgwallpattern"));
}
bool DocumentData::hasThumbnail() const {
return _thumbnail.location.valid();
}
@@ -662,9 +669,9 @@ bool DocumentData::saveToCache() const {
&& ((type == StickerDocument)
|| isAnimation()
|| isVoiceMessage()
|| (type == WallPaperDocument)
|| isWallPaper()
|| isTheme()
|| (mimeString() == qstr("image/png")
|| (hasMimeType(qstr("image/png"))
&& _filename.startsWith("image_")));
}
@@ -1234,11 +1241,12 @@ QString DocumentData::mimeString() const {
}
bool DocumentData::hasMimeType(QLatin1String mime) const {
return !_mimeString.compare(mime, Qt::CaseInsensitive);
return (_mimeString == mime);
}
void DocumentData::setMimeString(const QString &mime) {
_mimeString = mime;
_mimeString = std::move(_mimeString).toLower();
}
MediaKey DocumentData::mediaKey() const {
@@ -1264,7 +1272,7 @@ uint8 DocumentData::cacheTag() const {
return Data::kVideoMessageCacheTag;
} else if (isAnimation()) {
return Data::kAnimationCacheTag;
} else if (type == WallPaperDocument) {
} else if (isWallPaper()) {
return Data::kImageCacheTag;
}
return 0;
@@ -1299,14 +1307,9 @@ bool DocumentData::isGifv() const {
}
bool DocumentData::isTheme() const {
return
_mimeString == qstr("application/x-tgtheme-tdesktop")
|| _filename.endsWith(
qstr(".tdesktop-theme"),
Qt::CaseInsensitive)
|| _filename.endsWith(
qstr(".tdesktop-palette"),
Qt::CaseInsensitive);
return hasMimeType(qstr("application/x-tgtheme-tdesktop"))
|| _filename.endsWith(qstr(".tdesktop-theme"), Qt::CaseInsensitive)
|| _filename.endsWith(qstr(".tdesktop-palette"), Qt::CaseInsensitive);
}
bool DocumentData::isSong() const {

View File

@@ -155,6 +155,8 @@ public:
bool checkWallPaperProperties();
[[nodiscard]] bool isWallPaper() const;
[[nodiscard]] bool isPatternWallPaper() const;
[[nodiscard]] bool isPatternWallPaperPNG() const;
[[nodiscard]] bool isPatternWallPaperSVG() const;
[[nodiscard]] bool hasThumbnail() const;
[[nodiscard]] bool thumbnailLoading() const;

View File

@@ -24,7 +24,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "core/application.h"
#include "storage/file_download.h"
#include "ui/image/image.h"
#include "app.h"
#include <QtCore/QBuffer>
#include <QtGui/QImageReader>
@@ -40,6 +39,8 @@ enum class FileType {
Video,
AnimatedSticker,
WallPaper,
WallPatternPNG,
WallPatternSVG,
Theme,
};
@@ -61,6 +62,15 @@ enum class FileType {
return Lottie::ReadThumbnail(Lottie::ReadContent(data, path));
} else if (type == FileType::Theme) {
return Window::Theme::GeneratePreview(data, path);
} else if (type == FileType::WallPatternSVG) {
return Images::Read({
.path = path,
.content = std::move(data),
.maxSize = QSize(
kWallPaperThumbnailLimit,
kWallPaperThumbnailLimit),
.gzipSvg = true,
}).image;
}
auto buffer = QBuffer(&data);
auto file = QFile(path);
@@ -391,7 +401,11 @@ void DocumentMedia::checkStickerLarge(not_null<FileLoader*> loader) {
void DocumentMedia::GenerateGoodThumbnail(
not_null<DocumentData*> document,
QByteArray data) {
const auto type = document->isWallPaper()
const auto type = document->isPatternWallPaperSVG()
? FileType::WallPatternSVG
: document->isPatternWallPaperPNG()
? FileType::WallPatternPNG
: document->isWallPaper()
? FileType::WallPaper
: document->isTheme()
? FileType::Theme
@@ -416,7 +430,8 @@ void DocumentMedia::GenerateGoodThumbnail(
auto buffer = QBuffer(&bytes);
const auto format = (type == FileType::AnimatedSticker)
? "WEBP"
: (type == FileType::WallPaper && result.hasAlphaChannel())
: (type == FileType::WallPatternPNG
|| type == FileType::WallPatternSVG)
? "PNG"
: "JPG";
result.save(&buffer, format, kGoodThumbQuality);
@@ -464,11 +479,11 @@ void DocumentMedia::ReadOrGenerateThumbnail(
});
} else if (active) {
crl::async([=] {
const auto image = App::readImage(value, nullptr, false);
crl::on_main(guard, [=] {
auto image = Images::Read({ .content = value }).image;
crl::on_main(guard, [=, image = std::move(image)]() mutable {
document->setGoodThumbnailChecked(true);
if (const auto active = document->activeMediaView()) {
active->setGoodThumbnail(image);
active->setGoodThumbnail(std::move(image));
}
});
});

View File

@@ -7,7 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "data/data_document_resolver.h"
#include "app.h"
#include "facades.h"
#include "base/platform/base_platform_info.h"
#include "boxes/confirm_box.h"
@@ -34,6 +33,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
namespace Data {
namespace {
constexpr auto kMaxWallpaperSize = 3072;
void LaunchWithWarning(
// not_null<Window::Controller*> controller,
const QString &name,
@@ -174,29 +175,33 @@ bool IsIpRevealingName(const QString &filepath) {
);
}
[[nodiscard]] QImage ReadImage(
const QString &path,
const QByteArray &content,
bool gzipSvg) {
return Images::Read({
.path = path,
.content = content,
.maxSize = QSize(kMaxWallpaperSize, kMaxWallpaperSize),
.gzipSvg = gzipSvg,
}).image;
}
base::binary_guard ReadImageAsync(
not_null<Data::DocumentMedia*> media,
FnMut<QImage(QImage)> postprocess,
FnMut<void(QImage&&)> done) {
auto result = base::binary_guard();
const auto gzipSvg = media->owner()->isPatternWallPaperSVG();
crl::async([
gzipSvg,
bytes = media->bytes(),
path = media->owner()->filepath(),
postprocess = std::move(postprocess),
guard = result.make_guard(),
callback = std::move(done)
]() mutable {
auto format = QByteArray();
if (bytes.isEmpty()) {
QFile f(path);
if (f.size() <= App::kImageSizeLimit
&& f.open(QIODevice::ReadOnly)) {
bytes = f.readAll();
}
}
auto image = bytes.isEmpty()
? QImage()
: App::readImage(bytes, &format, false, nullptr);
auto image = ReadImage(path, bytes, gzipSvg);
if (postprocess) {
image = postprocess(std::move(image));
}
@@ -231,7 +236,7 @@ void ResolveDocument(
const auto media = document->createMediaView();
const auto openImageInApp = [&] {
if (document->size >= App::kImageSizeLimit) {
if (document->size >= Images::kReadBytesLimit) {
return false;
}
const auto &location = document->location(true);

View File

@@ -244,6 +244,14 @@ bool Media::forwardedBecomesUnread() const {
return false;
}
bool Media::dropForwardedInfo() const {
return false;
}
bool Media::forceForwardedInfo() const {
return false;
}
QString Media::errorTextForForward(not_null<PeerData*> peer) const {
return QString();
}
@@ -625,6 +633,10 @@ bool MediaFile::forwardedBecomesUnread() const {
|| _document->isVideoMessage();
}
bool MediaFile::dropForwardedInfo() const {
return _document->isSong();
}
QString MediaFile::errorTextForForward(not_null<PeerData*> peer) const {
if (const auto sticker = _document->sticker()) {
if (const auto error = Data::RestrictionError(
@@ -1007,7 +1019,8 @@ WebPageData *MediaWebPage::webpage() const {
bool MediaWebPage::hasReplyPreview() const {
if (const auto document = MediaWebPage::document()) {
return document->hasThumbnail() && !document->isPatternWallPaper();
return document->hasThumbnail()
&& !document->isPatternWallPaper();
} else if (const auto photo = MediaWebPage::photo()) {
return !photo->isNull();
}
@@ -1139,6 +1152,10 @@ QString MediaGame::errorTextForForward(not_null<PeerData*> peer) const {
).value_or(QString());
}
bool MediaGame::dropForwardedInfo() const {
return true;
}
bool MediaGame::consumeMessageText(const TextWithEntities &text) {
_consumedText = text;
return true;
@@ -1346,6 +1363,10 @@ TextForMimeData MediaDice::clipboardText() const {
return { notificationText() };
}
bool MediaDice::forceForwardedInfo() const {
return true;
}
bool MediaDice::updateInlineResultMedia(const MTPMessageMedia &media) {
return updateSentMedia(media);
}

View File

@@ -102,6 +102,8 @@ public:
virtual bool allowsEditMedia() const;
virtual bool allowsRevoke(TimeId now) const;
virtual bool forwardedBecomesUnread() const;
virtual bool dropForwardedInfo() const;
virtual bool forceForwardedInfo() const;
virtual QString errorTextForForward(not_null<PeerData*> peer) const;
[[nodiscard]] virtual bool consumeMessageText(
@@ -191,6 +193,7 @@ public:
bool allowsEditCaption() const override;
bool allowsEditMedia() const override;
bool forwardedBecomesUnread() const override;
bool dropForwardedInfo() const override;
QString errorTextForForward(not_null<PeerData*> peer) const override;
bool updateInlineResultMedia(const MTPMessageMedia &media) override;
@@ -352,6 +355,7 @@ public:
QString pinnedTextSubstring() const override;
TextForMimeData clipboardText() const override;
QString errorTextForForward(not_null<PeerData*> peer) const override;
bool dropForwardedInfo() const override;
bool consumeMessageText(const TextWithEntities &text) override;
TextWithEntities consumedMessageText() const override;
@@ -442,6 +446,8 @@ public:
QString notificationText() const override;
QString pinnedTextSubstring() const override;
TextForMimeData clipboardText() const override;
bool forceForwardedInfo() const override;
bool updateInlineResultMedia(const MTPMessageMedia &media) override;
bool updateSentMedia(const MTPMessageMedia &media) override;
std::unique_ptr<HistoryView::Media> createView(

View File

@@ -19,7 +19,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "storage/file_download.h"
#include "core/application.h"
#include "facades.h"
#include "app.h"
namespace {

View File

@@ -32,15 +32,21 @@ constexpr auto kLegacy2DefaultBackground = 5947530738516623361;
constexpr auto kDefaultBackground = 5778236420632084488;
constexpr auto kIncorrectDefaultBackground = FromLegacyBackgroundId(105);
quint32 SerializeMaybeColor(std::optional<QColor> color) {
return color
? ((quint32(std::clamp(color->red(), 0, 255)) << 16)
| (quint32(std::clamp(color->green(), 0, 255)) << 8)
| quint32(std::clamp(color->blue(), 0, 255)))
: quint32(-1);
constexpr auto kVersionTag = qint32(0x7FFFFFFF);
constexpr auto kVersion = 1;
[[nodiscard]] quint32 SerializeColor(const QColor &color) {
return (quint32(std::clamp(color.red(), 0, 255)) << 16)
| (quint32(std::clamp(color.green(), 0, 255)) << 8)
| quint32(std::clamp(color.blue(), 0, 255));
}
std::optional<QColor> MaybeColorFromSerialized(quint32 serialized) {
[[nodiscard]] quint32 SerializeMaybeColor(std::optional<QColor> color) {
return color ? SerializeColor(*color) : quint32(-1);
}
[[nodiscard]] std::optional<QColor> MaybeColorFromSerialized(
quint32 serialized) {
return (serialized == quint32(-1))
? std::nullopt
: std::make_optional(QColor(
@@ -49,7 +55,43 @@ std::optional<QColor> MaybeColorFromSerialized(quint32 serialized) {
int(serialized & 0xFFU)));
}
std::optional<QColor> ColorFromString(const QString &string) {
[[nodiscard]] QColor DefaultBackgroundColor() {
return QColor(213, 223, 233);
}
[[nodiscard]] std::optional<QColor> MaybeColorFromSerialized(
const tl::conditional<MTPint> &mtp) {
return mtp ? MaybeColorFromSerialized(mtp->v) : std::nullopt;
}
[[nodiscard]] std::vector<QColor> ColorsFromMTP(
const MTPDwallPaperSettings &data) {
auto result = std::vector<QColor>();
const auto c1 = MaybeColorFromSerialized(data.vbackground_color());
if (!c1) {
return result;
}
result.reserve(4);
result.push_back(*c1);
const auto c2 = MaybeColorFromSerialized(data.vsecond_background_color());
if (!c2) {
return result;
}
result.push_back(*c2);
const auto c3 = MaybeColorFromSerialized(data.vthird_background_color());
if (!c3) {
return result;
}
result.push_back(*c3);
const auto c4 = MaybeColorFromSerialized(data.vfourth_background_color());
if (!c4) {
return result;
}
result.push_back(*c4);
return result;
}
[[nodiscard]] std::optional<QColor> ColorFromString(QStringView string) {
if (string.size() != 6) {
return {};
} else if (ranges::any_of(string, [](QChar ch) {
@@ -59,7 +101,7 @@ std::optional<QColor> ColorFromString(const QString &string) {
})) {
return {};
}
const auto component = [](const QString &text, int index) {
const auto component = [](QStringView text, int index) {
const auto decimal = [](QChar hex) {
const auto code = hex.unicode();
return (code >= '0' && code <= '9')
@@ -78,7 +120,30 @@ std::optional<QColor> ColorFromString(const QString &string) {
255);
}
QString StringFromColor(QColor color) {
[[nodiscard]] std::vector<QColor> ColorsFromString(const QString &string) {
constexpr auto kMaxColors = 4;
const auto view = QStringView(string);
const auto count = int(view.size() / 6);
if (!count || count > kMaxColors || view.size() != count * 7 - 1) {
return {};
}
auto result = std::vector<QColor>();
result.reserve(count);
for (auto i = 0; i != count; ++i) {
if (i + 1 < count
&& view[i * 7 + 6] != '~'
&& (count > 2 || view[i * 7 + 6] != '-')) {
return {};
} else if (const auto parsed = ColorFromString(view.mid(i * 7, 6))) {
result.push_back(*parsed);
} else {
return {};
}
}
return result;
}
[[nodiscard]] QString StringFromColor(QColor color) {
const auto component = [](int value) {
const auto hex = [](int value) {
value = std::clamp(value, 0, 15);
@@ -93,6 +158,26 @@ QString StringFromColor(QColor color) {
+ component(color.blue());
}
[[nodiscard]] QString StringFromColors(const std::vector<QColor> &colors) {
Expects(!colors.empty());
auto strings = QStringList();
strings.reserve(colors.size());
for (const auto &color : colors) {
strings.push_back(StringFromColor(color));
}
const auto separator = (colors.size() > 2) ? '~' : '-';
return strings.join(separator);
}
[[nodiscard]] qint32 RawFromLegacyFlags(qint32 legacyFlags) {
using Flag = WallPaperFlag;
return ((legacyFlags & (1 << 0)) ? qint32(Flag::Creator) : 0)
| ((legacyFlags & (1 << 1)) ? qint32(Flag::Default) : 0)
| ((legacyFlags & (1 << 3)) ? qint32(Flag::Pattern) : 0)
| ((legacyFlags & (1 << 4)) ? qint32(Flag::Dark) : 0);
}
} // namespace
WallPaper::WallPaper(WallPaperId id) : _id(id) {
@@ -112,7 +197,13 @@ WallPaperId WallPaper::id() const {
}
std::optional<QColor> WallPaper::backgroundColor() const {
return _backgroundColor;
return _backgroundColors.empty()
? std::nullopt
: std::make_optional(_backgroundColors.front());
}
const std::vector<QColor> WallPaper::backgroundColors() const {
return _backgroundColors;
}
DocumentData *WallPaper::document() const {
@@ -124,19 +215,19 @@ Image *WallPaper::localThumbnail() const {
}
bool WallPaper::isPattern() const {
return _flags & MTPDwallPaper::Flag::f_pattern;
return _flags & WallPaperFlag::Pattern;
}
bool WallPaper::isDefault() const {
return _flags & MTPDwallPaper::Flag::f_default;
return _flags & WallPaperFlag::Default;
}
bool WallPaper::isCreator() const {
return _flags & MTPDwallPaper::Flag::f_creator;
return _flags & WallPaperFlag::Creator;
}
bool WallPaper::isDark() const {
return _flags & MTPDwallPaper::Flag::f_dark;
return _flags & WallPaperFlag::Dark;
}
bool WallPaper::isLocal() const {
@@ -144,13 +235,22 @@ bool WallPaper::isLocal() const {
}
bool WallPaper::isBlurred() const {
return _settings & MTPDwallPaperSettings::Flag::f_blur;
return _blurred;
}
int WallPaper::patternIntensity() const {
return _intensity;
}
float64 WallPaper::patternOpacity() const {
return _intensity / 100.;
}
int WallPaper::gradientRotation() const {
// In case of complex gradients rotation value is dynamic.
return (_backgroundColors.size() < 3) ? _rotation : 0;
}
bool WallPaper::hasShareUrl() const {
return !_slug.isEmpty();
}
@@ -162,19 +262,20 @@ QString WallPaper::shareUrl(not_null<Main::Session*> session) const {
const auto base = session->createInternalLinkFull("bg/" + _slug);
auto params = QStringList();
if (isPattern()) {
if (_backgroundColor) {
params.push_back("bg_color=" + StringFromColor(*_backgroundColor));
if (!backgroundColors().empty()) {
params.push_back(
"bg_color=" + StringFromColors(backgroundColors()));
}
if (_intensity) {
params.push_back("intensity=" + QString::number(_intensity));
}
}
auto mode = QStringList();
if (_settings & MTPDwallPaperSettings::Flag::f_blur) {
mode.push_back("blur");
if (_rotation && backgroundColors().size() == 2) {
params.push_back("rotation=" + QString::number(_rotation));
}
if (_settings & MTPDwallPaperSettings::Flag::f_motion) {
mode.push_back("motion");
auto mode = QStringList();
if (_blurred) {
mode.push_back("blur");
}
if (!mode.isEmpty()) {
params.push_back("mode=" + mode.join('+'));
@@ -211,94 +312,110 @@ MTPInputWallPaper WallPaper::mtpInput(not_null<Main::Session*> session) const {
}
MTPWallPaperSettings WallPaper::mtpSettings() const {
const auto serializeForIndex = [&](int index) {
return (_backgroundColors.size() > index)
? MTP_int(SerializeColor(_backgroundColors[index]))
: MTP_int(0);
};
using Flag = MTPDwallPaperSettings::Flag;
const auto flagForIndex = [&](int index) {
return (_backgroundColors.size() <= index)
? Flag(0)
: (index == 0)
? Flag::f_background_color
: (index == 1)
? Flag::f_second_background_color
: (index == 2)
? Flag::f_third_background_color
: Flag::f_fourth_background_color;
};
return MTP_wallPaperSettings(
MTP_flags(_settings),
(_backgroundColor
? MTP_int(SerializeMaybeColor(_backgroundColor))
: MTP_int(0)),
MTP_int(0), // second_background_color
MTP_int(0), // third_background_color
MTP_int(0), // fourth_background_color
MTP_flags((_blurred ? Flag::f_blur : Flag(0))
| flagForIndex(0)
| flagForIndex(1)
| flagForIndex(2)
| flagForIndex(3)),
serializeForIndex(0),
serializeForIndex(1),
serializeForIndex(2),
serializeForIndex(3),
MTP_int(_intensity),
MTP_int(0) // rotation
);
MTP_int(_rotation));
}
WallPaper WallPaper::withUrlParams(
const QMap<QString, QString> &params) const {
using Flag = MTPDwallPaperSettings::Flag;
auto result = *this;
result._settings = Flag(0);
result._backgroundColor = ColorFromString(_slug);
result._blurred = false;
result._backgroundColors = ColorsFromString(_slug);
result._intensity = kDefaultIntensity;
if (auto mode = params.value("mode"); !mode.isEmpty()) {
const auto list = mode.replace('+', ' ').split(' ');
for (const auto &change : list) {
if (change == qstr("blur")) {
result._settings |= Flag::f_blur;
} else if (change == qstr("motion")) {
result._settings |= Flag::f_motion;
result._blurred = true;
}
}
}
if (const auto color = ColorFromString(params.value("bg_color"))) {
result._settings |= Flag::f_background_color;
result._backgroundColor = color;
if (result._backgroundColors.empty()) {
result._backgroundColors = ColorsFromString(params.value("bg_color"));
}
if (result._backgroundColors.empty()) {
result._backgroundColors = ColorsFromString(params.value("gradient"));
}
if (result._backgroundColors.empty()) {
result._backgroundColors = ColorsFromString(params.value("color"));
}
if (result._backgroundColors.empty()) {
result._backgroundColors = ColorsFromString(params.value("slug"));
}
if (const auto string = params.value("intensity"); !string.isEmpty()) {
auto ok = false;
const auto intensity = string.toInt(&ok);
if (ok && base::in_range(intensity, 0, 101)) {
result._settings |= Flag::f_intensity;
if (ok && base::in_range(intensity, -100, 101)) {
result._intensity = intensity;
}
}
result._rotation = params.value("rotation").toInt();
result._rotation = (std::clamp(result._rotation, 0, 315) / 45) * 45;
return result;
}
WallPaper WallPaper::withBlurred(bool blurred) const {
using Flag = MTPDwallPaperSettings::Flag;
auto result = *this;
if (blurred) {
result._settings |= Flag::f_blur;
} else {
result._settings &= ~Flag::f_blur;
}
result._blurred = blurred;
return result;
}
WallPaper WallPaper::withPatternIntensity(int intensity) const {
using Flag = MTPDwallPaperSettings::Flag;
auto result = *this;
result._settings |= Flag::f_intensity;
result._intensity = intensity;
return result;
}
WallPaper WallPaper::withBackgroundColor(QColor color) const {
using Flag = MTPDwallPaperSettings::Flag;
WallPaper WallPaper::withGradientRotation(int rotation) const {
auto result = *this;
result._settings |= Flag::f_background_color;
result._backgroundColor = color;
if (ColorFromString(_slug)) {
result._slug = StringFromColor(color);
result._rotation = rotation;
return result;
}
WallPaper WallPaper::withBackgroundColors(std::vector<QColor> colors) const {
auto result = *this;
result._backgroundColors = std::move(colors);
if (!ColorsFromString(_slug).empty()) {
result._slug = StringFromColors(result._backgroundColors);
}
return result;
}
WallPaper WallPaper::withParamsFrom(const WallPaper &other) const {
auto result = *this;
result._settings = other._settings;
if (other._backgroundColor || !ColorFromString(_slug)) {
result._backgroundColor = other._backgroundColor;
if (ColorFromString(_slug)) {
result._slug = StringFromColor(*result._backgroundColor);
result._blurred = other._blurred;
if (!other._backgroundColors.empty() || ColorsFromString(_slug).empty()) {
result._backgroundColors = other._backgroundColors;
if (!ColorsFromString(_slug).empty()) {
result._slug = StringFromColors(result._backgroundColors);
}
}
result._intensity = other._intensity;
@@ -317,15 +434,13 @@ std::optional<WallPaper> WallPaper::Create(
return data.match([&](const MTPDwallPaper &data) {
return Create(session, data);
}, [](const MTPDwallPaperNoFile &data) {
return std::optional<WallPaper>(); // #TODO themes
return Create(data);
});
}
std::optional<WallPaper> WallPaper::Create(
not_null<Main::Session*> session,
const MTPDwallPaper &data) {
using Flag = MTPDwallPaper::Flag;
const auto document = session->data().processDocument(
data.vdocument());
if (!document->checkWallPaperProperties()) {
@@ -334,27 +449,41 @@ std::optional<WallPaper> WallPaper::Create(
auto result = WallPaper(data.vid().v);
result._accessHash = data.vaccess_hash().v;
result._ownerId = session->userId();
result._flags = data.vflags().v;
result._flags = (data.is_dark() ? WallPaperFlag::Dark : WallPaperFlag(0))
| (data.is_pattern() ? WallPaperFlag::Pattern : WallPaperFlag(0))
| (data.is_default() ? WallPaperFlag::Default : WallPaperFlag(0))
| (data.is_creator() ? WallPaperFlag::Creator : WallPaperFlag(0));
result._slug = qs(data.vslug());
result._document = document;
if (const auto settings = data.vsettings()) {
const auto isPattern = ((result._flags & Flag::f_pattern) != 0);
settings->match([&](const MTPDwallPaperSettings &data) {
using Flag = MTPDwallPaperSettings::Flag;
result._settings = data.vflags().v;
const auto backgroundColor = data.vbackground_color();
if (isPattern && backgroundColor) {
result._backgroundColor = MaybeColorFromSerialized(
backgroundColor->v);
} else {
result._settings &= ~Flag::f_background_color;
result._blurred = data.is_blur();
if (result.isPattern()) {
result._backgroundColors = ColorsFromMTP(data);
if (const auto intensity = data.vintensity()) {
result._intensity = intensity->v;
}
if (const auto rotation = data.vrotation()) {
result._rotation = rotation->v;
}
}
const auto intensity = data.vintensity();
if (isPattern && intensity) {
result._intensity = intensity->v;
} else {
result._settings &= ~Flag::f_intensity;
});
}
return result;
}
std::optional<WallPaper> WallPaper::Create(const MTPDwallPaperNoFile &data) {
auto result = WallPaper(data.vid().v);
result._flags = (data.is_dark() ? WallPaperFlag::Dark : WallPaperFlag(0))
| (data.is_default() ? WallPaperFlag::Default : WallPaperFlag(0));
result._blurred = false;
result._backgroundColors.clear();
if (const auto settings = data.vsettings()) {
settings->match([&](const MTPDwallPaperSettings &data) {
result._blurred = data.is_blur();
result._backgroundColors = ColorsFromMTP(data);
if (const auto rotation = data.vrotation()) {
result._rotation = rotation->v;
}
});
}
@@ -364,30 +493,38 @@ std::optional<WallPaper> WallPaper::Create(
QByteArray WallPaper::serialize() const {
auto size = sizeof(quint64) // _id
+ sizeof(quint64) // _accessHash
+ sizeof(qint32) // version tag
+ sizeof(qint32) // version
+ sizeof(qint32) // _flags
+ Serialize::stringSize(_slug)
+ sizeof(qint32) // _settings
+ sizeof(quint32) // _backgroundColor
+ sizeof(qint32) // _backgroundColors.size()
+ (_backgroundColors.size() * sizeof(quint32)) // _backgroundColors
+ sizeof(qint32) // _intensity
+ (2 * sizeof(qint32)); // ownerId
+ sizeof(qint32) // _rotation
+ sizeof(quint64); // ownerId
auto result = QByteArray();
result.reserve(size);
{
const auto field1 = qint32(uint32(_ownerId.bare & 0xFFFFFFFF));
const auto field2 = qint32(uint32(_ownerId.bare >> 32));
auto stream = QDataStream(&result, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_5_1);
stream
<< quint64(_id)
<< quint64(_accessHash)
<< qint32(kVersionTag)
<< qint32(kVersion)
<< qint32(_flags)
<< _slug
<< qint32(_settings)
<< SerializeMaybeColor(_backgroundColor)
<< qint32(_blurred ? 1 : 0)
<< qint32(_backgroundColors.size());
for (const auto &color : _backgroundColors) {
stream << SerializeMaybeColor(color);
}
stream
<< qint32(_intensity)
<< field1
<< field2;
<< qint32(_rotation)
<< quint64(_ownerId.bare);
}
return result;
}
@@ -400,46 +537,88 @@ std::optional<WallPaper> WallPaper::FromSerialized(
auto id = quint64();
auto accessHash = quint64();
auto ownerId = UserId();
auto flags = qint32();
auto slug = QString();
auto settings = qint32();
auto backgroundColor = quint32();
auto intensity = qint32();
auto versionTag = qint32();
auto version = qint32(0);
auto stream = QDataStream(serialized);
stream.setVersion(QDataStream::Qt_5_1);
stream
>> id
>> accessHash
>> flags
>> slug
>> settings
>> backgroundColor
>> intensity;
if (!stream.atEnd()) {
auto field1 = qint32();
auto field2 = qint32();
stream >> field1;
if (!stream.atEnd()) {
stream >> field2;
>> versionTag;
auto flags = qint32();
auto ownerId = UserId();
auto slug = QString();
auto blurred = qint32();
auto backgroundColors = std::vector<QColor>();
auto intensity = qint32();
auto rotation = qint32();
if (versionTag == kVersionTag) {
auto bareOwnerId = quint64();
auto backgroundColorsCount = qint32();
stream
>> version
>> flags
>> slug
>> blurred
>> backgroundColorsCount;
if (backgroundColorsCount < 0 || backgroundColorsCount > 4) {
return std::nullopt;
}
backgroundColors.reserve(backgroundColorsCount);
for (auto i = 0; i != backgroundColorsCount; ++i) {
auto serialized = quint32();
stream >> serialized;
const auto color = MaybeColorFromSerialized(serialized);
if (!color) {
return std::nullopt;
}
backgroundColors.push_back(*color);
}
stream
>> intensity
>> rotation
>> bareOwnerId;
ownerId = UserId(BareId(bareOwnerId));
} else {
auto settings = qint32();
auto backgroundColor = quint32();
stream
>> slug
>> settings
>> backgroundColor
>> intensity;
if (!stream.atEnd()) {
auto field1 = qint32();
auto field2 = qint32();
stream >> field1;
if (!stream.atEnd()) {
stream >> field2;
}
ownerId = UserId(
BareId(uint32(field1)) | (BareId(uint32(field2)) << 32));
}
flags = RawFromLegacyFlags(versionTag);
blurred = (settings & qint32(1U << 1)) ? 1 : 0;
if (const auto color = MaybeColorFromSerialized(backgroundColor)) {
backgroundColors.push_back(*color);
}
ownerId = UserId(
BareId(uint32(field1)) | (BareId(uint32(field2)) << 32));
}
if (stream.status() != QDataStream::Ok) {
return std::nullopt;
} else if (intensity < 0 || intensity > 100) {
} else if (intensity < -100 || intensity > 100) {
return std::nullopt;
}
auto result = WallPaper(id);
result._accessHash = accessHash;
result._ownerId = ownerId;
result._flags = MTPDwallPaper::Flags::from_raw(flags);
result._flags = WallPaperFlags::from_raw(flags);
result._slug = slug;
result._settings = MTPDwallPaperSettings::Flags::from_raw(settings);
result._backgroundColor = MaybeColorFromSerialized(backgroundColor);
result._blurred = (blurred == 1);
result._backgroundColors = std::move(backgroundColors);
result._intensity = intensity;
result._rotation = rotation;
return result;
}
@@ -450,28 +629,31 @@ std::optional<WallPaper> WallPaper::FromLegacySerialized(
QString slug) {
auto result = WallPaper(id);
result._accessHash = accessHash;
result._flags = MTPDwallPaper::Flags::from_raw(flags);
result._flags = WallPaperFlags::from_raw(RawFromLegacyFlags(flags));
result._slug = slug;
result._backgroundColor = ColorFromString(slug);
if (const auto color = ColorFromString(slug)) {
result._backgroundColors.push_back(*color);
}
return result;
}
std::optional<WallPaper> WallPaper::FromLegacyId(qint32 legacyId) {
auto result = WallPaper(FromLegacyBackgroundId(legacyId));
if (!IsCustomWallPaper(result)) {
result._flags = MTPDwallPaper::Flag::f_default;
result._flags = WallPaperFlag::Default;
}
return result;
}
std::optional<WallPaper> WallPaper::FromColorSlug(const QString &slug) {
if (const auto color = ColorFromString(slug)) {
auto result = CustomWallPaper();
result._slug = slug;
result._backgroundColor = color;
return result;
std::optional<WallPaper> WallPaper::FromColorsSlug(const QString &slug) {
auto colors = ColorsFromString(slug);
if (colors.empty()) {
return std::nullopt;
}
return std::nullopt;
auto result = CustomWallPaper();
result._slug = slug;
result._backgroundColors = std::move(colors);
return result;
}
WallPaper ThemeWallPaper() {
@@ -522,78 +704,54 @@ bool IsCloudWallPaper(const WallPaper &paper) {
&& !details::IsTestingEditorWallPaper(paper);
}
QColor PatternColor(QColor background) {
const auto hue = background.hueF();
const auto saturation = background.saturationF();
const auto value = background.valueF();
return QColor::fromHsvF(
hue,
std::min(1.0, saturation + 0.05 + 0.1 * (1. - saturation)),
(value > 0.5
? std::max(0., value * 0.65)
: std::max(0., std::min(1., 1. - value * 0.65))),
0.4
).toRgb();
QImage GenerateWallPaper(
QSize size,
const std::vector<QColor> &bg,
int gradientRotation,
float64 patternOpacity,
Fn<void(QPainter&)> drawPattern) {
auto result = bg.empty()
? Images::GenerateGradient(size, { DefaultBackgroundColor() })
: Images::GenerateGradient(size, bg, gradientRotation);
if (bg.size() > 1 && (!drawPattern || patternOpacity >= 0.)) {
result = Images::DitherImage(std::move(result));
}
if (drawPattern) {
auto p = QPainter(&result);
if (patternOpacity >= 0.) {
p.setCompositionMode(QPainter::CompositionMode_SoftLight);
p.setOpacity(patternOpacity);
} else {
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
}
drawPattern(p);
if (patternOpacity < 0. && patternOpacity > -1.) {
p.setCompositionMode(QPainter::CompositionMode_SourceOver);
p.setOpacity(1. + patternOpacity);
p.fillRect(QRect{ QPoint(), size }, Qt::black);
}
}
return std::move(result).convertToFormat(
QImage::Format_ARGB32_Premultiplied);
}
QImage PreparePatternImage(
QImage image,
QColor bg,
QColor fg,
int intensity) {
if (image.format() != QImage::Format_ARGB32_Premultiplied) {
image = std::move(image).convertToFormat(
QImage::Format_ARGB32_Premultiplied);
}
// Similar to ColorizePattern.
// But here we set bg to all 'alpha=0' pixels and fg to opaque ones.
QImage pattern,
const std::vector<QColor> &bg,
int gradientRotation,
float64 patternOpacity) {
auto result = GenerateWallPaper(
pattern.size(),
bg,
gradientRotation,
patternOpacity,
[&](QPainter &p) {
p.drawImage(QRect(QPoint(), pattern.size()), pattern);
});
const auto width = image.width();
const auto height = image.height();
const auto alpha = anim::interpolate(
0,
255,
fg.alphaF() * std::clamp(intensity / 100., 0., 1.));
if (!alpha) {
image.fill(bg);
return image;
}
fg.setAlpha(255);
const auto patternBg = anim::shifted(bg);
const auto patternFg = anim::shifted(fg);
constexpr auto resultIntsPerPixel = 1;
const auto resultIntsPerLine = (image.bytesPerLine() >> 2);
const auto resultIntsAdded = resultIntsPerLine - width * resultIntsPerPixel;
auto resultInts = reinterpret_cast<uint32*>(image.bits());
Assert(resultIntsAdded >= 0);
Assert(image.depth() == static_cast<int>((resultIntsPerPixel * sizeof(uint32)) << 3));
Assert(image.bytesPerLine() == (resultIntsPerLine << 2));
const auto maskBytesPerPixel = (image.depth() >> 3);
const auto maskBytesPerLine = image.bytesPerLine();
const auto maskBytesAdded = maskBytesPerLine - width * maskBytesPerPixel;
// We want to read the last byte of four available.
// This is the difference with style::colorizeImage.
auto maskBytes = image.constBits() + (maskBytesPerPixel - 1);
Assert(maskBytesAdded >= 0);
Assert(image.depth() == (maskBytesPerPixel << 3));
for (auto y = 0; y != height; ++y) {
for (auto x = 0; x != width; ++x) {
const auto maskOpacity = static_cast<anim::ShiftedMultiplier>(
*maskBytes) + 1;
const auto fgOpacity = (maskOpacity * alpha) >> 8;
const auto bgOpacity = 256 - fgOpacity;
*resultInts = anim::unshifted(
patternBg * bgOpacity + patternFg * fgOpacity);
maskBytes += maskBytesPerPixel;
resultInts += resultIntsPerPixel;
}
maskBytes += maskBytesAdded;
resultInts += resultIntsAdded;
}
return image;
pattern = QImage();
return result;
}
QImage PrepareBlurredBackground(QImage image) {
@@ -609,6 +767,30 @@ QImage PrepareBlurredBackground(QImage image) {
return Images::BlurLargeImage(image, kRadius);
}
QImage GenerateDitheredGradient(
const std::vector<QColor> &colors,
int rotation) {
constexpr auto kSize = 512;
const auto size = QSize(kSize, kSize);
if (colors.empty()) {
return Images::GenerateGradient(size, { DefaultBackgroundColor() });
}
auto result = Images::GenerateGradient(size, colors, rotation);
if (colors.size() > 1) {
result = Images::DitherImage(std::move(result));
}
return result;
}
QImage GenerateDitheredGradient(const Data::WallPaper &paper) {
if (paper.backgroundColors().empty()) {
return GenerateDitheredGradient({ DefaultBackgroundColor() }, 0);
}
return GenerateDitheredGradient(
paper.backgroundColors(),
paper.gradientRotation());
}
namespace details {
WallPaper UninitializedWallPaper() {

View File

@@ -7,6 +7,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#pragma once
#include "base/flags.h"
class Image;
namespace Main {
@@ -17,6 +19,15 @@ namespace Data {
struct FileOrigin;
enum class WallPaperFlag {
Pattern = (1 << 0),
Default = (1 << 1),
Creator = (1 << 2),
Dark = (1 << 3),
};
inline constexpr bool is_flag_type(WallPaperFlag) { return true; };
using WallPaperFlags = base::flags<WallPaperFlag>;
class WallPaper {
public:
explicit WallPaper(WallPaperId id);
@@ -25,6 +36,7 @@ public:
[[nodiscard]] WallPaperId id() const;
[[nodiscard]] std::optional<QColor> backgroundColor() const;
[[nodiscard]] const std::vector<QColor> backgroundColors() const;
[[nodiscard]] DocumentData *document() const;
[[nodiscard]] Image *localThumbnail() const;
[[nodiscard]] bool isPattern() const;
@@ -34,6 +46,8 @@ public:
[[nodiscard]] bool isLocal() const;
[[nodiscard]] bool isBlurred() const;
[[nodiscard]] int patternIntensity() const;
[[nodiscard]] float64 patternOpacity() const;
[[nodiscard]] int gradientRotation() const;
[[nodiscard]] bool hasShareUrl() const;
[[nodiscard]] QString shareUrl(not_null<Main::Session*> session) const;
@@ -50,7 +64,9 @@ public:
const QMap<QString, QString> &params) const;
[[nodiscard]] WallPaper withBlurred(bool blurred) const;
[[nodiscard]] WallPaper withPatternIntensity(int intensity) const;
[[nodiscard]] WallPaper withBackgroundColor(QColor color) const;
[[nodiscard]] WallPaper withGradientRotation(int rotation) const;
[[nodiscard]] WallPaper withBackgroundColors(
std::vector<QColor> colors) const;
[[nodiscard]] WallPaper withParamsFrom(const WallPaper &other) const;
[[nodiscard]] WallPaper withoutImageData() const;
@@ -60,6 +76,8 @@ public:
[[nodiscard]] static std::optional<WallPaper> Create(
not_null<Main::Session*> session,
const MTPDwallPaper &data);
[[nodiscard]] static std::optional<WallPaper> Create(
const MTPDwallPaperNoFile &data);
[[nodiscard]] QByteArray serialize() const;
[[nodiscard]] static std::optional<WallPaper> FromSerialized(
@@ -71,21 +89,22 @@ public:
QString slug);
[[nodiscard]] static std::optional<WallPaper> FromLegacyId(
qint32 legacyId);
[[nodiscard]] static std::optional<WallPaper> FromColorSlug(
[[nodiscard]] static std::optional<WallPaper> FromColorsSlug(
const QString &slug);
private:
static constexpr auto kDefaultIntensity = 40;
static constexpr auto kDefaultIntensity = 50;
WallPaperId _id = WallPaperId();
uint64 _accessHash = 0;
UserId _ownerId = 0;
MTPDwallPaper::Flags _flags;
WallPaperFlags _flags;
QString _slug;
MTPDwallPaperSettings::Flags _settings;
std::optional<QColor> _backgroundColor;
std::vector<QColor> _backgroundColors;
int _rotation = 0;
int _intensity = kDefaultIntensity;
bool _blurred = false;
DocumentData *_document = nullptr;
std::shared_ptr<Image> _thumbnail;
@@ -103,13 +122,22 @@ private:
[[nodiscard]] bool IsDefaultWallPaper(const WallPaper &paper);
[[nodiscard]] bool IsCloudWallPaper(const WallPaper &paper);
QColor PatternColor(QColor background);
QImage PreparePatternImage(
QImage image,
QColor bg,
QColor fg,
int intensity);
QImage PrepareBlurredBackground(QImage image);
[[nodiscard]] QImage GenerateWallPaper(
QSize size,
const std::vector<QColor> &bg,
int gradientRotation,
float64 patternOpacity = 1.,
Fn<void(QPainter&)> drawPattern = nullptr);
[[nodiscard]] QImage PreparePatternImage(
QImage pattern,
const std::vector<QColor> &bg,
int gradientRotation,
float64 patternOpacity);
[[nodiscard]] QImage PrepareBlurredBackground(QImage image);
[[nodiscard]] QImage GenerateDitheredGradient(
const std::vector<QColor> &colors,
int rotation);
[[nodiscard]] QImage GenerateDitheredGradient(const WallPaper &paper);
namespace details {

View File

@@ -12,7 +12,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_file_origin.h"
#include "storage/file_download.h"
#include "ui/image/image.h"
#include "app.h"
namespace Data {
@@ -28,7 +27,7 @@ not_null<StickersSet*> StickersSetThumbnailView::owner() const {
void StickersSetThumbnailView::set(
not_null<Main::Session*> session,
QByteArray content) {
auto image = App::readImage(content, nullptr, false);
auto image = Images::Read({ .content = content }).image;
if (image.isNull()) {
_content = std::move(content);
} else {

View File

@@ -18,7 +18,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "main/main_session_settings.h"
#include "history/history_item.h"
#include "history/history.h"
#include "app.h"
#include "styles/style_dialogs.h" // st::dialogsTextWidthMin
namespace Dialogs {

View File

@@ -118,10 +118,7 @@ InnerWidget::InnerWidget(
})
, _cancelSearchInChat(this, st::dialogsCancelSearchInPeer)
, _cancelSearchFromUser(this, st::dialogsCancelSearchInPeer) {
#ifndef OS_MAC_OLD // Qt 5.3.2 build is working with glitches otherwise.
setAttribute(Qt::WA_OpaquePaintEvent, true);
#endif // OS_MAC_OLD
_cancelSearchInChat->setClickedCallback([=] { cancelSearchInChat(); });
_cancelSearchInChat->hide();

View File

@@ -164,7 +164,7 @@ void Widget::BottomButton::paintEvent(QPaintEvent *e) {
Widget::Widget(
QWidget *parent,
not_null<Window::SessionController*> controller)
: Window::AbstractSectionWidget(parent, controller)
: Window::AbstractSectionWidget(parent, controller, PaintedBackground::Custom)
, _api(&controller->session().mtp())
, _searchControls(this)
, _mainMenuToggle(_searchControls, st::dialogsMenuToggle)

View File

@@ -7,7 +7,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "editor/photo_editor_layer_widget.h"
#include "app.h" // readImage
#include "boxes/confirm_box.h" // InformBox
#include "editor/photo_editor.h"
#include "storage/storage_media_prepare.h"
@@ -80,9 +79,11 @@ void PrepareProfilePhoto(
return;
}
auto image = result.remoteContent.isEmpty()
? App::readImage(result.paths.front())
: App::readImage(result.remoteContent);
auto image = Images::Read({
.path = result.paths.isEmpty() ? QString() : result.paths.front(),
.content = result.remoteContent,
.forceOpaque = true,
}).image;
if (image.isNull()
|| (image.width() > (10 * image.height()))
|| (image.height() > (10 * image.width()))) {

View File

@@ -895,9 +895,7 @@ void InnerWidget::paintEvent(QPaintEvent *e) {
Painter p(this);
auto ms = crl::now();
auto clip = e->rect();
if (_items.empty() && _upLoaded && _downLoaded) {
paintEmpty(p);
} else {
@@ -914,16 +912,26 @@ void InnerWidget::paintEvent(QPaintEvent *e) {
return this->itemTop(elem) < bottom;
});
if (from != end) {
auto viewport = QRect(); // #TODO bubbles
auto top = itemTop(from->get());
auto context = HistoryView::PaintContext{
.bubblesPattern = nullptr,
.viewport = viewport.translated(0, -top),
.clip = clip.translated(0, -top),
.now = crl::now(),
};
p.translate(0, top);
for (auto i = from; i != to; ++i) {
const auto view = i->get();
const auto selection = (view == _selectedItem)
context.selection = (view == _selectedItem)
? _selectedText
: TextSelection();
view->draw(p, clip.translated(0, -top), selection, ms);
auto height = view->height();
view->draw(p, context);
const auto height = view->height();
top += height;
context.viewport.translate(0, -height);
context.clip.translate(0, -height);
p.translate(0, height);
}
p.translate(0, -top);

View File

@@ -275,11 +275,14 @@ Widget::Widget(
QWidget *parent,
not_null<Window::SessionController*> controller,
not_null<ChannelData*> channel)
: Window::SectionWidget(parent, controller)
: Window::SectionWidget(parent, controller, PaintedBackground::Section)
, _scroll(this, st::historyScroll, false)
, _fixedBar(this, controller, channel)
, _fixedBarShadow(this)
, _whatIsThis(this, tr::lng_admin_log_about(tr::now).toUpper(), st::historyComposeButton) {
, _whatIsThis(
this,
tr::lng_admin_log_about(tr::now).toUpper(),
st::historyComposeButton) {
_fixedBar->move(0, 0);
_fixedBar->resizeToWidth(width());
_fixedBar->showFilterRequests(
@@ -303,6 +306,11 @@ Widget::Widget(
updateAdaptiveLayout();
}, lifetime());
controller->repaintBackgroundRequests(
) | rpl::start_with_next([=] {
update();
}, lifetime());
_inner = _scroll->setOwnedWidget(object_ptr<InnerWidget>(this, controller, channel));
_inner->showSearchSignal(
) | rpl::start_with_next([=] {

View File

@@ -1631,7 +1631,16 @@ void History::setUnreadCount(int newUnreadCount) {
const auto notifier = unreadStateChangeNotifier(true);
_unreadCount = newUnreadCount;
if (newUnreadCount == 1) {
const auto lastOutgoing = [&] {
const auto last = lastMessage();
return last
&& IsServerMsgId(last->id)
&& loadedAtBottom()
&& !isEmpty()
&& blocks.back()->messages.back()->data() == last
&& last->out();
}();
if (newUnreadCount == 1 && !lastOutgoing) {
if (loadedAtBottom()) {
_firstUnreadView = !isEmpty()
? blocks.back()->messages.back().get()

View File

@@ -560,7 +560,6 @@ void HistoryInner::paintEvent(QPaintEvent *e) {
Painter p(this);
auto clip = e->rect();
auto ms = crl::now();
const auto historyDisplayedEmpty = _history->isDisplayedEmpty()
&& (!_migrated || _migrated->isDisplayedEmpty());
@@ -602,6 +601,8 @@ void HistoryInner::paintEvent(QPaintEvent *e) {
} else {
seltoy += _dragSelTo->height();
}
const auto visibleAreaTopGlobal = mapToGlobal(
QPoint(0, _visibleAreaTop)).y();
auto mtop = migratedTop();
auto htop = historyTop();
@@ -613,15 +614,19 @@ void HistoryInner::paintEvent(QPaintEvent *e) {
auto view = block->messages[iItem].get();
auto item = view->data();
auto y = mtop + block->y() + view->y();
p.save();
p.translate(0, y);
if (clip.y() < y + view->height()) while (y < drawToY) {
const auto selection = itemRenderSelection(
auto top = mtop + block->y() + view->y();
auto context = _controller->bubblesContext({
.visibleAreaTop = _visibleAreaTop,
.visibleAreaTopGlobal = visibleAreaTopGlobal,
.clip = clip,
}).translated(0, -top);
p.translate(0, top);
if (context.clip.y() < view->height()) while (top < drawToY) {
context.selection = itemRenderSelection(
view,
selfromy - mtop,
seltoy - mtop);
view->draw(p, clip.translated(0, -y), selection, ms);
view->draw(p, context);
if (item->hasViews()) {
_controller->content()->scheduleViewIncrement(item);
@@ -631,9 +636,10 @@ void HistoryInner::paintEvent(QPaintEvent *e) {
_widget->enqueueMessageHighlight(view);
}
int32 h = view->height();
p.translate(0, h);
y += h;
const auto height = view->height();
top += height;
context.translate(0, -height);
p.translate(0, height);
++iItem;
if (iItem == block->messages.size()) {
@@ -647,7 +653,7 @@ void HistoryInner::paintEvent(QPaintEvent *e) {
view = block->messages[iItem].get();
item = view->data();
}
p.restore();
p.translate(0, -top);
}
if (htop >= 0) {
auto iBlock = (_curHistory == _history ? _curBlock : 0);
@@ -656,21 +662,27 @@ void HistoryInner::paintEvent(QPaintEvent *e) {
auto view = block->messages[iItem].get();
auto item = view->data();
auto readTill = (HistoryItem*)nullptr;
auto hclip = clip.intersected(QRect(0, hdrawtop, width(), clip.top() + clip.height()));
auto y = htop + block->y() + view->y();
p.save();
p.translate(0, y);
while (y < drawToY) {
const auto h = view->height();
if (hclip.y() < y + h && hdrawtop < y + h) {
const auto selection = itemRenderSelection(
auto top = htop + block->y() + view->y();
auto context = _controller->bubblesContext({
.visibleAreaTop = _visibleAreaTop,
.visibleAreaTopGlobal = visibleAreaTopGlobal,
.visibleAreaWidth = width(),
.clip = clip.intersected(
QRect(0, hdrawtop, width(), clip.top() + clip.height())
),
}).translated(0, -top);
p.translate(0, top);
while (top < drawToY) {
const auto height = view->height();
if (context.clip.y() < height && hdrawtop < top + height) {
context.selection = itemRenderSelection(
view,
selfromy - htop,
seltoy - htop);
view->draw(p, hclip.translated(0, -y), selection, ms);
view->draw(p, context);
const auto middle = y + h / 2;
const auto bottom = y + h;
const auto middle = top + height / 2;
const auto bottom = top + height;
if (_visibleAreaBottom >= bottom) {
const auto item = view->data();
if (!item->out() && item->unread()) {
@@ -688,8 +700,9 @@ void HistoryInner::paintEvent(QPaintEvent *e) {
}
}
}
p.translate(0, h);
y += h;
top += height;
context.translate(0, -height);
p.translate(0, height);
++iItem;
if (iItem == block->messages.size()) {
@@ -703,7 +716,7 @@ void HistoryInner::paintEvent(QPaintEvent *e) {
view = block->messages[iItem].get();
item = view->data();
}
p.restore();
p.translate(0, -top);
if (readTill && _widget->doWeReadServerHistory()) {
session().data().histories().readInboxTill(readTill);
@@ -3168,6 +3181,10 @@ void HistoryInner::addToSelection(
not_null<HistoryItem*> item) const {
const auto i = toItems->find(item);
if (i == toItems->cend()) {
if (toItems->size() == 1
&& toItems->begin()->second != FullSelection) {
toItems->clear();
}
toItems->emplace(item, FullSelection);
} else if (i->second != FullSelection) {
i->second = FullSelection;

View File

@@ -1059,6 +1059,7 @@ MessageFlags FlagsFromMTP(MTPDmessage::Flags flags) {
| ((flags & MTP::f_via_bot_id) ? Flag::HasViaBot : Flag())
| ((flags & MTP::f_reply_to) ? Flag::HasReplyInfo : Flag())
| ((flags & MTP::f_reply_markup) ? Flag::HasReplyMarkup : Flag())
| ((flags & MTP::f_from_scheduled) ? Flag::IsOrWasScheduled : Flag())
| ((flags & MTP::f_views) ? Flag::HasViews : Flag());
}

View File

@@ -45,7 +45,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "data/data_channel.h"
#include "data/data_user.h"
#include "data/data_histories.h"
#include "app.h"
#include "styles/style_dialogs.h"
#include "styles/style_widgets.h"
#include "styles/style_chat.h"
@@ -563,8 +562,14 @@ HistoryMessage::HistoryMessage(
auto config = CreateConfig();
if (original->Has<HistoryMessageForwarded>() || !original->history()->peer->isSelf()) {
// Server doesn't add "fwd_from" to non-forwarded messages from chat with yourself.
const auto originalMedia = original->media();
const auto dropForwardInfo = (originalMedia
&& originalMedia->dropForwardedInfo())
|| (original->history()->peer->isSelf()
&& !history->peer->isSelf()
&& !original->Has<HistoryMessageForwarded>()
&& (!originalMedia || !originalMedia->forceForwardedInfo()));
if (!dropForwardInfo) {
config.originalDate = original->dateOriginal();
if (const auto info = original->hiddenForwardedInfo()) {
config.senderNameOriginal = info->name;
@@ -596,6 +601,14 @@ HistoryMessage::HistoryMessage(
}
if (const auto fwdViaBot = original->viaBot()) {
config.viaBotId = peerToUser(fwdViaBot->id);
} else if (originalMedia && originalMedia->game()) {
if (const auto sender = original->senderOriginal()) {
if (const auto user = sender->asUser()) {
if (user->isBot()) {
config.viaBotId = peerToUser(user->id);
}
}
}
}
const auto fwdViewsCount = original->viewsCount();
if (fwdViewsCount > 0) {

View File

@@ -88,7 +88,6 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "chat_helpers/bot_keyboard.h"
#include "chat_helpers/message_field.h"
#include "chat_helpers/send_context_menu.h"
#include "platform/platform_specific.h"
#include "mtproto/mtproto_config.h"
#include "lang/lang_keys.h"
#include "mainwidget.h"
@@ -172,7 +171,7 @@ const auto kPsaAboutPrefix = "cloud_lng_about_psa_";
HistoryWidget::HistoryWidget(
QWidget *parent,
not_null<Window::SessionController*> controller)
: Window::AbstractSectionWidget(parent, controller)
: Window::AbstractSectionWidget(parent, controller, PaintedBackground::Section)
, _api(&controller->session().mtp())
, _updateEditTimeLeftDisplay([=] { updateField(); })
, _fieldBarCancel(this, st::historyReplyCancel)
@@ -310,6 +309,9 @@ HistoryWidget::HistoryWidget(
_historyDown->installEventFilter(this);
_unreadMentions->installEventFilter(this);
SendMenu::SetupUnreadMentionsMenu(_unreadMentions.data(), [=] {
return _history ? _history->peer.get() : nullptr;
});
InitMessageField(controller, _field);
@@ -430,6 +432,11 @@ HistoryWidget::HistoryWidget(
}
}, lifetime());
controller->repaintBackgroundRequests(
) | rpl::start_with_next([=] {
update();
}, lifetime());
session().data().newItemAdded(
) | rpl::start_with_next([=](not_null<HistoryItem*> item) {
newItemAdded(item);
@@ -3541,15 +3548,12 @@ void HistoryWidget::chooseAttach() {
}
if (!result.remoteContent.isEmpty()) {
auto animated = false;
auto image = App::readImage(
result.remoteContent,
nullptr,
false,
&animated);
if (!image.isNull() && !animated) {
auto read = Images::Read({
.content = result.remoteContent,
});
if (!read.image.isNull() && !read.animated) {
confirmSendingFiles(
std::move(image),
std::move(read.image),
std::move(result.remoteContent));
} else {
uploadFile(result.remoteContent, SendMediaType::File);
@@ -4494,10 +4498,7 @@ bool HistoryWidget::confirmSendingFiles(
}
if (hasImage) {
auto image = Platform::GetImageFromClipboard();
if (image.isNull()) {
image = qvariant_cast<QImage>(data->imageData());
}
auto image = qvariant_cast<QImage>(data->imageData());
if (!image.isNull()) {
confirmSendingFiles(
std::move(image),
@@ -4928,6 +4929,9 @@ void HistoryWidget::startItemRevealAnimations() {
1.,
HistoryView::ListWidget::kItemRevealDuration,
anim::easeOutCirc);
if (item->out() || _history->peer->isSelf()) {
controller()->rotateComplexGradientBackground();
}
}
}
}
@@ -6263,11 +6267,7 @@ void HistoryWidget::updatePreview() {
st::msgNameStyle,
tr::lng_preview_loading(tr::now),
Ui::NameTextOptions());
#ifndef OS_MAC_OLD
auto linkText = _previewLinks.splitRef(' ').at(0).toString();
#else // OS_MAC_OLD
auto linkText = _previewLinks.split(' ').at(0);
#endif // OS_MAC_OLD
_previewDescription.setText(
st::messageTextStyle,
TextUtilities::Clean(linkText),
@@ -6977,6 +6977,10 @@ void HistoryWidget::synteticScrollToY(int y) {
HistoryWidget::~HistoryWidget() {
if (_history) {
// Saving a draft on account switching.
saveFieldToHistoryLocalDraft();
session().api().saveDraftToCloudDelayed(_history);
clearAllLoadRequests();
}
setTabbedPanel(nullptr);

View File

@@ -1086,13 +1086,15 @@ void ComposeControls::initKeyHandler() {
auto keyEvent = static_cast<QKeyEvent*>(e.get());
const auto key = keyEvent->key();
const auto isCtrl = keyEvent->modifiers() == Qt::ControlModifier;
const auto hasModifiers = keyEvent->modifiers() != Qt::NoModifier;
const auto hasModifiers = (Qt::NoModifier !=
(keyEvent->modifiers()
& ~(Qt::KeypadModifier | Qt::GroupSwitchModifier)));
if (key == Qt::Key_O && isCtrl) {
_attachRequests.fire({});
return;
}
if (key == Qt::Key_Up && !hasModifiers) {
if (!isEditingMessage()) {
if (!isEditingMessage() && _field->empty()) {
_editLastMessageRequests.fire(std::move(keyEvent));
return;
}

View File

@@ -24,6 +24,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
#include "window/window_controller.h"
#include "window/window_session_controller.h"
#include "apiwrap.h"
#include "api/api_blocked_peers.h"
#include "main/main_session.h"
#include "boxes/confirm_box.h"
#include "boxes/peers/edit_contact_box.h"
@@ -393,7 +394,7 @@ void ContactStatus::setupReportHandler(not_null<PeerData*> peer) {
_controller->showBackFromStack();
});
if (const auto user = peer->asUser()) {
peer->session().api().blockPeer(user);
peer->session().api().blockedPeers().block(user);
}
const auto text = ((peer->isChat() || peer->isMegagroup())
? tr::lng_report_spam_sure_group

View File

@@ -24,6 +24,7 @@ class SessionController;
namespace Ui {
class PathShiftGradient;
struct BubblePattern;
} // namespace Ui
namespace HistoryView {
@@ -191,6 +192,30 @@ struct DateBadge : public RuntimeComponent<DateBadge, Element> {
};
struct PaintContext {
const Ui::BubblePattern *bubblesPattern = nullptr;
QRect viewport;
QRect clip;
TextSelection selection;
crl::time now = 0;
void translate(int x, int y) {
viewport.translate(x, y);
clip.translate(x, y);
}
void translate(QPoint point) {
translate(point.x(), point.y());
}
[[nodiscard]] PaintContext translated(int x, int y) const {
auto result = *this;
result.translate(x, y);
return result;
}
[[nodiscard]] PaintContext translated(QPoint point) const {
return translated(point.x(), point.y());
}
};
class Element
: public Object
, public RuntimeComposer<Element>
@@ -261,11 +286,7 @@ public:
bool displayDate() const;
bool isInOneDayWithPrevious() const;
virtual void draw(
Painter &p,
QRect clip,
TextSelection selection,
crl::time ms) const = 0;
virtual void draw(Painter &p, const PaintContext &context) const = 0;
[[nodiscard]] virtual PointState pointState(QPoint point) const = 0;
[[nodiscard]] virtual TextState textState(
QPoint point,

View File

@@ -1444,6 +1444,9 @@ void ListWidget::startItemRevealAnimations() {
1.,
kItemRevealDuration,
anim::easeOutCirc);
if (view->data()->out()) {
controller()->rotateComplexGradientBackground();
}
}
}
}
@@ -1609,17 +1612,22 @@ void ListWidget::paintEvent(QPaintEvent *e) {
return this->itemTop(elem) < bottom;
});
if (from != end(_items)) {
auto viewport = QRect(); // #TODO bubbles
auto top = itemTop(from->get());
auto context = HistoryView::PaintContext{
.bubblesPattern = nullptr,
.viewport = viewport.translated(0, -top),
.clip = clip.translated(0, -top),
.now = crl::now(),
};
p.translate(0, top);
for (auto i = from; i != to; ++i) {
const auto view = *i;
view->draw(
p,
clip.translated(0, -top),
itemRenderSelection(view),
ms);
view->draw(p, context);
const auto height = view->height();
top += height;
context.viewport.translate(0, -height);
context.clip.translate(0, -height);
p.translate(0, height);
}
p.translate(0, -top);

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